title
stringlengths
1
185
diff
stringlengths
0
32.2M
body
stringlengths
0
123k
url
stringlengths
57
58
created_at
stringlengths
20
20
closed_at
stringlengths
20
20
merged_at
stringlengths
20
20
updated_at
stringlengths
20
20
BUG: fix+test DTA/TDA/PA add/sub Index
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 47b138a9e1604..9f3249e14d851 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1216,7 +1216,7 @@ def _time_shift(self, periods, freq=None): def __add__(self, other): other = lib.item_from_zerodim(other) - if isinstance(other, (ABCSeries, ABCDataFrame)): + if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)): return NotImplemented # scalar others @@ -1282,7 +1282,7 @@ def __radd__(self, other): def __sub__(self, other): other = lib.item_from_zerodim(other) - if isinstance(other, (ABCSeries, ABCDataFrame)): + if isinstance(other, (ABCSeries, ABCDataFrame, ABCIndexClass)): return NotImplemented # scalar others @@ -1349,7 +1349,7 @@ def __sub__(self, other): return result def __rsub__(self, other): - if is_datetime64_dtype(other) and is_timedelta64_dtype(self): + if is_datetime64_any_dtype(other) and is_timedelta64_dtype(self): # ndarray[datetime64] cannot be subtracted from self, so # we need to wrap in DatetimeArray/Index and flip the operation if not isinstance(other, DatetimeLikeArrayMixin): diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index cca6836acf626..0e01216af9ec0 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -2249,6 +2249,23 @@ def test_add_datetimelike_and_dti(self, addend, tz): # ------------------------------------------------------------- + def test_dta_add_sub_index(self, tz_naive_fixture): + # Check that DatetimeArray defers to Index classes + dti = date_range("20130101", periods=3, tz=tz_naive_fixture) + dta = dti.array + result = dta - dti + expected = dti - dti + tm.assert_index_equal(result, expected) + + tdi = result + result = dta + tdi + expected = dti + tdi + tm.assert_index_equal(result, expected) + + result = dta - tdi + expected = dti - tdi + tm.assert_index_equal(result, expected) + def test_sub_dti_dti(self): # previously performed setop (deprecated in 0.16.0), now changed to # return subtraction -> TimeDeltaIndex (GH ...) @@ -2554,6 +2571,7 @@ def test_shift_months(years, months): tm.assert_index_equal(actual, expected) +# FIXME: this belongs in scalar tests class SubDatetime(datetime): pass diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index c1b32e8b13442..4b58c290c3cea 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -1041,6 +1041,18 @@ def test_parr_add_sub_tdt64_nat_array(self, box_df_fail, other): with pytest.raises(TypeError): other - obj + # --------------------------------------------------------------- + # Unsorted + + def test_parr_add_sub_index(self): + # Check that PeriodArray defers to Index on arithmetic ops + pi = pd.period_range("2000-12-31", periods=3) + parr = pi.array + + result = parr - pi + expected = pi - pi + tm.assert_index_equal(result, expected) + class TestPeriodSeriesArithmetic: def test_ops_series_timedelta(self): diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 326c565308124..4f5e00bc5a37d 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -480,6 +480,25 @@ def test_timedelta(self, freq): tm.assert_index_equal(result1, result4) tm.assert_index_equal(result2, result3) + def test_tda_add_sub_index(self): + # Check that TimedeltaArray defers to Index on arithmetic ops + tdi = TimedeltaIndex(["1 days", pd.NaT, "2 days"]) + tda = tdi.array + + dti = pd.date_range("1999-12-31", periods=3, freq="D") + + result = tda + dti + expected = tdi + dti + tm.assert_index_equal(result, expected) + + result = tda + tdi + expected = tdi + tdi + tm.assert_index_equal(result, expected) + + result = tda - tdi + expected = tdi - tdi + tm.assert_index_equal(result, expected) + class TestAddSubNaTMasking: # TODO: parametrize over boxes
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Looking forward to doing a couple of test-cleanup passes.
https://api.github.com/repos/pandas-dev/pandas/pulls/27726
2019-08-02T23:27:33Z
2019-08-05T11:45:25Z
2019-08-05T11:45:25Z
2019-08-05T14:28:54Z
STYLE: Add flake8-comprehensions to pre-commit configuration
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 5f7143ef518bb..32ffb3330564c 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -9,6 +9,7 @@ repos: hooks: - id: flake8 language: python_venv + additional_dependencies: [flake8-comprehensions] - repo: https://github.com/pre-commit/mirrors-isort rev: v4.3.20 hooks:
- [x] closes #27724 Running `pre-commit` with this change catches the error described in the issue.
https://api.github.com/repos/pandas-dev/pandas/pulls/27725
2019-08-02T22:19:58Z
2019-08-04T21:38:54Z
2019-08-04T21:38:53Z
2019-08-05T18:39:39Z
CLN: collected cleanups from other branches
diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index f704ceffa662e..7424c4ddc3d92 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -47,10 +47,6 @@ cpdef get_value_at(ndarray arr, object loc, object tz=None): return util.get_value_at(arr, loc) -def get_value_box(arr: ndarray, loc: object) -> object: - return get_value_at(arr, loc, tz=None) - - # Don't populate hash tables in monotonic indexes larger than this _SIZE_CUTOFF = 1000000 diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 39529177b9e35..667fb4501ed95 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -125,7 +125,11 @@ def __init__(self, values, copy=False): if isinstance(values, type(self)): values = values._ndarray if not isinstance(values, np.ndarray): - raise ValueError("'values' must be a NumPy array.") + raise ValueError( + "'values' must be a NumPy array, not {typ}".format( + typ=type(values).__name__ + ) + ) if values.ndim != 1: raise ValueError("PandasArray must be 1-dimensional.") diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index afd1e8203059e..ec4419b02d8b1 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -173,8 +173,8 @@ class TimedeltaArray(dtl.DatetimeLikeArrayMixin, dtl.TimelikeOps): "ceil", ] - # Needed so that NaT.__richcmp__(DateTimeArray) operates pointwise - ndim = 1 + # Note: ndim must be defined to ensure NaT.__richcmp(TimedeltaArray) + # operates pointwise. @property def _box_func(self): diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 2271ff643bc15..d93a95931dcc1 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4713,7 +4713,7 @@ def get_value(self, series, key): raise try: - return libindex.get_value_box(s, key) + return libindex.get_value_at(s, key) except IndexError: raise except TypeError: diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 6a2aebe5db246..9f3aa699cfaf4 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -434,7 +434,7 @@ def f(m, v, i): return self.split_and_operate(mask, f, inplace) - def split_and_operate(self, mask, f, inplace): + def split_and_operate(self, mask, f, inplace: bool): """ split the block per-column, and apply the callable f per-column, return a new block for each. Handle @@ -493,17 +493,15 @@ def make_a_block(nv, ref_loc): return new_blocks - def _maybe_downcast(self, blocks, downcast=None): + def _maybe_downcast(self, blocks: List["Block"], downcast=None) -> List["Block"]: # no need to downcast our float # unless indicated - if downcast is None and self.is_float: - return blocks - elif downcast is None and (self.is_timedelta or self.is_datetime): + if downcast is None and ( + self.is_float or self.is_timedelta or self.is_datetime + ): return blocks - if not isinstance(blocks, list): - blocks = [blocks] return _extend_blocks([b.downcast(downcast) for b in blocks]) def downcast(self, dtypes=None): @@ -1343,7 +1341,15 @@ def shift(self, periods, axis=0, fill_value=None): return [self.make_block(new_values)] - def where(self, other, cond, align=True, errors="raise", try_cast=False, axis=0): + def where( + self, + other, + cond, + align=True, + errors="raise", + try_cast: bool = False, + axis: int = 0, + ) -> List["Block"]: """ evaluate the block; return result block(s) from the result @@ -1442,7 +1448,7 @@ def func(cond, values, other): if try_cast: result = self._try_cast_result(result) - return self.make_block(result) + return [self.make_block(result)] # might need to separate out blocks axis = cond.ndim - 1 @@ -1474,9 +1480,9 @@ def _unstack(self, unstacker_func, new_columns, n_rows, fill_value): new_columns : Index All columns of the unstacked BlockManager. n_rows : int - Only used in ExtensionBlock.unstack + Only used in ExtensionBlock._unstack fill_value : int - Only used in ExtensionBlock.unstack + Only used in ExtensionBlock._unstack Returns ------- @@ -1550,7 +1556,7 @@ def quantile(self, qs, interpolation="linear", axis=0): result = result[..., 0] result = lib.item_from_zerodim(result) - ndim = getattr(result, "ndim", None) or 0 + ndim = np.ndim(result) return make_block(result, placement=np.arange(len(result)), ndim=ndim) def _replace_coerce( @@ -1923,7 +1929,15 @@ def shift( ) ] - def where(self, other, cond, align=True, errors="raise", try_cast=False, axis=0): + def where( + self, + other, + cond, + align=True, + errors="raise", + try_cast: bool = False, + axis: int = 0, + ) -> List["Block"]: if isinstance(other, ABCDataFrame): # ExtensionArrays are 1-D, so if we get here then # `other` should be a DataFrame with a single column. @@ -1968,7 +1982,7 @@ def where(self, other, cond, align=True, errors="raise", try_cast=False, axis=0) np.where(cond, self.values, other), dtype=dtype ) - return self.make_block_same_class(result, placement=self.mgr_locs) + return [self.make_block_same_class(result, placement=self.mgr_locs)] @property def _ftype(self): @@ -2706,7 +2720,7 @@ def f(m, v, i): return blocks - def _maybe_downcast(self, blocks, downcast=None): + def _maybe_downcast(self, blocks: List["Block"], downcast=None) -> List["Block"]: if downcast is not None: return blocks @@ -3031,7 +3045,15 @@ def concat_same_type(self, to_concat, placement=None): values, placement=placement or slice(0, len(values), 1), ndim=self.ndim ) - def where(self, other, cond, align=True, errors="raise", try_cast=False, axis=0): + def where( + self, + other, + cond, + align=True, + errors="raise", + try_cast: bool = False, + axis: int = 0, + ) -> List["Block"]: # TODO(CategoricalBlock.where): # This can all be deleted in favor of ExtensionBlock.where once # we enforce the deprecation. diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index e5acd23b77d5d..b30ddbc383906 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1823,7 +1823,7 @@ def _simple_blockify(tuples, dtype): """ values, placement = _stack_arrays(tuples, dtype) - # CHECK DTYPE? + # TODO: CHECK DTYPE? if dtype is not None and values.dtype != dtype: # pragma: no cover values = values.astype(dtype) diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 66878c3b1026c..a5d0e2cb3b58f 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -1630,15 +1630,14 @@ def _get_period_bins(self, ax): def _take_new_index(obj, indexer, new_index, axis=0): - from pandas.core.api import Series, DataFrame - if isinstance(obj, Series): + if isinstance(obj, ABCSeries): new_values = algos.take_1d(obj.values, indexer) - return Series(new_values, index=new_index, name=obj.name) - elif isinstance(obj, DataFrame): + return obj._constructor(new_values, index=new_index, name=obj.name) + elif isinstance(obj, ABCDataFrame): if axis == 1: raise NotImplementedError("axis 1 is not supported") - return DataFrame( + return obj._constructor( obj._data.reindex_indexer(new_axis=new_index, indexer=indexer, axis=1) ) else: diff --git a/pandas/core/window.py b/pandas/core/window.py index 4b6a1cf2e9a04..a7425bc1466c3 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -265,6 +265,8 @@ def _wrap_result(self, result, block=None, obj=None): # coerce if necessary if block is not None: if is_timedelta64_dtype(block.values.dtype): + # TODO: do we know what result.dtype is at this point? + # i.e. can we just do an astype? from pandas import to_timedelta result = to_timedelta(result.ravel(), unit="ns").values.reshape( diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 9b8c8e6d8a077..ce724f5a60beb 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -506,7 +506,7 @@ def test_datetime(): desc_result = grouped.describe() idx = cats.codes.argsort() - ord_labels = cats.take_nd(idx) + ord_labels = cats.take(idx) ord_data = data.take(idx) expected = ord_data.groupby(ord_labels, observed=False).describe() assert_frame_equal(desc_result, expected)
https://api.github.com/repos/pandas-dev/pandas/pulls/27723
2019-08-02T21:41:51Z
2019-08-05T15:52:45Z
2019-08-05T15:52:45Z
2019-08-05T16:37:58Z
BUG: fix replace_list
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index c80195af413f7..a4e792091cb4b 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -152,7 +152,7 @@ ExtensionArray Other ^^^^^ - +- Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` when replacing timezone-aware timestamps using a dict-like replacer (:issue:`27720`) - - - diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 821c35e0cce2f..2b783e3e7aaf8 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6658,9 +6658,8 @@ def replace( else: # need a non-zero len on all axes - for a in self._AXIS_ORDERS: - if not len(self._get_axis(a)): - return self + if not self.size: + return self new_data = self._data if is_dict_like(to_replace): diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 8956821740bf3..b2019e3e59dda 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -7,7 +7,7 @@ import numpy as np -from pandas._libs import internals as libinternals, lib +from pandas._libs import Timedelta, Timestamp, internals as libinternals, lib from pandas.util._validators import validate_bool_kwarg from pandas.core.dtypes.cast import ( @@ -602,9 +602,10 @@ def comp(s, regex=False): """ if isna(s): return isna(values) - if hasattr(s, "asm8"): + if isinstance(s, (Timedelta, Timestamp)) and getattr(s, "tz", None) is None: + return _compare_or_regex_search( - maybe_convert_objects(values), getattr(s, "asm8"), regex + maybe_convert_objects(values), s.asm8, regex ) return _compare_or_regex_search(values, s, regex) diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index dea1d5114f1b9..ed80e249220fd 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -1029,22 +1029,20 @@ def test_replace_series(self, how, to_key, from_key): tm.assert_series_equal(result, exp) - # TODO(jbrockmendel) commented out to only have a single xfail printed - @pytest.mark.xfail( - reason="GH #18376, tzawareness-compat bug in BlockManager.replace_list" + @pytest.mark.parametrize("how", ["dict", "series"]) + @pytest.mark.parametrize( + "to_key", + ["timedelta64[ns]", "bool", "object", "complex128", "float64", "int64"], ) - # @pytest.mark.parametrize('how', ['dict', 'series']) - # @pytest.mark.parametrize('to_key', ['timedelta64[ns]', 'bool', 'object', - # 'complex128', 'float64', 'int64']) - # @pytest.mark.parametrize('from_key', ['datetime64[ns, UTC]', - # 'datetime64[ns, US/Eastern]']) - # def test_replace_series_datetime_tz(self, how, to_key, from_key): - def test_replace_series_datetime_tz(self): + @pytest.mark.parametrize( + "from_key", ["datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"] + ) + def test_replace_series_datetime_tz(self, how, to_key, from_key): how = "series" from_key = "datetime64[ns, US/Eastern]" to_key = "timedelta64[ns]" - index = pd.Index([3, 4], name="xxx") + index = pd.Index([3, 4], name="xyz") obj = pd.Series(self.rep[from_key], index=index, name="yyy") assert obj.dtype == from_key @@ -1061,24 +1059,17 @@ def test_replace_series_datetime_tz(self): tm.assert_series_equal(result, exp) - # TODO(jreback) commented out to only have a single xfail printed - @pytest.mark.xfail( - reason="different tz, currently mask_missing raises SystemError", strict=False + @pytest.mark.parametrize("how", ["dict", "series"]) + @pytest.mark.parametrize( + "to_key", + ["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"], ) - # @pytest.mark.parametrize('how', ['dict', 'series']) - # @pytest.mark.parametrize('to_key', [ - # 'datetime64[ns]', 'datetime64[ns, UTC]', - # 'datetime64[ns, US/Eastern]']) - # @pytest.mark.parametrize('from_key', [ - # 'datetime64[ns]', 'datetime64[ns, UTC]', - # 'datetime64[ns, US/Eastern]']) - # def test_replace_series_datetime_datetime(self, how, to_key, from_key): - def test_replace_series_datetime_datetime(self): - how = "dict" - to_key = "datetime64[ns]" - from_key = "datetime64[ns]" - - index = pd.Index([3, 4], name="xxx") + @pytest.mark.parametrize( + "from_key", + ["datetime64[ns]", "datetime64[ns, UTC]", "datetime64[ns, US/Eastern]"], + ) + def test_replace_series_datetime_datetime(self, how, to_key, from_key): + index = pd.Index([3, 4], name="xyz") obj = pd.Series(self.rep[from_key], index=index, name="yyy") assert obj.dtype == from_key
- [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27720
2019-08-02T19:01:24Z
2019-08-05T11:58:49Z
2019-08-05T11:58:49Z
2019-08-05T14:44:19Z
remove confusing instructions and link.
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index 80dc8b0d8782b..b38f7767ae073 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -133,22 +133,11 @@ Installing a C compiler Pandas uses C extensions (mostly written using Cython) to speed up certain operations. To install pandas from source, you need to compile these C extensions, which means you need a C compiler. This process depends on which -platform you're using. Follow the `CPython contributing guide -<https://devguide.python.org/setup/#compile-and-build>`_ for getting a -compiler installed. You don't need to do any of the ``./configure`` or ``make`` -steps; you only need to install the compiler. - -For Windows developers, when using Python 3.5 and later, it is sufficient to -install `Visual Studio 2017 <https://visualstudio.com/>`_ with the -**Python development workload** and the **Python native development tools** -option. Otherwise, the following links may be helpful. - -* https://blogs.msdn.microsoft.com/pythonengineering/2017/03/07/python-support-in-vs2017/ -* https://blogs.msdn.microsoft.com/pythonengineering/2016/04/11/unable-to-find-vcvarsall-bat/ -* https://github.com/conda/conda-recipes/wiki/Building-from-Source-on-Windows-32-bit-and-64-bit -* https://cowboyprogrammer.org/building-python-wheels-for-windows/ -* https://blog.ionelmc.ro/2014/12/21/compiling-python-extensions-on-windows/ -* https://support.enthought.com/hc/en-us/articles/204469260-Building-Python-extensions-with-Canopy +platform you're using. + +* Windows: https://devguide.python.org/setup/#windows-compiling +* Mac: https://devguide.python.org/setup/#macos +* Unix: https://devguide.python.org/setup/#unix-compiling Let us know if you have any difficulties by opening an issue or reaching out on `Gitter`_.
- [ ] closes #27707 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27717
2019-08-02T16:16:54Z
2019-08-05T13:32:32Z
2019-08-05T13:32:31Z
2019-08-12T21:24:56Z
pandas.PeriodIndex and pandas.DateTimeIndex docstring quotes fix
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 2e086c8ce8c34..6a4ca0ab4147a 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -1414,17 +1414,69 @@ def date(self): return tslib.ints_to_pydatetime(timestamps, box="date") - year = _field_accessor("year", "Y", "The year of the datetime.") - month = _field_accessor("month", "M", "The month as January=1, December=12. ") - day = _field_accessor("day", "D", "The days of the datetime.") - hour = _field_accessor("hour", "h", "The hours of the datetime.") - minute = _field_accessor("minute", "m", "The minutes of the datetime.") - second = _field_accessor("second", "s", "The seconds of the datetime.") + year = _field_accessor( + "year", + "Y", + """ + The year of the datetime. + """, + ) + month = _field_accessor( + "month", + "M", + """ + The month as January=1, December=12. + """, + ) + day = _field_accessor( + "day", + "D", + """ + The month as January=1, December=12. + """, + ) + hour = _field_accessor( + "hour", + "h", + """ + The hours of the datetime. + """, + ) + minute = _field_accessor( + "minute", + "m", + """ + The minutes of the datetime. + """, + ) + second = _field_accessor( + "second", + "s", + """ + The seconds of the datetime. + """, + ) microsecond = _field_accessor( - "microsecond", "us", "The microseconds of the datetime." + "microsecond", + "us", + """ + The microseconds of the datetime. + """, + ) + nanosecond = _field_accessor( + "nanosecond", + "ns", + """ + The nanoseconds of the datetime. + """, + ) + weekofyear = _field_accessor( + "weekofyear", + "woy", + """ + The week ordinal of the year. + """, ) - nanosecond = _field_accessor("nanosecond", "ns", "The nanoseconds of the datetime.") - weekofyear = _field_accessor("weekofyear", "woy", "The week ordinal of the year.") week = weekofyear _dayofweek_doc = """ The day of the week with Monday=0, Sunday=6. @@ -1466,13 +1518,31 @@ def date(self): weekday_name = _field_accessor( "weekday_name", "weekday_name", - "The name of day in a week (ex: Friday)\n\n.. deprecated:: 0.23.0", + """ + The name of day in a week (ex: Friday)\n\n.. deprecated:: 0.23.0 + """, ) - dayofyear = _field_accessor("dayofyear", "doy", "The ordinal day of the year.") - quarter = _field_accessor("quarter", "q", "The quarter of the date.") + dayofyear = _field_accessor( + "dayofyear", + "doy", + """ + The ordinal day of the year. + """, + ) + quarter = _field_accessor( + "quarter", + "q", + """ + The quarter of the date. + """, + ) days_in_month = _field_accessor( - "days_in_month", "dim", "The number of days in the month." + "days_in_month", + "dim", + """ + The number of days in the month. + """, ) daysinmonth = days_in_month _is_month_doc = """ diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index c290391278def..91dd853e78c77 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -342,25 +342,85 @@ def __array__(self, dtype=None): # -------------------------------------------------------------------- # Vectorized analogues of Period properties - year = _field_accessor("year", 0, "The year of the period") - month = _field_accessor("month", 3, "The month as January=1, December=12") - day = _field_accessor("day", 4, "The days of the period") - hour = _field_accessor("hour", 5, "The hour of the period") - minute = _field_accessor("minute", 6, "The minute of the period") - second = _field_accessor("second", 7, "The second of the period") - weekofyear = _field_accessor("week", 8, "The week ordinal of the year") + year = _field_accessor( + "year", + 0, + """ + The year of the period. + """, + ) + month = _field_accessor( + "month", + 3, + """ + The month as January=1, December=12. + """, + ) + day = _field_accessor( + "day", + 4, + """ + The days of the period. + """, + ) + hour = _field_accessor( + "hour", + 5, + """ + The hour of the period. + """, + ) + minute = _field_accessor( + "minute", + 6, + """ + The minute of the period. + """, + ) + second = _field_accessor( + "second", + 7, + """ + The second of the period. + """, + ) + weekofyear = _field_accessor( + "week", + 8, + """ + The week ordinal of the year. + """, + ) week = weekofyear dayofweek = _field_accessor( - "dayofweek", 10, "The day of the week with Monday=0, Sunday=6" + "dayofweek", + 10, + """ + The day of the week with Monday=0, Sunday=6. + """, ) weekday = dayofweek dayofyear = day_of_year = _field_accessor( - "dayofyear", 9, "The ordinal day of the year" + "dayofyear", + 9, + """ + The ordinal day of the year. + """, + ) + quarter = _field_accessor( + "quarter", + 2, + """ + The quarter of the date. + """, ) - quarter = _field_accessor("quarter", 2, "The quarter of the date") qyear = _field_accessor("qyear", 1) days_in_month = _field_accessor( - "days_in_month", 11, "The number of days in the month" + "days_in_month", + 11, + """ + The number of days in the month. + """, ) daysinmonth = days_in_month
- [x] closes #27713 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27716
2019-08-02T16:11:27Z
2019-08-02T21:12:01Z
2019-08-02T21:12:01Z
2019-08-02T21:12:03Z
TST: troubleshoot inconsistent xfails
diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index c9597505fa596..5ecd641fc68be 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -11,6 +11,7 @@ import struct import sys +PY35 = sys.version_info[:2] == (3, 5) PY36 = sys.version_info >= (3, 6) PY37 = sys.version_info >= (3, 7) PYPY = platform.python_implementation() == "PyPy" diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index cca6836acf626..0b17ece14cbd1 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -666,6 +666,7 @@ def test_comparison_tzawareness_compat_scalars(self, op, box_with_array): # Raising in __eq__ will fallback to NumPy, which warns, fails, # then re-raises the original exception. So we just need to ignore. @pytest.mark.filterwarnings("ignore:elementwise comp:DeprecationWarning") + @pytest.mark.filterwarnings("ignore:Converting timezone-aware:FutureWarning") def test_scalar_comparison_tzawareness( self, op, other, tz_aware_fixture, box_with_array ): diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 8c0930c044838..c500760fa1390 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -1789,9 +1789,10 @@ def test_result_types(self): self.check_result_type(np.float32, np.float32) self.check_result_type(np.float64, np.float64) - def test_result_types2(self): + @td.skip_if_windows + def test_result_complex128(self): # xref https://github.com/pandas-dev/pandas/issues/12293 - pytest.skip("unreliable tests on complex128") + # this fails on Windows, apparently a floating point precision issue # Did not test complex64 because DataFrame is converting it to # complex128. Due to https://github.com/pandas-dev/pandas/issues/10952 diff --git a/pandas/tests/extension/test_datetime.py b/pandas/tests/extension/test_datetime.py index 9a7a43cff0c27..a60607d586ada 100644 --- a/pandas/tests/extension/test_datetime.py +++ b/pandas/tests/extension/test_datetime.py @@ -142,16 +142,6 @@ def test_divmod_series_array(self): # skipping because it is not implemented pass - @pytest.mark.xfail(reason="different implementation", strict=False) - def test_direct_arith_with_series_returns_not_implemented(self, data): - # Right now, we have trouble with this. Returning NotImplemented - # fails other tests like - # tests/arithmetic/test_datetime64::TestTimestampSeriesArithmetic:: - # test_dt64_seris_add_intlike - return super( - TestArithmeticOps, self - ).test_direct_arith_with_series_returns_not_implemented(data) - class TestCasting(BaseDatetimeTests, base.BaseCastingTests): pass @@ -163,12 +153,6 @@ def _compare_other(self, s, data, op_name, other): # with (some) integers, depending on the value. pass - @pytest.mark.xfail(reason="different implementation", strict=False) - def test_direct_arith_with_series_returns_not_implemented(self, data): - return super( - TestComparisonOps, self - ).test_direct_arith_with_series_returns_not_implemented(data) - class TestMissing(BaseDatetimeTests, base.BaseMissingTests): pass diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index d5c66f0c1dd64..e99208ac78e15 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -1819,10 +1819,17 @@ def test_any_all_bool_only(self): (np.any, {"A": pd.Series([0, 1], dtype="category")}, True), (np.all, {"A": pd.Series([1, 2], dtype="category")}, True), (np.any, {"A": pd.Series([1, 2], dtype="category")}, True), - # # Mix - # GH 21484 - # (np.all, {'A': pd.Series([10, 20], dtype='M8[ns]'), - # 'B': pd.Series([10, 20], dtype='m8[ns]')}, True), + # Mix GH#21484 + pytest.param( + np.all, + { + "A": pd.Series([10, 20], dtype="M8[ns]"), + "B": pd.Series([10, 20], dtype="m8[ns]"), + }, + True, + # In 1.13.3 and 1.14 np.all(df) returns a Timedelta here + marks=[td.skip_if_np_lt("1.15")], + ), ], ) def test_any_all_np_func(self, func, data, expected): diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 486b3b28b29a3..9b8c8e6d8a077 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -4,8 +4,6 @@ import numpy as np import pytest -from pandas.compat import PY37 - import pandas as pd from pandas import ( Categorical, @@ -209,7 +207,7 @@ def test_level_get_group(observed): assert_frame_equal(result, expected) -@pytest.mark.xfail(PY37, reason="flaky on 3.7, xref gh-21636", strict=False) +# GH#21636 previously flaky on py37 @pytest.mark.parametrize("ordered", [True, False]) def test_apply(ordered): # GH 10138 diff --git a/pandas/tests/indexes/datetimes/test_construction.py b/pandas/tests/indexes/datetimes/test_construction.py index 66a22ae7e9e46..88bc11c588673 100644 --- a/pandas/tests/indexes/datetimes/test_construction.py +++ b/pandas/tests/indexes/datetimes/test_construction.py @@ -759,6 +759,8 @@ def test_constructor_with_int_tz(self, klass, box, tz, dtype): assert result == expected # This is the desired future behavior + # Note: this xfail is not strict because the test passes with + # None or any of the UTC variants for tz_naive_fixture @pytest.mark.xfail(reason="Future behavior", strict=False) @pytest.mark.filterwarnings("ignore:\\n Passing:FutureWarning") def test_construction_int_rountrip(self, tz_naive_fixture): @@ -766,7 +768,7 @@ def test_construction_int_rountrip(self, tz_naive_fixture): # TODO(GH-24559): Remove xfail tz = tz_naive_fixture result = 1293858000000000000 - expected = DatetimeIndex([1293858000000000000], tz=tz).asi8[0] + expected = DatetimeIndex([result], tz=tz).asi8[0] assert result == expected def test_construction_from_replaced_timestamps_with_dst(self): diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index 10d422e8aa52c..8db15709da35d 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -741,10 +741,7 @@ def test_to_datetime_tz_psycopg2(self, cache): ) tm.assert_index_equal(result, expected) - @pytest.mark.parametrize( - "cache", - [pytest.param(True, marks=pytest.mark.skipif(True, reason="GH 18111")), False], - ) + @pytest.mark.parametrize("cache", [True, False]) def test_datetime_bool(self, cache): # GH13176 with pytest.raises(TypeError): diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index c6485ff21bcfb..ee236a8253b01 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -340,7 +340,6 @@ def test_to_csv_string_array_ascii(self): with open(path, "r") as f: assert f.read() == expected_ascii - @pytest.mark.xfail(strict=False) def test_to_csv_string_array_utf8(self): # GH 10813 str_array = [{"names": ["foo", "bar"]}, {"names": ["baz", "qux"]}] diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index a04fb9fd50257..d634859e72d7b 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -33,6 +33,10 @@ except ImportError: _HAVE_FASTPARQUET = False +pytestmark = pytest.mark.filterwarnings( + "ignore:RangeIndex.* is deprecated:DeprecationWarning" +) + # setup engines & skips @pytest.fixture( @@ -408,8 +412,6 @@ def test_basic(self, pa, df_full): check_round_trip(df, pa) - # TODO: This doesn't fail on all systems; track down which - @pytest.mark.xfail(reason="pyarrow fails on this (ARROW-1883)", strict=False) def test_basic_subset_columns(self, pa, df_full): # GH18628 diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index e3bc3d452f038..69070ea11e478 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -1098,7 +1098,6 @@ def test_time(self): assert xp == rs @pytest.mark.slow - @pytest.mark.xfail(strict=False, reason="Unreliable test") def test_time_change_xlim(self): t = datetime(1, 1, 1, 3, 30, 0) deltas = np.random.randint(1, 20, 3).cumsum() diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index 4404b93e86218..b57b817461788 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -10,6 +10,7 @@ from pandas._libs.tslibs.parsing import DateParseError from pandas._libs.tslibs.period import IncompatibleFrequency from pandas._libs.tslibs.timezones import dateutil_gettz, maybe_get_tz +from pandas.compat import PY35 from pandas.compat.numpy import np_datetime64_compat import pandas as pd @@ -1579,8 +1580,9 @@ def test_period_immutable(): per.freq = 2 * freq -# TODO: This doesn't fail on all systems; track down which -@pytest.mark.xfail(reason="Parses as Jan 1, 0007 on some systems", strict=False) +@pytest.mark.xfail( + PY35, reason="Parsing as Period('0007-01-01', 'D') for reasons unknown", strict=True +) def test_small_year_parsing(): per1 = Period("0001-01-07", "D") assert per1.year == 1 diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index 32d32a5d14fb2..3a5a387b919be 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -1489,7 +1489,7 @@ def test_value_counts_with_nan(self): "unicode_", "timedelta64[h]", pytest.param( - "datetime64[D]", marks=pytest.mark.xfail(reason="GH#7996", strict=False) + "datetime64[D]", marks=pytest.mark.xfail(reason="GH#7996", strict=True) ), ], ) diff --git a/pandas/tests/sparse/test_combine_concat.py b/pandas/tests/sparse/test_combine_concat.py index d7295c4bfe5f0..c553cd3fd1a7a 100644 --- a/pandas/tests/sparse/test_combine_concat.py +++ b/pandas/tests/sparse/test_combine_concat.py @@ -440,7 +440,7 @@ def test_concat_sparse_dense_rows(self, fill_value, sparse_idx, dense_idx): "fill_value,sparse_idx,dense_idx", itertools.product([None, 0, 1, np.nan], [0, 1], [1, 0]), ) - @pytest.mark.xfail(reason="The iloc fails and I can't make expected", strict=False) + @pytest.mark.xfail(reason="The iloc fails and I can't make expected", strict=True) def test_concat_sparse_dense_cols(self, fill_value, sparse_idx, dense_idx): # See GH16874, GH18914 and #18686 for why this should be a DataFrame from pandas.core.dtypes.common import is_sparse diff --git a/pandas/tests/sparse/test_pivot.py b/pandas/tests/sparse/test_pivot.py index 85b899dfe76d5..880c1c55f9f79 100644 --- a/pandas/tests/sparse/test_pivot.py +++ b/pandas/tests/sparse/test_pivot.py @@ -2,7 +2,6 @@ import pytest import pandas as pd -from pandas import _np_version_under1p17 import pandas.util.testing as tm @@ -49,11 +48,6 @@ def test_pivot_table_with_nans(self): ) tm.assert_frame_equal(res_sparse, res_dense) - @pytest.mark.xfail( - not _np_version_under1p17, - reason="failing occasionally on numpy > 1.17", - strict=False, - ) def test_pivot_table_multi(self): res_sparse = pd.pivot_table( self.sparse, index="A", columns="B", values=["D", "E"]
https://api.github.com/repos/pandas-dev/pandas/pulls/27715
2019-08-02T15:42:37Z
2019-08-05T11:55:36Z
2019-08-05T11:55:36Z
2019-08-05T14:28:35Z
REF/CLN: maybe_downcast_to_dtype
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index fd8536e38eee7..4bb1deffd9524 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -46,6 +46,7 @@ ) from .dtypes import DatetimeTZDtype, ExtensionDtype, PeriodDtype from .generic import ( + ABCDataFrame, ABCDatetimeArray, ABCDatetimeIndex, ABCPeriodArray, @@ -95,12 +96,13 @@ def maybe_downcast_to_dtype(result, dtype): """ try to cast to the specified dtype (e.g. convert back to bool/int or could be an astype of float64->float32 """ + do_round = False if is_scalar(result): return result - - def trans(x): - return x + elif isinstance(result, ABCDataFrame): + # occurs in pivot_table doctest + return result if isinstance(dtype, str): if dtype == "infer": @@ -118,83 +120,115 @@ def trans(x): elif inferred_type == "floating": dtype = "int64" if issubclass(result.dtype.type, np.number): - - def trans(x): # noqa - return x.round() + do_round = True else: dtype = "object" - if isinstance(dtype, str): dtype = np.dtype(dtype) - try: + converted = maybe_downcast_numeric(result, dtype, do_round) + if converted is not result: + return converted + + # a datetimelike + # GH12821, iNaT is casted to float + if dtype.kind in ["M", "m"] and result.dtype.kind in ["i", "f"]: + try: + result = result.astype(dtype) + except Exception: + if dtype.tz: + # convert to datetime and change timezone + from pandas import to_datetime + + result = to_datetime(result).tz_localize("utc") + result = result.tz_convert(dtype.tz) + + elif dtype.type is Period: + # TODO(DatetimeArray): merge with previous elif + from pandas.core.arrays import PeriodArray + try: + return PeriodArray(result, freq=dtype.freq) + except TypeError: + # e.g. TypeError: int() argument must be a string, a + # bytes-like object or a number, not 'Period + pass + + return result + + +def maybe_downcast_numeric(result, dtype, do_round: bool = False): + """ + Subset of maybe_downcast_to_dtype restricted to numeric dtypes. + + Parameters + ---------- + result : ndarray or ExtensionArray + dtype : np.dtype or ExtensionDtype + do_round : bool + + Returns + ------- + ndarray or ExtensionArray + """ + if not isinstance(dtype, np.dtype): + # e.g. SparseDtype has no itemsize attr + return result + + if isinstance(result, list): + # reached via groupoby.agg _ohlc; really this should be handled + # earlier + result = np.array(result) + + def trans(x): + if do_round: + return x.round() + return x + + if dtype.kind == result.dtype.kind: # don't allow upcasts here (except if empty) - if dtype.kind == result.dtype.kind: - if result.dtype.itemsize <= dtype.itemsize and np.prod(result.shape): - return result + if result.dtype.itemsize <= dtype.itemsize and result.size: + return result - if is_bool_dtype(dtype) or is_integer_dtype(dtype): + if is_bool_dtype(dtype) or is_integer_dtype(dtype): + if not result.size: # if we don't have any elements, just astype it - if not np.prod(result.shape): - return trans(result).astype(dtype) + return trans(result).astype(dtype) - # do a test on the first element, if it fails then we are done - r = result.ravel() - arr = np.array([r[0]]) + # do a test on the first element, if it fails then we are done + r = result.ravel() + arr = np.array([r[0]]) + if isna(arr).any() or not np.allclose(arr, trans(arr).astype(dtype), rtol=0): # if we have any nulls, then we are done - if isna(arr).any() or not np.allclose( - arr, trans(arr).astype(dtype), rtol=0 - ): - return result + return result + elif not isinstance(r[0], (np.integer, np.floating, np.bool, int, float, bool)): # a comparable, e.g. a Decimal may slip in here - elif not isinstance( - r[0], (np.integer, np.floating, np.bool, int, float, bool) - ): - return result + return result - if ( - issubclass(result.dtype.type, (np.object_, np.number)) - and notna(result).all() - ): - new_result = trans(result).astype(dtype) - try: - if np.allclose(new_result, result, rtol=0): - return new_result - except Exception: - - # comparison of an object dtype with a number type could - # hit here - if (new_result == result).all(): - return new_result - elif issubclass(dtype.type, np.floating) and not is_bool_dtype(result.dtype): - return result.astype(dtype) - - # a datetimelike - # GH12821, iNaT is casted to float - elif dtype.kind in ["M", "m"] and result.dtype.kind in ["i", "f"]: + if ( + issubclass(result.dtype.type, (np.object_, np.number)) + and notna(result).all() + ): + new_result = trans(result).astype(dtype) try: - result = result.astype(dtype) + if np.allclose(new_result, result, rtol=0): + return new_result except Exception: - if dtype.tz: - # convert to datetime and change timezone - from pandas import to_datetime - - result = to_datetime(result).tz_localize("utc") - result = result.tz_convert(dtype.tz) - - elif dtype.type == Period: - # TODO(DatetimeArray): merge with previous elif - from pandas.core.arrays import PeriodArray - - return PeriodArray(result, freq=dtype.freq) - - except Exception: - pass + # comparison of an object dtype with a number type could + # hit here + if (new_result == result).all(): + return new_result + + elif ( + issubclass(dtype.type, np.floating) + and not is_bool_dtype(result.dtype) + and not is_string_dtype(result.dtype) + ): + return result.astype(dtype) return result
Separate out a numeric-only maybe_downcast_to_dtype_numeric from maybe_downcast_to_dtype. Avoid a giant try/except by checking the correct things up front. The non-numeric portion of maybe_downcast_to_dtype casts to datetime64, datetime64tz, or PeriodArray. Following #27683 the next step in cleaning up internals is going to be getting rid of _try_cast_result, which will involve replacing a usage of maybe_cast_to_dtype with the less-broadly-scoped maybe_cast_to_dtype_numeric.
https://api.github.com/repos/pandas-dev/pandas/pulls/27714
2019-08-02T15:34:09Z
2019-08-04T21:52:45Z
2019-08-04T21:52:45Z
2019-08-04T23:12:38Z
BUG: partial string indexing with scalar
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index c80195af413f7..3097bfa21f9e1 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -82,7 +82,7 @@ Interval Indexing ^^^^^^^^ -- +- Bug in partial-string indexing returning a NumPy array rather than a ``Series`` when indexing with a scalar like ``.loc['2015']`` (:issue:`27516`) - - diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index ce7b73a92b18a..a524de3002402 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -243,6 +243,9 @@ def _outer_indexer(self, left, right): _infer_as_myclass = False _engine_type = libindex.ObjectEngine + # whether we support partial string indexing. Overridden + # in DatetimeIndex and PeriodIndex + _supports_partial_string_indexing = False _accessors = {"str"} diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index d6f0008a2646f..c01acbeab1473 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -238,6 +238,7 @@ def _join_i8_wrapper(joinf, **kwargs): ) _engine_type = libindex.DatetimeEngine + _supports_partial_string_indexing = True _tz = None _freq = None diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 19fe1eb897f19..f6b3d1076043e 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -173,6 +173,7 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index, PeriodDelegateMixin): _data = None _engine_type = libindex.PeriodEngine + _supports_partial_string_indexing = True # ------------------------------------------------------------------------ # Index Constructors diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index df89dbe6db6dc..e308ae03730b3 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1704,6 +1704,11 @@ def _is_scalar_access(self, key: Tuple): if isinstance(ax, MultiIndex): return False + if isinstance(k, str) and ax._supports_partial_string_indexing: + # partial string indexing, df.loc['2000', 'A'] + # should not be considered scalar + return False + if not ax.is_unique: return False @@ -1719,7 +1724,10 @@ def _get_partial_string_timestamp_match_key(self, key, labels): """Translate any partial string timestamp matches in key, returning the new key (GH 10331)""" if isinstance(labels, MultiIndex): - if isinstance(key, str) and labels.levels[0].is_all_dates: + if ( + isinstance(key, str) + and labels.levels[0]._supports_partial_string_indexing + ): # Convert key '2016-01-01' to # ('2016-01-01'[, slice(None, None, None)]+) key = tuple([key] + [slice(None)] * (len(labels.levels) - 1)) @@ -1729,7 +1737,10 @@ def _get_partial_string_timestamp_match_key(self, key, labels): # (..., slice('2016-01-01', '2016-01-01', None), ...) new_key = [] for i, component in enumerate(key): - if isinstance(component, str) and labels.levels[i].is_all_dates: + if ( + isinstance(component, str) + and labels.levels[i]._supports_partial_string_indexing + ): new_key.append(slice(component, component, None)) else: new_key.append(component) @@ -2334,7 +2345,7 @@ def convert_to_index_sliceable(obj, key): # We might have a datetimelike string that we can translate to a # slice here via partial string indexing - if idx.is_all_dates: + if idx._supports_partial_string_indexing: try: return idx._get_string_slice(key) except (KeyError, ValueError, NotImplementedError): diff --git a/pandas/tests/indexes/datetimes/test_partial_slicing.py b/pandas/tests/indexes/datetimes/test_partial_slicing.py index 3095bf9657277..5660fa5ffed80 100644 --- a/pandas/tests/indexes/datetimes/test_partial_slicing.py +++ b/pandas/tests/indexes/datetimes/test_partial_slicing.py @@ -468,3 +468,14 @@ def test_getitem_with_datestring_with_UTC_offset(self, start, end): with pytest.raises(ValueError, match="The index must be timezone"): df = df.tz_localize(None) df[start:end] + + def test_slice_reduce_to_series(self): + # GH 27516 + df = pd.DataFrame( + {"A": range(24)}, index=pd.date_range("2000", periods=24, freq="M") + ) + expected = pd.Series( + range(12), index=pd.date_range("2000", periods=12, freq="M"), name="A" + ) + result = df.loc["2000", "A"] + tm.assert_series_equal(result, expected)
Closes #27516 cc @jreback if you have thoughts on this approach.
https://api.github.com/repos/pandas-dev/pandas/pulls/27712
2019-08-02T14:22:02Z
2019-08-04T21:54:57Z
2019-08-04T21:54:57Z
2019-08-04T21:55:20Z
Backport PR #27710 on branch 0.25.x (DOC: Fixed a typo in the roadmap.rst (the word "uses" appeared twice))
diff --git a/doc/source/development/roadmap.rst b/doc/source/development/roadmap.rst index 88e0a18e6b81a..00598830e2fe9 100644 --- a/doc/source/development/roadmap.rst +++ b/doc/source/development/roadmap.rst @@ -96,7 +96,7 @@ Decoupling of indexing and internals The code for getting and setting values in pandas' data structures needs refactoring. In particular, we must clearly separate code that converts keys (e.g., the argument -to ``DataFrame.loc``) to positions from code that uses uses these positions to get +to ``DataFrame.loc``) to positions from code that uses these positions to get or set values. This is related to the proposed BlockManager rewrite. Currently, the BlockManager sometimes uses label-based, rather than position-based, indexing. We propose that it should only work with positional indexing, and the translation of keys
Backport PR #27710: DOC: Fixed a typo in the roadmap.rst (the word "uses" appeared twice)
https://api.github.com/repos/pandas-dev/pandas/pulls/27711
2019-08-02T13:28:58Z
2019-08-02T13:29:11Z
2019-08-02T13:29:11Z
2019-08-02T13:29:11Z
DOC: Fixed a typo in the roadmap.rst (the word "uses" appeared twice)
diff --git a/doc/source/development/roadmap.rst b/doc/source/development/roadmap.rst index 88e0a18e6b81a..00598830e2fe9 100644 --- a/doc/source/development/roadmap.rst +++ b/doc/source/development/roadmap.rst @@ -96,7 +96,7 @@ Decoupling of indexing and internals The code for getting and setting values in pandas' data structures needs refactoring. In particular, we must clearly separate code that converts keys (e.g., the argument -to ``DataFrame.loc``) to positions from code that uses uses these positions to get +to ``DataFrame.loc``) to positions from code that uses these positions to get or set values. This is related to the proposed BlockManager rewrite. Currently, the BlockManager sometimes uses label-based, rather than position-based, indexing. We propose that it should only work with positional indexing, and the translation of keys
https://api.github.com/repos/pandas-dev/pandas/pulls/27710
2019-08-02T13:14:59Z
2019-08-02T13:28:18Z
2019-08-02T13:28:18Z
2019-08-02T13:40:52Z
Linebreak is bleeding into the documentation page
diff --git a/pandas/core/base.py b/pandas/core/base.py index cfa8d25210129..38a8bf7171521 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -687,8 +687,9 @@ def transpose(self, *args, **kwargs): T = property( transpose, - doc="""\nReturn the transpose, which is by - definition self.\n""", + doc=""" + Return the transpose, which is by definition self. + """, ) @property
https://pandas.pydata.org/pandas-docs/stable/reference/series.html ```html <table><td> ... <tr class="row-even"><td><a class="reference internal" href="api/pandas.Series.T.html#pandas.Series.T" title="pandas.Series.T"><code class="xref py py-obj docutils literal notranslate"><span class="pre">Series.T</span></code></a></td> <td>Return the transpose, which is by</td> </tr> ... </td> </table> ``` And looks weird on https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.T.html#pandas.Series.T - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27708
2019-08-02T07:59:37Z
2019-08-03T16:05:38Z
2019-08-03T16:05:38Z
2019-08-04T11:33:26Z
CLN: rename reduce-->do_reduce
diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx index 739ac0ed397ca..f95685c337969 100644 --- a/pandas/_libs/reduction.pyx +++ b/pandas/_libs/reduction.pyx @@ -628,7 +628,7 @@ cdef class BlockSlider: arr.shape[1] = 0 -def reduce(arr, f, axis=0, dummy=None, labels=None): +def compute_reduction(arr, f, axis=0, dummy=None, labels=None): """ Parameters diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 6a32553fe2d38..d24aafae0967d 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -1280,7 +1280,8 @@ class Timedelta(_Timedelta): else: raise ValueError( "Value must be Timedelta, string, integer, " - "float, timedelta or convertible") + "float, timedelta or convertible, not {typ}" + .format(typ=type(value).__name__)) if is_timedelta64_object(value): value = value.view('i8') diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 2246bbfde636d..5c8599dbb054b 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -221,7 +221,7 @@ def apply_raw(self): """ apply to the values as a numpy array """ try: - result = reduction.reduce(self.values, self.f, axis=self.axis) + result = reduction.compute_reduction(self.values, self.f, axis=self.axis) except Exception: result = np.apply_along_axis(self.f, self.axis, self.values) @@ -281,7 +281,7 @@ def apply_standard(self): dummy = Series(empty_arr, index=index, dtype=values.dtype) try: - result = reduction.reduce( + result = reduction.compute_reduction( values, self.f, axis=self.axis, dummy=dummy, labels=labels ) return self.obj._constructor_sliced(result, index=labels) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index b16217d5d0a32..d22b4bd4d3f2b 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -2703,7 +2703,7 @@ def _convert_to_list_like(list_like): elif is_scalar(list_like): return [list_like] else: - # is this reached? + # TODO: is this reached? return [list_like] diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 47718fc39ca1d..9b516c1b6ae02 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -57,21 +57,10 @@ class AttributesMixin: _data = None # type: np.ndarray - @property - def _attributes(self): - # Inheriting subclass should implement _attributes as a list of strings - raise AbstractMethodError(self) - @classmethod def _simple_new(cls, values, **kwargs): raise AbstractMethodError(cls) - def _get_attributes_dict(self): - """ - return an attributes dict for my class - """ - return {k: getattr(self, k, None) for k in self._attributes} - @property def _scalar_type(self) -> Type[DatetimeLikeScalar]: """The scalar associated with this datelike diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 6a4ca0ab4147a..061ee4b90d0e9 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -328,7 +328,6 @@ class DatetimeArray(dtl.DatetimeLikeArrayMixin, dtl.TimelikeOps, dtl.DatelikeOps # ----------------------------------------------------------------- # Constructors - _attributes = ["freq", "tz"] _dtype = None # type: Union[np.dtype, DatetimeTZDtype] _freq = None diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 6203cfdf6df6b..20ce11c70c344 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -161,7 +161,6 @@ class PeriodArray(dtl.DatetimeLikeArrayMixin, dtl.DatelikeOps): # array priority higher than numpy scalars __array_priority__ = 1000 - _attributes = ["freq"] _typ = "periodarray" # ABCPeriodArray _scalar_type = Period diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index dd0b9a79c6dca..afd1e8203059e 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -199,7 +199,6 @@ def dtype(self): # ---------------------------------------------------------------- # Constructors - _attributes = ["freq"] def __init__(self, values, dtype=_TD_DTYPE, freq=None, copy=False): if isinstance(values, (ABCSeries, ABCIndexClass)): diff --git a/pandas/core/generic.py b/pandas/core/generic.py index ea49a13439bfb..010e5b890c5b5 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3556,7 +3556,7 @@ def _iget_item_cache(self, item): def _box_item_values(self, key, values): raise AbstractMethodError(self) - def _slice(self, slobj, axis=0, kind=None): + def _slice(self, slobj: slice, axis=0, kind=None): """ Construct a slice of this container. @@ -6183,8 +6183,6 @@ def fillna( axis = 0 axis = self._get_axis_number(axis) - from pandas import DataFrame - if value is None: if self._is_mixed_type and axis == 1: @@ -6247,7 +6245,7 @@ def fillna( new_data = self._data.fillna( value=value, limit=limit, inplace=inplace, downcast=downcast ) - elif isinstance(value, DataFrame) and self.ndim == 2: + elif isinstance(value, ABCDataFrame) and self.ndim == 2: new_data = self.where(self.notna(), value) else: raise ValueError("invalid fill value with a %s" % type(value)) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index ec526b338eee1..c5e81e21e9fd5 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -29,14 +29,16 @@ class providing the base-class of operations. from pandas.core.dtypes.cast import maybe_downcast_to_dtype from pandas.core.dtypes.common import ( ensure_float, + is_datetime64_dtype, is_datetime64tz_dtype, is_extension_array_dtype, + is_integer_dtype, is_numeric_dtype, + is_object_dtype, is_scalar, ) from pandas.core.dtypes.missing import isna, notna -from pandas.api.types import is_datetime64_dtype, is_integer_dtype, is_object_dtype import pandas.core.algorithms as algorithms from pandas.core.arrays import Categorical from pandas.core.base import ( @@ -343,7 +345,7 @@ class _GroupBy(PandasObject, SelectionMixin): def __init__( self, - obj, + obj: NDFrame, keys=None, axis=0, level=None, @@ -360,8 +362,8 @@ def __init__( self._selection = selection - if isinstance(obj, NDFrame): - obj._consolidate_inplace() + assert isinstance(obj, NDFrame), type(obj) + obj._consolidate_inplace() self.level = level diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 5c32550af3883..143755a47b97b 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -25,6 +25,7 @@ from pandas.core.arrays import Categorical, ExtensionArray import pandas.core.common as com from pandas.core.frame import DataFrame +from pandas.core.generic import NDFrame from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby from pandas.core.groupby.ops import BaseGrouper from pandas.core.index import CategoricalIndex, Index, MultiIndex @@ -423,7 +424,7 @@ def groups(self): def _get_grouper( - obj, + obj: NDFrame, key=None, axis=0, level=None, diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 1484feeeada64..f20c3f702e29d 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -906,7 +906,7 @@ def _get_sorted_data(self): return self.data.take(self.sort_idx, axis=self.axis) def _chop(self, sdata, slice_obj): - return sdata.iloc[slice_obj] + raise AbstractMethodError(self) def apply(self, f): raise AbstractMethodError(self) @@ -933,7 +933,7 @@ def _chop(self, sdata, slice_obj): if self.axis == 0: return sdata.iloc[slice_obj] else: - return sdata._slice(slice_obj, axis=1) # .loc[:, slice_obj] + return sdata._slice(slice_obj, axis=1) def get_splitter(data, *args, **kwargs): diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 01bfbed1aab4c..2c8006680626c 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -37,6 +37,7 @@ from pandas.core.dtypes.generic import ( ABCDataFrame, ABCDatetimeArray, + ABCDatetimeIndex, ABCIndex, ABCIndexClass, ABCSeries, @@ -47,7 +48,7 @@ import pandas as pd from pandas._typing import ArrayLike -import pandas.core.common as com +from pandas.core.construction import extract_array from . import missing from .docstrings import ( @@ -1022,7 +1023,7 @@ def wrapper(left, right): # does inference in the case where `result` has object-dtype. return construct_result(left, result, index=left.index, name=res_name) - elif isinstance(right, (ABCDatetimeArray, pd.DatetimeIndex)): + elif isinstance(right, (ABCDatetimeArray, ABCDatetimeIndex)): result = op(left._values, right) return construct_result(left, result, index=left.index, name=res_name) @@ -1194,7 +1195,7 @@ def wrapper(self, other, axis=None): ) # always return a full value series here - res_values = com.values_from_object(res) + res_values = extract_array(res, extract_numpy=True) return self._constructor( res_values, index=self.index, name=res_name, dtype="bool" ) diff --git a/pandas/tests/groupby/test_bin_groupby.py b/pandas/tests/groupby/test_bin_groupby.py index b240876de92b1..2195686ee9c7f 100644 --- a/pandas/tests/groupby/test_bin_groupby.py +++ b/pandas/tests/groupby/test_bin_groupby.py @@ -6,15 +6,13 @@ from pandas.core.dtypes.common import ensure_int64 -from pandas import Index, isna +from pandas import Index, Series, isna from pandas.core.groupby.ops import generate_bins_generic import pandas.util.testing as tm from pandas.util.testing import assert_almost_equal def test_series_grouper(): - from pandas import Series - obj = Series(np.random.randn(10)) dummy = obj[:0] @@ -31,8 +29,6 @@ def test_series_grouper(): def test_series_bin_grouper(): - from pandas import Series - obj = Series(np.random.randn(10)) dummy = obj[:0] @@ -123,30 +119,32 @@ class TestMoments: class TestReducer: def test_int_index(self): - from pandas.core.series import Series - arr = np.random.randn(100, 4) - result = reduction.reduce(arr, np.sum, labels=Index(np.arange(4))) + result = reduction.compute_reduction(arr, np.sum, labels=Index(np.arange(4))) expected = arr.sum(0) assert_almost_equal(result, expected) - result = reduction.reduce(arr, np.sum, axis=1, labels=Index(np.arange(100))) + result = reduction.compute_reduction( + arr, np.sum, axis=1, labels=Index(np.arange(100)) + ) expected = arr.sum(1) assert_almost_equal(result, expected) dummy = Series(0.0, index=np.arange(100)) - result = reduction.reduce(arr, np.sum, dummy=dummy, labels=Index(np.arange(4))) + result = reduction.compute_reduction( + arr, np.sum, dummy=dummy, labels=Index(np.arange(4)) + ) expected = arr.sum(0) assert_almost_equal(result, expected) dummy = Series(0.0, index=np.arange(4)) - result = reduction.reduce( + result = reduction.compute_reduction( arr, np.sum, axis=1, dummy=dummy, labels=Index(np.arange(100)) ) expected = arr.sum(1) assert_almost_equal(result, expected) - result = reduction.reduce( + result = reduction.compute_reduction( arr, np.sum, axis=1, dummy=dummy, labels=Index(np.arange(100)) ) assert_almost_equal(result, expected)
The current name makes it difficult to grep for. Assorted cleanups; added type annotations in a few places.
https://api.github.com/repos/pandas-dev/pandas/pulls/27706
2019-08-02T01:12:20Z
2019-08-05T06:31:49Z
2019-08-05T06:31:49Z
2019-08-05T14:32:37Z
BUG: Avoid try/except in blocks, fix setitem bug in datetimelike EA
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index f86b307e5ede3..2206fd3316685 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -473,6 +473,8 @@ def __setitem__( # to a period in from_sequence). For DatetimeArray, it's Timestamp... # I don't know if mypy can do that, possibly with Generics. # https://mypy.readthedocs.io/en/latest/generics.html + if lib.is_scalar(value) and not isna(value): + value = com.maybe_box_datetimelike(value) if is_list_like(value): is_slice = isinstance(key, slice) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 6d70fcfb62d52..563faab98d68b 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2230,7 +2230,9 @@ def _can_hold_element(self, element): if tipo is not None: if self.is_datetimetz: # require exact match, since non-nano does not exist - return is_dtype_equal(tipo, self.dtype) + return is_dtype_equal(tipo, self.dtype) or is_valid_nat_for_dtype( + element, self.dtype + ) # GH#27419 if we get a non-nano datetime64 object return is_datetime64_dtype(tipo) @@ -2500,26 +2502,28 @@ def concat_same_type(self, to_concat, placement=None): def fillna(self, value, limit=None, inplace=False, downcast=None): # We support filling a DatetimeTZ with a `value` whose timezone # is different by coercing to object. - try: + if self._can_hold_element(value): return super().fillna(value, limit, inplace, downcast) - except (ValueError, TypeError): - # different timezones, or a non-tz - return self.astype(object).fillna( - value, limit=limit, inplace=inplace, downcast=downcast - ) + + # different timezones, or a non-tz + return self.astype(object).fillna( + value, limit=limit, inplace=inplace, downcast=downcast + ) def setitem(self, indexer, value): # https://github.com/pandas-dev/pandas/issues/24020 # Need a dedicated setitem until #24020 (type promotion in setitem # for extension arrays) is designed and implemented. - try: + if self._can_hold_element(value) or ( + isinstance(indexer, np.ndarray) and indexer.size == 0 + ): return super().setitem(indexer, value) - except (ValueError, TypeError): - obj_vals = self.values.astype(object) - newb = make_block( - obj_vals, placement=self.mgr_locs, klass=ObjectBlock, ndim=self.ndim - ) - return newb.setitem(indexer, value) + + obj_vals = self.values.astype(object) + newb = make_block( + obj_vals, placement=self.mgr_locs, klass=ObjectBlock, ndim=self.ndim + ) + return newb.setitem(indexer, value) def equals(self, other): # override for significant performance improvement diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py index 58c2f3fc65bb2..d749d9bb47d25 100644 --- a/pandas/tests/arrays/test_datetimes.py +++ b/pandas/tests/arrays/test_datetimes.py @@ -179,6 +179,22 @@ def test_setitem_clears_freq(self): a[0] = pd.Timestamp("2000", tz="US/Central") assert a.freq is None + @pytest.mark.parametrize( + "obj", + [ + pd.Timestamp.now(), + pd.Timestamp.now().to_datetime64(), + pd.Timestamp.now().to_pydatetime(), + ], + ) + def test_setitem_objects(self, obj): + # make sure we accept datetime64 and datetime in addition to Timestamp + dti = pd.date_range("2000", periods=2, freq="D") + arr = dti._data + + arr[0] = obj + assert arr[0] == obj + def test_repeat_preserves_tz(self): dti = pd.date_range("2000", periods=2, freq="D", tz="US/Central") arr = DatetimeArray(dti) diff --git a/pandas/tests/arrays/test_timedeltas.py b/pandas/tests/arrays/test_timedeltas.py index 5825f9f150eb8..540c3343b2a1b 100644 --- a/pandas/tests/arrays/test_timedeltas.py +++ b/pandas/tests/arrays/test_timedeltas.py @@ -125,6 +125,22 @@ def test_setitem_clears_freq(self): a[0] = pd.Timedelta("1H") assert a.freq is None + @pytest.mark.parametrize( + "obj", + [ + pd.Timedelta(seconds=1), + pd.Timedelta(seconds=1).to_timedelta64(), + pd.Timedelta(seconds=1).to_pytimedelta(), + ], + ) + def test_setitem_objects(self, obj): + # make sure we accept timedelta64 and timedelta in addition to Timedelta + tdi = pd.timedelta_range("2 Days", periods=4, freq="H") + arr = TimedeltaArray(tdi, freq=tdi.freq) + + arr[0] = obj + assert arr[0] == pd.Timedelta(seconds=1) + class TestReductions: def test_min_max(self): diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index d75016824d6cf..c760c75e44f6b 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -418,7 +418,7 @@ def test_value_counts_unique_nunique_null(self, null_obj): values = o._shallow_copy(v) else: o = o.copy() - o[0:2] = iNaT + o[0:2] = pd.NaT values = o._values elif needs_i8_conversion(o):
The initial impetus for this was avoiding two try/excepts in Block methods (i.e. the diff in internals.blocks). This uncovered the bug in DTA/TDA, which accounts for the rest of the diff.
https://api.github.com/repos/pandas-dev/pandas/pulls/27704
2019-08-01T23:15:43Z
2019-08-04T21:58:00Z
2019-08-04T21:58:00Z
2019-08-04T23:12:01Z
Backport PR #27701 on branch 0.25.x (CI: Fixed CI)
diff --git a/ci/deps/travis-36-locale.yaml b/ci/deps/travis-36-locale.yaml index 0d9a760914dab..7da4abb9283df 100644 --- a/ci/deps/travis-36-locale.yaml +++ b/ci/deps/travis-36-locale.yaml @@ -29,13 +29,13 @@ dependencies: - s3fs=0.0.8 - scipy - sqlalchemy=1.1.4 - - xarray=0.8.2 + - xarray=0.10 - xlrd - xlsxwriter - xlwt # universal - - pytest>=4.0.2 - - pytest-xdist + - pytest>=5.0.1 + - pytest-xdist>=1.29.0 - pytest-mock - pip - pip:
Backport PR #27701: CI: Fixed CI
https://api.github.com/repos/pandas-dev/pandas/pulls/27703
2019-08-01T22:43:02Z
2019-08-02T11:45:44Z
2019-08-02T11:45:44Z
2019-08-02T11:45:44Z
BUG: Concatenation warning still appears with sort=False
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index c80195af413f7..01e4046e8b743 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -125,7 +125,7 @@ Reshaping ^^^^^^^^^ - A ``KeyError`` is now raised if ``.unstack()`` is called on a :class:`Series` or :class:`DataFrame` with a flat :class:`Index` passing a name which is not the correct one (:issue:`18303`) -- +- :meth:`DataFrame.join` now suppresses the ``FutureWarning`` when the sort parameter is specified (:issue:`21952`) - Sparse diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5980e3d133374..2a93cd5937221 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -7217,10 +7217,14 @@ def _join_compat( # join indexes only using concat if can_concat: if how == "left": - res = concat(frames, axis=1, join="outer", verify_integrity=True) + res = concat( + frames, axis=1, join="outer", verify_integrity=True, sort=sort + ) return res.reindex(self.index, copy=False) else: - return concat(frames, axis=1, join=how, verify_integrity=True) + return concat( + frames, axis=1, join=how, verify_integrity=True, sort=sort + ) joined = frames[0] diff --git a/pandas/tests/frame/test_join.py b/pandas/tests/frame/test_join.py index adace5e4784ae..220968d4b3d29 100644 --- a/pandas/tests/frame/test_join.py +++ b/pandas/tests/frame/test_join.py @@ -193,3 +193,32 @@ def test_join_left_sequence_non_unique_index(): ) tm.assert_frame_equal(joined, expected) + + +@pytest.mark.parametrize("sort_kw", [True, False, None]) +def test_suppress_future_warning_with_sort_kw(sort_kw): + a = DataFrame({"col1": [1, 2]}, index=["c", "a"]) + + b = DataFrame({"col2": [4, 5]}, index=["b", "a"]) + + c = DataFrame({"col3": [7, 8]}, index=["a", "b"]) + + expected = DataFrame( + { + "col1": {"a": 2.0, "b": float("nan"), "c": 1.0}, + "col2": {"a": 5.0, "b": 4.0, "c": float("nan")}, + "col3": {"a": 7.0, "b": 8.0, "c": float("nan")}, + } + ) + if sort_kw is False: + expected = expected.reindex(index=["c", "a", "b"]) + + if sort_kw is None: + # only warn if not explicitly specified + ctx = tm.assert_produces_warning(FutureWarning, check_stacklevel=False) + else: + ctx = tm.assert_produces_warning(None, check_stacklevel=False) + + with ctx: + result = a.join([b, c], how="outer", sort=sort_kw) + tm.assert_frame_equal(result, expected)
- [x] closes #21952 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27702
2019-08-01T21:14:26Z
2019-08-04T21:59:13Z
2019-08-04T21:59:13Z
2019-08-12T21:24:42Z
CI: Fixed CI
diff --git a/ci/deps/travis-36-locale.yaml b/ci/deps/travis-36-locale.yaml index 0d9a760914dab..7da4abb9283df 100644 --- a/ci/deps/travis-36-locale.yaml +++ b/ci/deps/travis-36-locale.yaml @@ -29,13 +29,13 @@ dependencies: - s3fs=0.0.8 - scipy - sqlalchemy=1.1.4 - - xarray=0.8.2 + - xarray=0.10 - xlrd - xlsxwriter - xlwt # universal - - pytest>=4.0.2 - - pytest-xdist + - pytest>=5.0.1 + - pytest-xdist>=1.29.0 - pytest-mock - pip - pip:
cc @jbrockmendel
https://api.github.com/repos/pandas-dev/pandas/pulls/27701
2019-08-01T20:42:51Z
2019-08-01T22:42:51Z
2019-08-01T22:42:51Z
2019-08-01T22:42:52Z
BUG: grouby(axis=1) cannot select column names
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index cc4bab8b9a923..a266f79aed02c 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -166,6 +166,7 @@ Groupby/resample/rolling - - +- Bug in :meth:`DataFrame.groupby` not offering selection by column name when ``axis=1`` (:issue:`27614`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 1d88ebd26b1b6..5c32550af3883 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -606,10 +606,10 @@ def is_in_obj(gpr): elif is_in_axis(gpr): # df.groupby('name') if gpr in obj: if validate: - obj._check_label_or_level_ambiguity(gpr) + obj._check_label_or_level_ambiguity(gpr, axis=axis) in_axis, name, gpr = True, gpr, obj[gpr] exclusions.append(name) - elif obj._is_level_reference(gpr): + elif obj._is_level_reference(gpr, axis=axis): in_axis, name, level, gpr = False, None, gpr, None else: raise KeyError(gpr) diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 2379d25ebe5aa..4556b22b57279 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1860,3 +1860,25 @@ def test_groupby_groups_in_BaseGrouper(): result = df.groupby(["beta", pd.Grouper(level="alpha")]) expected = df.groupby(["beta", "alpha"]) assert result.groups == expected.groups + + +@pytest.mark.parametrize("group_name", ["x", ["x"]]) +def test_groupby_axis_1(group_name): + # GH 27614 + df = pd.DataFrame( + np.arange(12).reshape(3, 4), index=[0, 1, 0], columns=[10, 20, 10, 20] + ) + df.index.name = "y" + df.columns.name = "x" + + results = df.groupby(group_name, axis=1).sum() + expected = df.T.groupby(group_name).sum().T + assert_frame_equal(results, expected) + + # test on MI column + iterables = [["bar", "baz", "foo"], ["one", "two"]] + mi = pd.MultiIndex.from_product(iterables=iterables, names=["x", "x1"]) + df = pd.DataFrame(np.arange(18).reshape(3, 6), index=[0, 1, 0], columns=mi) + results = df.groupby(group_name, axis=1).sum() + expected = df.T.groupby(group_name).sum().T + assert_frame_equal(results, expected)
- [x] closes #27614 - [x] tests added / passed - [ ] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27700
2019-08-01T20:13:50Z
2019-08-02T13:31:00Z
2019-08-02T13:31:00Z
2019-08-02T13:44:13Z
BUG: DTA/TDA incorrectly accepting iNaT for setitem
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index f86b307e5ede3..47b138a9e1604 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -499,9 +499,6 @@ def __setitem__( value = self._unbox_scalar(value) elif is_valid_nat_for_dtype(value, self.dtype): value = iNaT - elif not isna(value) and lib.is_integer(value) and value == iNaT: - # exclude misc e.g. object() and any NAs not allowed above - value = iNaT else: msg = ( "'value' should be a '{scalar}', 'NaT', or array of those. " diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index d9646feaf661e..ffda2f4de2700 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -682,15 +682,15 @@ def test_casting_nat_setitem_array(array, casting_nats): [ ( pd.TimedeltaIndex(["1 Day", "3 Hours", "NaT"])._data, - (np.datetime64("NaT", "ns"),), + (np.datetime64("NaT", "ns"), pd.NaT.value), ), ( pd.date_range("2000-01-01", periods=3, freq="D")._data, - (np.timedelta64("NaT", "ns"),), + (np.timedelta64("NaT", "ns"), pd.NaT.value), ), ( pd.period_range("2000-01-01", periods=3, freq="D")._data, - (np.datetime64("NaT", "ns"), np.timedelta64("NaT", "ns")), + (np.datetime64("NaT", "ns"), np.timedelta64("NaT", "ns"), pd.NaT.value), ), ], ids=lambda x: type(x).__name__, diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index d75016824d6cf..c760c75e44f6b 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -418,7 +418,7 @@ def test_value_counts_unique_nunique_null(self, null_obj): values = o._shallow_copy(v) else: o = o.copy() - o[0:2] = iNaT + o[0:2] = pd.NaT values = o._values elif needs_i8_conversion(o):
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry First of several related PRs.
https://api.github.com/repos/pandas-dev/pandas/pulls/27699
2019-08-01T18:16:28Z
2019-08-02T15:59:17Z
2019-08-02T15:59:17Z
2019-08-02T16:03:45Z
Backport PR #27478 on branch 0.25.x (Add a Roadmap)
diff --git a/doc/source/development/index.rst b/doc/source/development/index.rst index a149f31118ed5..c7710ff19f078 100644 --- a/doc/source/development/index.rst +++ b/doc/source/development/index.rst @@ -16,3 +16,4 @@ Development internals extending developer + roadmap diff --git a/doc/source/development/roadmap.rst b/doc/source/development/roadmap.rst new file mode 100644 index 0000000000000..88e0a18e6b81a --- /dev/null +++ b/doc/source/development/roadmap.rst @@ -0,0 +1,193 @@ +.. _roadmap: + +======= +Roadmap +======= + +This page provides an overview of the major themes in pandas' development. Each of +these items requires a relatively large amount of effort to implement. These may +be achieved more quickly with dedicated funding or interest from contributors. + +An item being on the roadmap does not mean that it will *necessarily* happen, even +with unlimited funding. During the implementation period we may discover issues +preventing the adoption of the feature. + +Additionally, an item *not* being on the roadmap does not exclude it from inclusion +in pandas. The roadmap is intended for larger, fundamental changes to the project that +are likely to take months or years of developer time. Smaller-scoped items will continue +to be tracked on our `issue tracker <https://github.com/pandas-dev/pandas/issues>`__. + +See :ref:`roadmap.evolution` for proposing changes to this document. + +Extensibility +------------- + +Pandas :ref:`extending.extension-types` allow for extending NumPy types with custom +data types and array storage. Pandas uses extension types internally, and provides +an interface for 3rd-party libraries to define their own custom data types. + +Many parts of pandas still unintentionally convert data to a NumPy array. +These problems are especially pronounced for nested data. + +We'd like to improve the handling of extension arrays throughout the library, +making their behavior more consistent with the handling of NumPy arrays. We'll do this +by cleaning up pandas' internals and adding new methods to the extension array interface. + +String data type +---------------- + +Currently, pandas stores text data in an ``object`` -dtype NumPy array. +The current implementation has two primary drawbacks: First, ``object`` -dtype +is not specific to strings: any Python object can be stored in an ``object`` -dtype +array, not just strings. Second: this is not efficient. The NumPy memory model +isn't especially well-suited to variable width text data. + +To solve the first issue, we propose a new extension type for string data. This +will initially be opt-in, with users explicitly requesting ``dtype="string"``. +The array backing this string dtype may initially be the current implementation: +an ``object`` -dtype NumPy array of Python strings. + +To solve the second issue (performance), we'll explore alternative in-memory +array libraries (for example, Apache Arrow). As part of the work, we may +need to implement certain operations expected by pandas users (for example +the algorithm used in, ``Series.str.upper``). That work may be done outside of +pandas. + +Apache Arrow interoperability +----------------------------- + +`Apache Arrow <https://arrow.apache.org>`__ is a cross-language development +platform for in-memory data. The Arrow logical types are closely aligned with +typical pandas use cases. + +We'd like to provide better-integrated support for Arrow memory and data types +within pandas. This will let us take advantage of its I/O capabilities and +provide for better interoperability with other languages and libraries +using Arrow. + +Block manager rewrite +--------------------- + +We'd like to replace pandas current internal data structures (a collection of +1 or 2-D arrays) with a simpler collection of 1-D arrays. + +Pandas internal data model is quite complex. A DataFrame is made up of +one or more 2-dimensional "blocks", with one or more blocks per dtype. This +collection of 2-D arrays is managed by the BlockManager. + +The primary benefit of the BlockManager is improved performance on certain +operations (construction from a 2D array, binary operations, reductions across the columns), +especially for wide DataFrames. However, the BlockManager substantially increases the +complexity and maintenance burden of pandas. + +By replacing the BlockManager we hope to achieve + +* Substantially simpler code +* Easier extensibility with new logical types +* Better user control over memory use and layout +* Improved micro-performance +* Option to provide a C / Cython API to pandas' internals + +See `these design documents <https://dev.pandas.io/pandas2/internal-architecture.html#removal-of-blockmanager-new-dataframe-internals>`__ +for more. + +Decoupling of indexing and internals +------------------------------------ + +The code for getting and setting values in pandas' data structures needs refactoring. +In particular, we must clearly separate code that converts keys (e.g., the argument +to ``DataFrame.loc``) to positions from code that uses uses these positions to get +or set values. This is related to the proposed BlockManager rewrite. Currently, the +BlockManager sometimes uses label-based, rather than position-based, indexing. +We propose that it should only work with positional indexing, and the translation of keys +to positions should be entirely done at a higher level. + +Indexing is a complicated API with many subtleties. This refactor will require care +and attention. More details are discussed at +https://github.com/pandas-dev/pandas/wiki/(Tentative)-rules-for-restructuring-indexing-code + +Numba-accelerated operations +---------------------------- + +`Numba <https://numba.pydata.org>`__ is a JIT compiler for Python code. We'd like to provide +ways for users to apply their own Numba-jitted functions where pandas accepts user-defined functions +(for example, :meth:`Series.apply`, :meth:`DataFrame.apply`, :meth:`DataFrame.applymap`, +and in groupby and window contexts). This will improve the performance of +user-defined-functions in these operations by staying within compiled code. + + +Documentation improvements +-------------------------- + +We'd like to improve the content, structure, and presentation of the pandas documentation. +Some specific goals include + +* Overhaul the HTML theme with a modern, responsive design (:issue:`15556`) +* Improve the "Getting Started" documentation, designing and writing learning paths + for users different backgrounds (e.g. brand new to programming, familiar with + other languages like R, already familiar with Python). +* Improve the overall organization of the documentation and specific subsections + of the documentation to make navigation and finding content easier. + +Package docstring validation +---------------------------- + +To improve the quality and consistency of pandas docstrings, we've developed +tooling to check docstrings in a variety of ways. +https://github.com/pandas-dev/pandas/blob/master/scripts/validate_docstrings.py +contains the checks. + +Like many other projects, pandas uses the +`numpydoc <https://numpydoc.readthedocs.io/en/latest/>`__ style for writing +docstrings. With the collaboration of the numpydoc maintainers, we'd like to +move the checks to a package other than pandas so that other projects can easily +use them as well. + +Performance monitoring +---------------------- + +Pandas uses `airspeed velocity <https://asv.readthedocs.io/en/stable/>`__ to +monitor for performance regressions. ASV itself is a fabulous tool, but requires +some additional work to be integrated into an open source project's workflow. + +The `asv-runner <https://github.com/asv-runner>`__ organization, currently made up +of pandas maintainers, provides tools built on top of ASV. We have a physical +machine for running a number of project's benchmarks, and tools managing the +benchmark runs and reporting on results. + +We'd like to fund improvements and maintenance of these tools to + +* Be more stable. Currently, they're maintained on the nights and weekends when + a maintainer has free time. +* Tune the system for benchmarks to improve stability, following + https://pyperf.readthedocs.io/en/latest/system.html +* Build a GitHub bot to request ASV runs *before* a PR is merged. Currently, the + benchmarks are only run nightly. + +.. _roadmap.evolution: + +Roadmap Evolution +----------------- + +Pandas continues to evolve. The direction is primarily determined by community +interest. Everyone is welcome to review existing items on the roadmap and +to propose a new item. + +Each item on the roadmap should be a short summary of a larger design proposal. +The proposal should include + +1. Short summary of the changes, which would be appropriate for inclusion in + the roadmap if accepted. +2. Motivation for the changes. +3. An explanation of why the change is in scope for pandas. +4. Detailed design: Preferably with example-usage (even if not implemented yet) + and API documentation +5. API Change: Any API changes that may result from the proposal. + +That proposal may then be submitted as a GitHub issue, where the pandas maintainers +can review and comment on the design. The `pandas mailing list <https://mail.python.org/mailman/listinfo/pandas-dev>`__ +should be notified of the proposal. + +When there's agreement that an implementation +would be welcome, the roadmap should be updated to include the summary and a +link to the discussion issue.
Backport PR #27478: Add a Roadmap
https://api.github.com/repos/pandas-dev/pandas/pulls/27698
2019-08-01T18:04:23Z
2019-08-02T11:47:46Z
2019-08-02T11:47:46Z
2019-08-02T11:47:50Z
Replace with nested dict raises for overlapping keys
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 7fe358d3820f2..7a10447e3ad40 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -207,6 +207,7 @@ ExtensionArray Other ^^^^^ - Trying to set the ``display.precision``, ``display.max_rows`` or ``display.max_columns`` using :meth:`set_option` to anything but a ``None`` or a positive int will raise a ``ValueError`` (:issue:`23348`) +- Using :meth:`DataFrame.replace` with overlapping keys in a nested dictionary will no longer raise, now matching the behavior of a flat dictionary (:issue:`27660`) - :meth:`DataFrame.to_csv` and :meth:`Series.to_csv` now support dicts as ``compression`` argument with key ``'method'`` being the compression method and others as additional compression options when the compression method is ``'zip'``. (:issue:`26023`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index fac5e0f085fc6..6ade69fb4ca9d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6669,11 +6669,7 @@ def replace( for k, v in items: keys, values = list(zip(*v.items())) or ([], []) - if set(keys) & set(values): - raise ValueError( - "Replacement not allowed with " - "overlapping keys and values" - ) + to_rep_dict[k] = list(keys) value_dict[k] = list(values) diff --git a/pandas/tests/frame/test_replace.py b/pandas/tests/frame/test_replace.py index 2862615ef8585..b341ed6a52ca5 100644 --- a/pandas/tests/frame/test_replace.py +++ b/pandas/tests/frame/test_replace.py @@ -1069,18 +1069,24 @@ def test_replace_truthy(self): e = df assert_frame_equal(r, e) - def test_replace_int_to_int_chain(self): + def test_nested_dict_overlapping_keys_replace_int(self): + # GH 27660 keep behaviour consistent for simple dictionary and + # nested dictionary replacement df = DataFrame({"a": list(range(1, 5))}) - with pytest.raises(ValueError, match="Replacement not allowed .+"): - df.replace({"a": dict(zip(range(1, 5), range(2, 6)))}) - def test_replace_str_to_str_chain(self): + result = df.replace({"a": dict(zip(range(1, 5), range(2, 6)))}) + expected = df.replace(dict(zip(range(1, 5), range(2, 6)))) + assert_frame_equal(result, expected) + + def test_nested_dict_overlapping_keys_replace_str(self): + # GH 27660 a = np.arange(1, 5) astr = a.astype(str) bstr = np.arange(2, 6).astype(str) df = DataFrame({"a": astr}) - with pytest.raises(ValueError, match="Replacement not allowed .+"): - df.replace({"a": dict(zip(astr, bstr))}) + result = df.replace(dict(zip(astr, bstr))) + expected = df.replace({"a": dict(zip(astr, bstr))}) + assert_frame_equal(result, expected) def test_replace_swapping_bug(self): df = pd.DataFrame({"a": [True, False, True]})
- [x] closes #27660 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27696
2019-08-01T14:26:59Z
2019-08-27T14:09:42Z
2019-08-27T14:09:41Z
2019-08-27T14:09:55Z
Backport PR #27689 on branch 0.25.x (DOC: 0.25 fixups)
diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst index 592b4748126c1..0509a370d7866 100644 --- a/doc/source/whatsnew/index.rst +++ b/doc/source/whatsnew/index.rst @@ -16,6 +16,7 @@ Version 0.25 .. toctree:: :maxdepth: 2 + v0.25.1 v0.25.0 Version 0.24 diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 5b8f980d27b9d..74232c41d8a8c 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -1267,4 +1267,4 @@ Other Contributors ~~~~~~~~~~~~ -.. contributors:: 0.24.x..HEAD +.. contributors:: v0.24.x..HEAD diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 40fefe7ec43a8..c80195af413f7 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -1,7 +1,3 @@ -:orphan: - -.. TODO. Remove the orphan tag. - .. _whatsnew_0251: What's new in 0.25.1 (July XX, 2019) @@ -166,6 +162,4 @@ Other Contributors ~~~~~~~~~~~~ -.. TODO. Change to v0.25.0..HEAD - -.. contributors:: HEAD..HEAD +.. contributors:: v0.25.0..HEAD
Backport PR #27689: DOC: 0.25 fixups
https://api.github.com/repos/pandas-dev/pandas/pulls/27694
2019-08-01T13:57:13Z
2019-08-01T20:40:52Z
2019-08-01T20:40:52Z
2019-08-01T20:40:52Z
Backport PR #27653 on branch 0.25.x (BUG: Fix dir(interval_index))
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index fb67decb46b64..40fefe7ec43a8 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -78,7 +78,7 @@ Strings Interval ^^^^^^^^ - +- Bug in :class:`IntervalIndex` where `dir(obj)` would raise ``ValueError`` (:issue:`27571`) - - - diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 27ee685acfde7..fef17fd43a8e3 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -969,6 +969,7 @@ _TYPE_MAP = { 'M': 'datetime64', 'timedelta64[ns]': 'timedelta64', 'm': 'timedelta64', + 'interval': 'interval', } # types only exist on certain platform diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 7c293ca4e50b0..d4c6d780709a5 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -1957,8 +1957,11 @@ def _validate(data): values = getattr(data, "values", data) # Series / Index values = getattr(values, "categories", values) # categorical / normal - # missing values obfuscate type inference -> skip - inferred_dtype = lib.infer_dtype(values, skipna=True) + try: + inferred_dtype = lib.infer_dtype(values, skipna=True) + except ValueError: + # GH#27571 mostly occurs with ExtensionArray + inferred_dtype = None if inferred_dtype not in allowed_types: raise AttributeError("Can only use .str accessor with string " "values!") diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 4d688976cd50b..6ab3830317059 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -1134,6 +1134,17 @@ def test_categorical(self): result = lib.infer_dtype(Series(arr), skipna=True) assert result == "categorical" + def test_interval(self): + idx = pd.IntervalIndex.from_breaks(range(5), closed="both") + inferred = lib.infer_dtype(idx, skipna=False) + assert inferred == "interval" + + inferred = lib.infer_dtype(idx._data, skipna=False) + assert inferred == "interval" + + inferred = lib.infer_dtype(pd.Series(idx), skipna=False) + assert inferred == "interval" + class TestNumberScalar: def test_is_number(self): diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index c61af1ce70aed..c1a21e6a7f152 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -1095,3 +1095,10 @@ def test_is_all_dates(self): ) year_2017_index = pd.IntervalIndex([year_2017]) assert not year_2017_index.is_all_dates + + +def test_dir(): + # GH#27571 dir(interval_index) should not raise + index = IntervalIndex.from_arrays([0, 1], [1, 2]) + result = dir(index) + assert "str" not in result
Backport PR #27653: BUG: Fix dir(interval_index)
https://api.github.com/repos/pandas-dev/pandas/pulls/27693
2019-08-01T12:57:14Z
2019-08-01T13:56:31Z
2019-08-01T13:56:31Z
2019-08-01T13:56:31Z
Backport PR #27580 on branch 0.25.x
diff --git a/doc/source/install.rst b/doc/source/install.rst index 352b56ebd3020..fc99b458fa0af 100644 --- a/doc/source/install.rst +++ b/doc/source/install.rst @@ -15,35 +15,10 @@ Instructions for installing from source, `PyPI <https://pypi.org/project/pandas>`__, `ActivePython <https://www.activestate.com/activepython/downloads>`__, various Linux distributions, or a `development version <http://github.com/pandas-dev/pandas>`__ are also provided. -.. _install.dropping-27: - -Plan for dropping Python 2.7 ----------------------------- - -The Python core team plans to stop supporting Python 2.7 on January 1st, 2020. -In line with `NumPy's plans`_, all pandas releases through December 31, 2018 -will support Python 2. - -The 0.24.x feature release will be the last release to -support Python 2. The released package will continue to be available on -PyPI and through conda. - - Starting **January 1, 2019**, all new feature releases (> 0.24) will be Python 3 only. - -If there are people interested in continued support for Python 2.7 past December -31, 2018 (either backporting bug fixes or funding) please reach out to the -maintainers on the issue tracker. - -For more information, see the `Python 3 statement`_ and the `Porting to Python 3 guide`_. - -.. _NumPy's plans: https://github.com/numpy/numpy/blob/master/doc/neps/nep-0014-dropping-python2.7-proposal.rst#plan-for-dropping-python-27-support -.. _Python 3 statement: http://python3statement.org/ -.. _Porting to Python 3 guide: https://docs.python.org/3/howto/pyporting.html - Python version support ---------------------- -Officially Python 2.7, 3.5, 3.6, and 3.7. +Officially Python 3.5.3 and above, 3.6, and 3.7. Installing pandas ----------------- diff --git a/doc/source/whatsnew/v0.23.0.rst b/doc/source/whatsnew/v0.23.0.rst index 62cf977d8c8ac..f4c283ea742f7 100644 --- a/doc/source/whatsnew/v0.23.0.rst +++ b/doc/source/whatsnew/v0.23.0.rst @@ -31,7 +31,7 @@ Check the :ref:`API Changes <whatsnew_0230.api_breaking>` and :ref:`deprecations .. warning:: Starting January 1, 2019, pandas feature releases will support Python 3 only. - See :ref:`install.dropping-27` for more. + See `Dropping Python 2.7 <https://pandas.pydata.org/pandas-docs/version/0.24/install.html#install-dropping-27>`_ for more. .. contents:: What's new in v0.23.0 :local: diff --git a/doc/source/whatsnew/v0.23.1.rst b/doc/source/whatsnew/v0.23.1.rst index d730a57a01a60..03b7d9db6bc63 100644 --- a/doc/source/whatsnew/v0.23.1.rst +++ b/doc/source/whatsnew/v0.23.1.rst @@ -12,7 +12,7 @@ and bug fixes. We recommend that all users upgrade to this version. .. warning:: Starting January 1, 2019, pandas feature releases will support Python 3 only. - See :ref:`install.dropping-27` for more. + See `Dropping Python 2.7 <https://pandas.pydata.org/pandas-docs/version/0.24/install.html#install-dropping-27>`_ for more. .. contents:: What's new in v0.23.1 :local: diff --git a/doc/source/whatsnew/v0.23.2.rst b/doc/source/whatsnew/v0.23.2.rst index df8cc12e3385e..9f24092d1d4ae 100644 --- a/doc/source/whatsnew/v0.23.2.rst +++ b/doc/source/whatsnew/v0.23.2.rst @@ -17,7 +17,7 @@ and bug fixes. We recommend that all users upgrade to this version. .. warning:: Starting January 1, 2019, pandas feature releases will support Python 3 only. - See :ref:`install.dropping-27` for more. + See `Dropping Python 2.7 <https://pandas.pydata.org/pandas-docs/version/0.24/install.html#install-dropping-27>`_ for more. .. contents:: What's new in v0.23.2 :local: diff --git a/doc/source/whatsnew/v0.23.4.rst b/doc/source/whatsnew/v0.23.4.rst index 060d1fc8eba34..eadac6f569926 100644 --- a/doc/source/whatsnew/v0.23.4.rst +++ b/doc/source/whatsnew/v0.23.4.rst @@ -12,7 +12,7 @@ and bug fixes. We recommend that all users upgrade to this version. .. warning:: Starting January 1, 2019, pandas feature releases will support Python 3 only. - See :ref:`install.dropping-27` for more. + See `Dropping Python 2.7 <https://pandas.pydata.org/pandas-docs/version/0.24/install.html#install-dropping-27>`_ for more. .. contents:: What's new in v0.23.4 :local: diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst index a66056f661de3..d9f41d2a75116 100644 --- a/doc/source/whatsnew/v0.24.0.rst +++ b/doc/source/whatsnew/v0.24.0.rst @@ -6,7 +6,7 @@ What's new in 0.24.0 (January 25, 2019) .. warning:: The 0.24.x series of releases will be the last to support Python 2. Future feature - releases will support Python 3 only. See :ref:`install.dropping-27` for more + releases will support Python 3 only. See `Dropping Python 2.7 <https://pandas.pydata.org/pandas-docs/version/0.24/install.html#install-dropping-27>`_ for more details. {{ header }} diff --git a/doc/source/whatsnew/v0.24.1.rst b/doc/source/whatsnew/v0.24.1.rst index 1b0232cad7476..aead8c48eb9b7 100644 --- a/doc/source/whatsnew/v0.24.1.rst +++ b/doc/source/whatsnew/v0.24.1.rst @@ -6,7 +6,7 @@ Whats new in 0.24.1 (February 3, 2019) .. warning:: The 0.24.x series of releases will be the last to support Python 2. Future feature - releases will support Python 3 only. See :ref:`install.dropping-27` for more. + releases will support Python 3 only. See `Dropping Python 2.7 <https://pandas.pydata.org/pandas-docs/version/0.24/install.html#install-dropping-27>`_ for more. {{ header }} diff --git a/doc/source/whatsnew/v0.24.2.rst b/doc/source/whatsnew/v0.24.2.rst index da8064893e8a8..d1a893f99cff4 100644 --- a/doc/source/whatsnew/v0.24.2.rst +++ b/doc/source/whatsnew/v0.24.2.rst @@ -6,7 +6,7 @@ Whats new in 0.24.2 (March 12, 2019) .. warning:: The 0.24.x series of releases will be the last to support Python 2. Future feature - releases will support Python 3 only. See :ref:`install.dropping-27` for more. + releases will support Python 3 only. See `Dropping Python 2.7 <https://pandas.pydata.org/pandas-docs/version/0.24/install.html#install-dropping-27>`_ for more. {{ header }} diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index 42e756635e739..5b8f980d27b9d 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -6,7 +6,7 @@ What's new in 0.25.0 (July 18, 2019) .. warning:: Starting with the 0.25.x series of releases, pandas only supports Python 3.5.3 and higher. - See :ref:`install.dropping-27` for more details. + See `Dropping Python 2.7 <https://pandas.pydata.org/pandas-docs/version/0.24/install.html#install-dropping-27>`_ for more details. .. warning::
closes #27558
https://api.github.com/repos/pandas-dev/pandas/pulls/27691
2019-08-01T12:24:09Z
2019-08-01T13:56:20Z
2019-08-01T13:56:20Z
2019-10-29T06:51:25Z
DOC: 0.25 fixups
diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst index b7555ed94a1ed..aeab2cf5809e7 100644 --- a/doc/source/whatsnew/index.rst +++ b/doc/source/whatsnew/index.rst @@ -24,6 +24,7 @@ Version 0.25 .. toctree:: :maxdepth: 2 + v0.25.1 v0.25.0 Version 0.24 diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index f4ef26dd8b740..51d05911829d6 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -1268,4 +1268,4 @@ Other Contributors ~~~~~~~~~~~~ -.. contributors:: 0.24.x..HEAD +.. contributors:: v0.24.x..HEAD diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index fb67decb46b64..fabdde33f5660 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -1,7 +1,3 @@ -:orphan: - -.. TODO. Remove the orphan tag. - .. _whatsnew_0251: What's new in 0.25.1 (July XX, 2019) @@ -166,6 +162,4 @@ Other Contributors ~~~~~~~~~~~~ -.. TODO. Change to v0.25.0..HEAD - -.. contributors:: HEAD..HEAD +.. contributors:: v0.25.0..HEAD
* fix tag for contributors * fix 0.25.1 contributors * remove orphan Closes https://github.com/pandas-dev/pandas/issues/27687
https://api.github.com/repos/pandas-dev/pandas/pulls/27689
2019-08-01T12:07:54Z
2019-08-01T13:57:00Z
2019-08-01T13:57:00Z
2019-10-22T12:10:11Z
CLN: Prune unnecessary internals
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index da3db1c18e534..811836d0e8a4d 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -671,7 +671,7 @@ def _transform_item_by_item(self, obj, wrapper): except Exception: pass - if len(output) == 0: # pragma: no cover + if len(output) == 0: raise TypeError("Transform function invalid for data types") columns = obj.columns diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 15b94e59c065c..12b9cf25687cf 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1206,7 +1206,7 @@ def mean(self, *args, **kwargs): ) except GroupByError: raise - except Exception: # pragma: no cover + except Exception: with _group_selection_context(self): f = lambda x: x.mean(axis=self.axis, **kwargs) return self._python_agg_general(f) @@ -1232,7 +1232,7 @@ def median(self, **kwargs): ) except GroupByError: raise - except Exception: # pragma: no cover + except Exception: def f(x): if isinstance(x, np.ndarray): @@ -2470,7 +2470,7 @@ def groupby(obj, by, **kwds): from pandas.core.groupby.generic import DataFrameGroupBy klass = DataFrameGroupBy - else: # pragma: no cover + else: raise TypeError("invalid type: {}".format(obj)) return klass(obj, by, **kwds) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 4a8ee8fa2c5f4..6d70fcfb62d52 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -760,7 +760,7 @@ def to_native_types(self, slicer=None, na_rep="nan", quoting=None, **kwargs): values[mask] = na_rep return values - # block actions #### + # block actions # def copy(self, deep=True): """ copy constructor """ values = self.values @@ -1538,16 +1538,14 @@ def quantile(self, qs, interpolation="linear", axis=0): ).reshape(len(values), len(qs)) else: # asarray needed for Sparse, see GH#24600 - # Note: we use self.values below instead of values because the - # `asi8` conversion above will behave differently under `isna` - mask = np.asarray(isna(self.values)) + mask = np.asarray(isna(values)) result = nanpercentile( values, np.array(qs) * 100, axis=axis, na_value=self.fill_value, mask=mask, - ndim=self.ndim, + ndim=values.ndim, interpolation=interpolation, ) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 344d41ed26943..8956821740bf3 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -975,8 +975,6 @@ def iget(self, i): """ block = self.blocks[self._blknos[i]] values = block.iget(self._blklocs[i]) - if values.ndim != 1: - return values # shortcut for select a single-dim from a 2-dim BM return SingleBlockManager( diff --git a/pandas/io/clipboards.py b/pandas/io/clipboards.py index 0006824f09fe7..d38221d784273 100644 --- a/pandas/io/clipboards.py +++ b/pandas/io/clipboards.py @@ -121,7 +121,7 @@ def to_clipboard(obj, excel=True, sep=None, **kwargs): # pragma: no cover return except TypeError: warnings.warn( - "to_clipboard in excel mode requires a single " "character separator." + "to_clipboard in excel mode requires a single character separator." ) elif sep is not None: warnings.warn("to_clipboard with excel=False ignores the sep argument") diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 7afc234446a71..154656fbb250b 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -297,7 +297,7 @@ def read_excel( for arg in ("sheet", "sheetname", "parse_cols"): if arg in kwds: raise TypeError( - "read_excel() got an unexpected keyword argument " "`{}`".format(arg) + "read_excel() got an unexpected keyword argument `{}`".format(arg) ) if not isinstance(io, ExcelFile): @@ -353,7 +353,7 @@ def __init__(self, filepath_or_buffer): self.book = self.load_workbook(filepath_or_buffer) else: raise ValueError( - "Must explicitly set engine if not passing in" " buffer or path for io." + "Must explicitly set engine if not passing in buffer or path for io." ) @property @@ -713,9 +713,7 @@ def _get_sheet_name(self, sheet_name): if sheet_name is None: sheet_name = self.cur_sheet if sheet_name is None: # pragma: no cover - raise ValueError( - "Must pass explicit sheet_name or set " "cur_sheet property" - ) + raise ValueError("Must pass explicit sheet_name or set cur_sheet property") return sheet_name def _value_with_fmt(self, val): @@ -851,7 +849,7 @@ def parse( """ if "chunksize" in kwds: raise NotImplementedError( - "chunksize keyword of read_excel " "is not implemented" + "chunksize keyword of read_excel is not implemented" ) return self._reader.parse( diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py index 35a62b627823a..6fe22f14c2c5b 100644 --- a/pandas/io/feather_format.py +++ b/pandas/io/feather_format.py @@ -53,7 +53,7 @@ def to_feather(df, path): if df.index.name is not None: raise ValueError( - "feather does not serialize index meta-data on a " "default index" + "feather does not serialize index meta-data on a default index" ) # validate columns diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py index d86bf432b83c4..60daf311397e8 100644 --- a/pandas/io/formats/csvs.py +++ b/pandas/io/formats/csvs.py @@ -96,9 +96,7 @@ def __init__( # validate mi options if self.has_mi_columns: if cols is not None: - raise TypeError( - "cannot specify cols with a MultiIndex on the " "columns" - ) + raise TypeError("cannot specify cols with a MultiIndex on the columns") if cols is not None: if isinstance(cols, ABCIndexClass): @@ -158,7 +156,7 @@ def save(self): """ # GH21227 internal compression is not used when file-like passed. if self.compression and hasattr(self.path_or_buf, "write"): - msg = "compression has no effect when passing file-like " "object as input." + msg = "compression has no effect when passing file-like object as input." warnings.warn(msg, RuntimeWarning, stacklevel=2) # when zip compression is called. diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 6e4894bdb0f56..980fc4888d625 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -2,9 +2,10 @@ Internal module for formatting output data in csv, html, and latex files. This module also applies to display formatting. """ - +import decimal from functools import partial from io import StringIO +import math import re from shutil import get_terminal_size from typing import ( @@ -862,7 +863,7 @@ def to_latex( with codecs.open(self.buf, "w", encoding=encoding) as f: latex_renderer.write_result(f) else: - raise TypeError("buf is not a file name and it has no write " "method") + raise TypeError("buf is not a file name and it has no write method") def _format_col(self, i: int) -> List[str]: frame = self.tr_frame @@ -907,7 +908,7 @@ def to_html( with open(self.buf, "w") as f: buffer_put_lines(f, html) else: - raise TypeError("buf is not a file name and it has no write " " method") + raise TypeError("buf is not a file name and it has no write method") def _get_formatted_column_labels(self, frame: "DataFrame") -> List[List[str]]: from pandas.core.index import _sparsify @@ -1782,9 +1783,6 @@ def __call__(self, num: Union[int, float]) -> str: @return: engineering formatted string """ - import decimal - import math - dnum = decimal.Decimal(str(num)) if decimal.Decimal.is_nan(dnum): diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 3e5b200c4643b..f4b00b0aac5f7 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -687,7 +687,7 @@ def parser_f( read_csv = Appender( _doc_read_csv_and_table.format( func_name="read_csv", - summary=("Read a comma-separated values (csv) file " "into DataFrame."), + summary=("Read a comma-separated values (csv) file into DataFrame."), _default_sep="','", ) )(read_csv) @@ -770,7 +770,7 @@ def read_fwf( if colspecs is None and widths is None: raise ValueError("Must specify either colspecs or widths") elif colspecs not in (None, "infer") and widths is not None: - raise ValueError("You must specify only one of 'widths' and " "'colspecs'") + raise ValueError("You must specify only one of 'widths' and 'colspecs'") # Compute 'colspecs' from 'widths', if specified. if widths is not None: @@ -901,9 +901,7 @@ def _get_options_with_defaults(self, engine): # see gh-12935 if argname == "mangle_dupe_cols" and not value: - raise ValueError( - "Setting mangle_dupe_cols=False is " "not supported yet" - ) + raise ValueError("Setting mangle_dupe_cols=False is not supported yet") else: options[argname] = value @@ -942,7 +940,7 @@ def _check_file_or_buffer(self, f, engine): # needs to have that attribute ("next" for Python 2.x, "__next__" # for Python 3.x) if engine != "c" and not hasattr(f, next_attr): - msg = "The 'python' engine cannot iterate " "through this file buffer." + msg = "The 'python' engine cannot iterate through this file buffer." raise ValueError(msg) return engine @@ -959,7 +957,7 @@ def _clean_options(self, options, engine): # C engine not supported yet if engine == "c": if options["skipfooter"] > 0: - fallback_reason = "the 'c' engine does not support" " skipfooter" + fallback_reason = "the 'c' engine does not support skipfooter" engine = "python" encoding = sys.getfilesystemencoding() or "utf-8" @@ -1397,11 +1395,11 @@ def __init__(self, kwds): raise ValueError("header must be integer or list of integers") if kwds.get("usecols"): raise ValueError( - "cannot specify usecols when " "specifying a multi-index header" + "cannot specify usecols when specifying a multi-index header" ) if kwds.get("names"): raise ValueError( - "cannot specify names when " "specifying a multi-index header" + "cannot specify names when specifying a multi-index header" ) # validate index_col that only contains integers @@ -1611,7 +1609,7 @@ def _get_name(icol): if col_names is None: raise ValueError( - ("Must supply column order to use {icol!s} " "as index").format( + ("Must supply column order to use {icol!s} as index").format( icol=icol ) ) @@ -2379,7 +2377,7 @@ def _make_reader(self, f): if sep is None or len(sep) == 1: if self.lineterminator: raise ValueError( - "Custom line terminators not supported in " "python parser (yet)" + "Custom line terminators not supported in python parser (yet)" ) class MyDialect(csv.Dialect): @@ -2662,7 +2660,7 @@ def _infer_columns(self): "number of header fields in the file" ) if len(columns) > 1: - raise TypeError("Cannot pass names with multi-index " "columns") + raise TypeError("Cannot pass names with multi-index columns") if self.usecols is not None: # Set _use_cols. We don't store columns because they are @@ -2727,7 +2725,7 @@ def _handle_usecols(self, columns, usecols_key): elif any(isinstance(u, str) for u in self.usecols): if len(columns) > 1: raise ValueError( - "If using multiple headers, usecols must " "be integers." + "If using multiple headers, usecols must be integers." ) col_indices = [] diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index da9264557931d..415cb50472a4c 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -366,7 +366,7 @@ def read_hdf(path_or_buf, key=None, mode="r", **kwargs): path_or_buf = _stringify_path(path_or_buf) if not isinstance(path_or_buf, str): raise NotImplementedError( - "Support for generic buffers has not " "been implemented." + "Support for generic buffers has not been implemented." ) try: exists = os.path.exists(path_or_buf) @@ -1047,7 +1047,7 @@ def append( """ if columns is not None: raise TypeError( - "columns is not a supported keyword in append, " "try data_columns" + "columns is not a supported keyword in append, try data_columns" ) if dropna is None: @@ -2161,7 +2161,7 @@ def set_atom( # which is an error raise TypeError( - "too many timezones in this block, create separate " "data columns" + "too many timezones in this block, create separate data columns" ) elif inferred_type == "unicode": raise TypeError("[unicode] is not implemented as a table column") @@ -2338,9 +2338,7 @@ def validate_attr(self, append): if append: existing_fields = getattr(self.attrs, self.kind_attr, None) if existing_fields is not None and existing_fields != list(self.values): - raise ValueError( - "appended items do not match existing items" " in table!" - ) + raise ValueError("appended items do not match existing items in table!") existing_dtype = getattr(self.attrs, self.dtype_attr, None) if existing_dtype is not None and existing_dtype != self.dtype: @@ -2834,7 +2832,7 @@ def write_multi_index(self, key, index): # write the level if is_extension_type(lev): raise NotImplementedError( - "Saving a MultiIndex with an " "extension dtype is not supported." + "Saving a MultiIndex with an extension dtype is not supported." ) level_key = "{key}_level{idx}".format(key=key, idx=i) conv_level = _convert_index( @@ -3079,7 +3077,7 @@ def validate_read(self, kwargs): kwargs = super().validate_read(kwargs) if "start" in kwargs or "stop" in kwargs: raise NotImplementedError( - "start and/or stop are not supported " "in fixed Sparse reading" + "start and/or stop are not supported in fixed Sparse reading" ) return kwargs @@ -3376,7 +3374,7 @@ def validate_multiindex(self, obj): return obj.reset_index(), levels except ValueError: raise ValueError( - "duplicate names/columns in the multi-index when " "storing as a table" + "duplicate names/columns in the multi-index when storing as a table" ) @property @@ -4081,7 +4079,7 @@ def read_column(self, column, where=None, start=None, stop=None): return False if where is not None: - raise TypeError("read_column does not currently accept a where " "clause") + raise TypeError("read_column does not currently accept a where clause") # find the axes for a in self.axes: @@ -4990,7 +4988,7 @@ def __init__(self, table, where=None, start=None, stop=None): self.stop is not None and (where >= self.stop).any() ): raise ValueError( - "where must have index locations >= start and " "< stop" + "where must have index locations >= start and < stop" ) self.coordinates = where diff --git a/pandas/io/sas/sas_xport.py b/pandas/io/sas/sas_xport.py index 34b93d72d0e29..ea26a9b8efdbf 100644 --- a/pandas/io/sas/sas_xport.py +++ b/pandas/io/sas/sas_xport.py @@ -26,7 +26,7 @@ "000000000000000000000000000000 " ) _correct_header1 = ( - "HEADER RECORD*******MEMBER HEADER RECORD!!!!!!!" "000000000000000001600000000" + "HEADER RECORD*******MEMBER HEADER RECORD!!!!!!!000000000000000001600000000" ) _correct_header2 = ( "HEADER RECORD*******DSCRPTR HEADER RECORD!!!!!!!" diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 6fe34e4e9705a..f1f52a9198d29 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -233,7 +233,7 @@ def read_sql_table( con = _engine_builder(con) if not _is_sqlalchemy_connectable(con): raise NotImplementedError( - "read_sql_table only supported for " "SQLAlchemy connectable." + "read_sql_table only supported for SQLAlchemy connectable." ) import sqlalchemy from sqlalchemy.schema import MetaData @@ -503,7 +503,7 @@ def to_sql( frame = frame.to_frame() elif not isinstance(frame, DataFrame): raise NotImplementedError( - "'frame' argument should be either a " "Series or a DataFrame" + "'frame' argument should be either a Series or a DataFrame" ) pandas_sql.to_sql( @@ -1756,7 +1756,7 @@ def has_table(self, name, schema=None): wld = "?" query = ( - "SELECT name FROM sqlite_master " "WHERE type='table' AND name={wld};" + "SELECT name FROM sqlite_master WHERE type='table' AND name={wld};" ).format(wld=wld) return len(self.execute(query, [name]).fetchall()) > 0 diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 32122a9daa1db..69bafc7749258 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -367,7 +367,7 @@ def convert_delta_safe(base, deltas, unit): conv_dates = convert_delta_safe(base, ms, "ms") elif fmt.startswith(("%tC", "tC")): - warnings.warn("Encountered %tC format. Leaving in Stata " "Internal Format.") + warnings.warn("Encountered %tC format. Leaving in Stata Internal Format.") conv_dates = Series(dates, dtype=np.object) if has_bad_values: conv_dates[bad_locs] = NaT @@ -856,7 +856,7 @@ def __init__(self, value): string = property( lambda self: self._str, - doc="The Stata representation of the missing value: " "'.', '.a'..'.z'", + doc="The Stata representation of the missing value: '.', '.a'..'.z'", ) value = property( lambda self: self._value, doc="The binary representation of the missing value." @@ -1959,7 +1959,7 @@ def _maybe_convert_to_int_keys(convert_dates, varlist): new_dict.update({varlist.index(key): convert_dates[key]}) else: if not isinstance(key, int): - raise ValueError("convert_dates key must be a " "column or an integer") + raise ValueError("convert_dates key must be a column or an integer") new_dict.update({key: convert_dates[key]}) return new_dict @@ -2533,9 +2533,7 @@ def _write_variable_labels(self): if col in self._variable_labels: label = self._variable_labels[col] if len(label) > 80: - raise ValueError( - "Variable labels must be 80 characters " "or fewer" - ) + raise ValueError("Variable labels must be 80 characters or fewer") is_latin1 = all(ord(c) < 256 for c in label) if not is_latin1: raise ValueError( @@ -3093,9 +3091,7 @@ def _write_variable_labels(self): if col in self._variable_labels: label = self._variable_labels[col] if len(label) > 80: - raise ValueError( - "Variable labels must be 80 characters " "or fewer" - ) + raise ValueError("Variable labels must be 80 characters or fewer") is_latin1 = all(ord(c) < 256 for c in label) if not is_latin1: raise ValueError(
Also some post-black cleanups in pandas.io (I think we're almost done with these) Removing "pragma: no cover" in a couple places because I'm working in those areas and it would be easier if we caught more specific things so I want to see if they are ever reached.
https://api.github.com/repos/pandas-dev/pandas/pulls/27685
2019-08-01T03:00:28Z
2019-08-01T12:15:17Z
2019-08-01T12:15:17Z
2019-08-01T14:09:08Z
CLN: remove _try_coerce_result altogether
diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 1484feeeada64..b066629676e5d 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -25,6 +25,7 @@ is_categorical_dtype, is_complex_dtype, is_datetime64_any_dtype, + is_datetime64tz_dtype, is_integer_dtype, is_numeric_dtype, is_sparse, @@ -451,6 +452,7 @@ def wrapper(*args, **kwargs): def _cython_operation(self, kind, values, how, axis, min_count=-1, **kwargs): assert kind in ["transform", "aggregate"] + orig_values = values # can we do this operation with our cython functions # if not raise NotImplementedError @@ -475,23 +477,11 @@ def _cython_operation(self, kind, values, how, axis, min_count=-1, **kwargs): "timedelta64 type does not support {} operations".format(how) ) - arity = self._cython_arity.get(how, 1) - - vdim = values.ndim - swapped = False - if vdim == 1: - values = values[:, None] - out_shape = (self.ngroups, arity) - else: - if axis > 0: - swapped = True - assert axis == 1, axis - values = values.T - if arity > 1: - raise NotImplementedError( - "arity of more than 1 is not supported for the 'how' argument" - ) - out_shape = (self.ngroups,) + values.shape[1:] + if is_datetime64tz_dtype(values.dtype): + # Cast to naive; we'll cast back at the end of the function + # TODO: possible need to reshape? kludge can be avoided when + # 2D EA is allowed. + values = values.view("M8[ns]") is_datetimelike = needs_i8_conversion(values.dtype) is_numeric = is_numeric_dtype(values.dtype) @@ -513,6 +503,24 @@ def _cython_operation(self, kind, values, how, axis, min_count=-1, **kwargs): else: values = values.astype(object) + arity = self._cython_arity.get(how, 1) + + vdim = values.ndim + swapped = False + if vdim == 1: + values = values[:, None] + out_shape = (self.ngroups, arity) + else: + if axis > 0: + swapped = True + assert axis == 1, axis + values = values.T + if arity > 1: + raise NotImplementedError( + "arity of more than 1 is not supported for the 'how' argument" + ) + out_shape = (self.ngroups,) + values.shape[1:] + try: func = self._get_cython_function(kind, how, values, is_numeric) except NotImplementedError: @@ -581,6 +589,9 @@ def _cython_operation(self, kind, values, how, axis, min_count=-1, **kwargs): if swapped: result = result.swapaxes(0, axis) + if is_datetime64tz_dtype(orig_values.dtype): + result = type(orig_values)(result.astype(np.int64), dtype=orig_values.dtype) + return result, names def aggregate(self, values, how, axis=0, min_count=-1): diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 8ade489e71587..6a2aebe5db246 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -417,9 +417,6 @@ def fillna(self, value, limit=None, inplace=False, downcast=None): if self._can_hold_element(value): # equivalent: self._try_coerce_args(value) would not raise blocks = self.putmask(mask, value, inplace=inplace) - blocks = [ - b.make_block(values=self._try_coerce_result(b.values)) for b in blocks - ] return self._maybe_downcast(blocks, downcast) # we can't process the value, but nothing to do @@ -734,12 +731,7 @@ def _try_coerce_args(self, other): return other - def _try_coerce_result(self, result): - """ reverse of try_coerce_args """ - return result - def _try_coerce_and_cast_result(self, result, dtype=None): - result = self._try_coerce_result(result) result = self._try_cast_result(result, dtype=dtype) return result @@ -1406,7 +1398,7 @@ def func(cond, values, other): try: fastres = expressions.where(cond, values, other) - return self._try_coerce_result(fastres) + return fastres except Exception as detail: if errors == "raise": raise TypeError( @@ -1692,7 +1684,6 @@ def putmask(self, mask, new, align=True, inplace=False, axis=0, transpose=False) mask = _safe_reshape(mask, new_values.shape) new_values[mask] = new - new_values = self._try_coerce_result(new_values) return [self.make_block(values=new_values)] def _try_cast_result(self, result, dtype=None): @@ -1870,20 +1861,6 @@ def _slice(self, slicer): return self.values[slicer] - def _try_cast_result(self, result, dtype=None): - """ - if we have an operation that operates on for example floats - we want to try to cast back to our EA here if possible - - result could be a 2-D numpy array, e.g. the result of - a numeric operation; but it must be shape (1, X) because - we by-definition operate on the ExtensionBlocks one-by-one - - result could also be an EA Array itself, in which case it - is already a 1-D array - """ - return result - def formatting_values(self): # Deprecating the ability to override _formatting_values. # Do the warning here, it's only user in pandas, since we @@ -2443,20 +2420,6 @@ def _try_coerce_args(self, other): return other - def _try_coerce_result(self, result): - """ reverse of try_coerce_args """ - if isinstance(result, np.ndarray): - if result.ndim == 2: - # kludge for 2D blocks with 1D EAs - result = result[0, :] - if result.dtype == np.float64: - # needed for post-groupby.median - result = self._holder._from_sequence( - result.astype(np.int64), freq=None, dtype=self.values.dtype - ) - - return result - def diff(self, n, axis=0): """1st discrete difference @@ -2619,10 +2582,6 @@ def _try_coerce_args(self, other): return other - def _try_coerce_result(self, result): - """ reverse of try_coerce_args / try_operate """ - return result - def should_store(self, value): return issubclass( value.dtype.type, np.timedelta64 @@ -3031,16 +2990,6 @@ def array_dtype(self): """ return np.object_ - def _try_coerce_result(self, result): - """ reverse of try_coerce_args """ - - # GH12564: CategoricalBlock is 1-dim only - # while returned results could be any dim - if (not is_categorical_dtype(result)) and isinstance(result, np.ndarray): - result = _block_shape(result, ndim=self.ndim) - - return result - def to_dense(self): # Categorical.get_values returns a DatetimeIndex for datetime # categories, so we can't simply use `np.asarray(self.values)` like diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 8956821740bf3..c7318314b8af9 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -908,7 +908,7 @@ def fast_xs(self, loc): # Such assignment may incorrectly coerce NaT to None # result[blk.mgr_locs] = blk._slice((slice(None), loc)) for i, rl in enumerate(blk.mgr_locs): - result[rl] = blk._try_coerce_result(blk.iget((i, loc))) + result[rl] = blk.iget((i, loc)) if is_extension_array_dtype(dtype): result = dtype.construct_array_type()._from_sequence(result, dtype=dtype)
Following #27628, we can now remove _try_coerce_result altogether. The step after this removes _try_cast_result.
https://api.github.com/repos/pandas-dev/pandas/pulls/27683
2019-07-31T20:44:49Z
2019-08-05T11:57:08Z
2019-08-05T11:57:08Z
2019-08-05T14:33:16Z
ENH: Implement weighted rolling var and std
diff --git a/doc/source/reference/window.rst b/doc/source/reference/window.rst index 2f6addf607877..d09ac0d1fa7f7 100644 --- a/doc/source/reference/window.rst +++ b/doc/source/reference/window.rst @@ -34,6 +34,8 @@ Standard moving window functions Rolling.quantile Window.mean Window.sum + Window.var + Window.std .. _api.functions_expanding: diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index cb1d80a34514c..36c1889e7df06 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -110,6 +110,7 @@ Other enhancements (depending on the presence of missing data) or object dtype column. (:issue:`28368`) - :meth:`DataFrame.to_json` now accepts an ``indent`` integer argument to enable pretty printing of JSON output (:issue:`12004`) - :meth:`read_stata` can read Stata 119 dta files. (:issue:`28250`) +- Implemented :meth:`pandas.core.window.Window.var` and :meth:`pandas.core.window.Window.std` functions (:issue:`26597`) - Added ``encoding`` argument to :meth:`DataFrame.to_string` for non-ascii text (:issue:`28766`) - Added ``encoding`` argument to :func:`DataFrame.to_html` for non-ascii text (:issue:`28663`) - :meth:`Styler.background_gradient` now accepts ``vmin`` and ``vmax`` arguments (:issue:`12145`) diff --git a/pandas/_libs/window.pyx b/pandas/_libs/window.pyx index b51d61d05ce98..62066c5f66ea3 100644 --- a/pandas/_libs/window.pyx +++ b/pandas/_libs/window.pyx @@ -1752,6 +1752,226 @@ cdef ndarray[float64_t] _roll_weighted_sum_mean(float64_t[:] values, return np.asarray(output) +# ---------------------------------------------------------------------- +# Rolling var for weighted window + + +cdef inline float64_t calc_weighted_var(float64_t t, + float64_t sum_w, + Py_ssize_t win_n, + unsigned int ddof, + float64_t nobs, + int64_t minp) nogil: + """ + Calculate weighted variance for a window using West's method. + + Paper: https://dl.acm.org/citation.cfm?id=359153 + + Parameters + ---------- + t: float64_t + sum of weighted squared differences + sum_w: float64_t + sum of weights + win_n: Py_ssize_t + window size + ddof: unsigned int + delta degrees of freedom + nobs: float64_t + number of observations + minp: int64_t + minimum number of observations + + Returns + ------- + result : float64_t + weighted variance of the window + """ + + cdef: + float64_t result + + # Variance is unchanged if no observation is added or removed + if (nobs >= minp) and (nobs > ddof): + + # pathological case + if nobs == 1: + result = 0 + else: + result = t * win_n / ((win_n - ddof) * sum_w) + if result < 0: + result = 0 + else: + result = NaN + + return result + + +cdef inline void add_weighted_var(float64_t val, + float64_t w, + float64_t *t, + float64_t *sum_w, + float64_t *mean, + float64_t *nobs) nogil: + """ + Update weighted mean, sum of weights and sum of weighted squared + differences to include value and weight pair in weighted variance + calculation using West's method. + + Paper: https://dl.acm.org/citation.cfm?id=359153 + + Parameters + ---------- + val: float64_t + window values + w: float64_t + window weights + t: float64_t + sum of weighted squared differences + sum_w: float64_t + sum of weights + mean: float64_t + weighted mean + nobs: float64_t + number of observations + """ + + cdef: + float64_t temp, q, r + + if isnan(val): + return + + nobs[0] = nobs[0] + 1 + + q = val - mean[0] + temp = sum_w[0] + w + r = q * w / temp + + mean[0] = mean[0] + r + t[0] = t[0] + r * sum_w[0] * q + sum_w[0] = temp + + +cdef inline void remove_weighted_var(float64_t val, + float64_t w, + float64_t *t, + float64_t *sum_w, + float64_t *mean, + float64_t *nobs) nogil: + """ + Update weighted mean, sum of weights and sum of weighted squared + differences to remove value and weight pair from weighted variance + calculation using West's method. + + Paper: https://dl.acm.org/citation.cfm?id=359153 + + Parameters + ---------- + val: float64_t + window values + w: float64_t + window weights + t: float64_t + sum of weighted squared differences + sum_w: float64_t + sum of weights + mean: float64_t + weighted mean + nobs: float64_t + number of observations + """ + + cdef: + float64_t temp, q, r + + if notnan(val): + nobs[0] = nobs[0] - 1 + + if nobs[0]: + q = val - mean[0] + temp = sum_w[0] - w + r = q * w / temp + + mean[0] = mean[0] - r + t[0] = t[0] - r * sum_w[0] * q + sum_w[0] = temp + + else: + t[0] = 0 + sum_w[0] = 0 + mean[0] = 0 + + +def roll_weighted_var(float64_t[:] values, float64_t[:] weights, + int64_t minp, unsigned int ddof): + """ + Calculates weighted rolling variance using West's online algorithm. + + Paper: https://dl.acm.org/citation.cfm?id=359153 + + Parameters + ---------- + values: float64_t[:] + values to roll window over + weights: float64_t[:] + array of weights whose lenght is window size + minp: int64_t + minimum number of observations to calculate + variance of a window + ddof: unsigned int + the divisor used in variance calculations + is the window size - ddof + + Returns + ------- + output: float64_t[:] + weighted variances of windows + """ + + cdef: + float64_t t = 0, sum_w = 0, mean = 0, nobs = 0 + float64_t val, pre_val, w, pre_w + Py_ssize_t i, n, win_n + float64_t[:] output + + n = len(values) + win_n = len(weights) + output = np.empty(n, dtype=float) + + with nogil: + + for i in range(win_n): + add_weighted_var(values[i], weights[i], &t, + &sum_w, &mean, &nobs) + + output[i] = calc_weighted_var(t, sum_w, win_n, + ddof, nobs, minp) + + for i in range(win_n, n): + val = values[i] + pre_val = values[i - win_n] + + w = weights[i % win_n] + pre_w = weights[(i - win_n) % win_n] + + if notnan(val): + if pre_val == pre_val: + remove_weighted_var(pre_val, pre_w, &t, + &sum_w, &mean, &nobs) + + add_weighted_var(val, w, &t, &sum_w, &mean, &nobs) + + elif pre_val == pre_val: + remove_weighted_var(pre_val, pre_w, &t, + &sum_w, &mean, &nobs) + + output[i] = calc_weighted_var(t, sum_w, win_n, + ddof, nobs, minp) + + return output + + # ---------------------------------------------------------------------- # Exponentially weighted moving average diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py index 47bd8f2ec593b..c3b7531ce5904 100644 --- a/pandas/core/window/expanding.py +++ b/pandas/core/window/expanding.py @@ -181,13 +181,13 @@ def mean(self, *args, **kwargs): def median(self, **kwargs): return super().median(**kwargs) - @Substitution(name="expanding") + @Substitution(name="expanding", versionadded="") @Appender(_shared_docs["std"]) def std(self, ddof=1, *args, **kwargs): nv.validate_expanding_func("std", args, kwargs) return super().std(ddof=ddof, **kwargs) - @Substitution(name="expanding") + @Substitution(name="expanding", versionadded="") @Appender(_shared_docs["var"]) def var(self, ddof=1, *args, **kwargs): nv.validate_expanding_func("var", args, kwargs) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index bf5ea9c457e8a..ab59cb1170b75 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -4,7 +4,7 @@ """ from datetime import timedelta from textwrap import dedent -from typing import Callable, List, Optional, Set, Union +from typing import Callable, Dict, List, Optional, Set, Tuple, Union import warnings import numpy as np @@ -169,13 +169,30 @@ def __getattr__(self, attr): def _dir_additions(self): return self.obj._dir_additions() - def _get_window(self, other=None, **kwargs) -> int: + def _get_win_type(self, kwargs: Dict): """ - Returns window length + Exists for compatibility, overriden by subclass Window. Parameters ---------- - other: + kwargs : dict + ignored, exists for compatibility + + Returns + ------- + None + """ + return None + + def _get_window(self, other=None, win_type: Optional[str] = None) -> int: + """ + Return window length. + + Parameters + ---------- + other : + ignored, exists for compatibility + win_type : ignored, exists for compatibility Returns @@ -405,6 +422,7 @@ def _apply( ------- y : type of input """ + if center is None: center = self.center @@ -412,7 +430,8 @@ def _apply( check_minp = _use_window if window is None: - window = self._get_window(**kwargs) + win_type = self._get_win_type(kwargs) + window = self._get_window(win_type=win_type) blocks, obj = self._create_blocks() block_list = list(blocks) @@ -612,6 +631,126 @@ def aggregate(self, func, *args, **kwargs): """ ) + _shared_docs["var"] = dedent( + """ + Calculate unbiased %(name)s variance. + %(versionadded)s + Normalized by N-1 by default. This can be changed using the `ddof` + argument. + + Parameters + ---------- + ddof : int, default 1 + Delta Degrees of Freedom. The divisor used in calculations + is ``N - ddof``, where ``N`` represents the number of elements. + *args, **kwargs + For NumPy compatibility. No additional arguments are used. + + Returns + ------- + Series or DataFrame + Returns the same object type as the caller of the %(name)s calculation. + + See Also + -------- + Series.%(name)s : Calling object with Series data. + DataFrame.%(name)s : Calling object with DataFrames. + Series.var : Equivalent method for Series. + DataFrame.var : Equivalent method for DataFrame. + numpy.var : Equivalent method for Numpy array. + + Notes + ----- + The default `ddof` of 1 used in :meth:`Series.var` is different than the + default `ddof` of 0 in :func:`numpy.var`. + + A minimum of 1 period is required for the rolling calculation. + + Examples + -------- + >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5]) + >>> s.rolling(3).var() + 0 NaN + 1 NaN + 2 0.333333 + 3 1.000000 + 4 1.000000 + 5 1.333333 + 6 0.000000 + dtype: float64 + + >>> s.expanding(3).var() + 0 NaN + 1 NaN + 2 0.333333 + 3 0.916667 + 4 0.800000 + 5 0.700000 + 6 0.619048 + dtype: float64 + """ + ) + + _shared_docs["std"] = dedent( + """ + Calculate %(name)s standard deviation. + %(versionadded)s + Normalized by N-1 by default. This can be changed using the `ddof` + argument. + + Parameters + ---------- + ddof : int, default 1 + Delta Degrees of Freedom. The divisor used in calculations + is ``N - ddof``, where ``N`` represents the number of elements. + *args, **kwargs + For NumPy compatibility. No additional arguments are used. + + Returns + ------- + Series or DataFrame + Returns the same object type as the caller of the %(name)s calculation. + + See Also + -------- + Series.%(name)s : Calling object with Series data. + DataFrame.%(name)s : Calling object with DataFrames. + Series.std : Equivalent method for Series. + DataFrame.std : Equivalent method for DataFrame. + numpy.std : Equivalent method for Numpy array. + + Notes + ----- + The default `ddof` of 1 used in Series.std is different than the default + `ddof` of 0 in numpy.std. + + A minimum of one period is required for the rolling calculation. + + Examples + -------- + >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5]) + >>> s.rolling(3).std() + 0 NaN + 1 NaN + 2 0.577350 + 3 1.000000 + 4 1.000000 + 5 1.154701 + 6 0.000000 + dtype: float64 + + >>> s.expanding(3).std() + 0 NaN + 1 NaN + 2 0.577350 + 3 0.957427 + 4 0.894427 + 5 0.836660 + 6 0.786796 + dtype: float64 + """ + ) + class Window(_Window): """ @@ -783,15 +922,63 @@ def validate(self): else: raise ValueError("Invalid window {0}".format(window)) - def _get_window(self, other=None, **kwargs) -> np.ndarray: + def _get_win_type(self, kwargs: Dict) -> Union[str, Tuple]: """ - Provide validation for the window type, return the window - which has already been validated. + Extract arguments for the window type, provide validation for it + and return the validated window type. Parameters ---------- - other: + kwargs : dict + + Returns + ------- + win_type : str, or tuple + """ + # the below may pop from kwargs + def _validate_win_type(win_type, kwargs): + arg_map = { + "kaiser": ["beta"], + "gaussian": ["std"], + "general_gaussian": ["power", "width"], + "slepian": ["width"], + "exponential": ["tau"], + } + + if win_type in arg_map: + win_args = _pop_args(win_type, arg_map[win_type], kwargs) + if win_type == "exponential": + # exponential window requires the first arg (center) + # to be set to None (necessary for symmetric window) + win_args.insert(0, None) + + return tuple([win_type] + win_args) + + return win_type + + def _pop_args(win_type, arg_names, kwargs): + msg = "%s window requires %%s" % win_type + all_args = [] + for n in arg_names: + if n not in kwargs: + raise ValueError(msg % n) + all_args.append(kwargs.pop(n)) + return all_args + + return _validate_win_type(self.win_type, kwargs) + + def _get_window( + self, other=None, win_type: Optional[Union[str, Tuple]] = None + ) -> np.ndarray: + """ + Get the window, weights. + + Parameters + ---------- + other : ignored, exists for compatibility + win_type : str, or tuple + type of window to create Returns ------- @@ -805,37 +992,6 @@ def _get_window(self, other=None, **kwargs) -> np.ndarray: elif is_integer(window): import scipy.signal as sig - # the below may pop from kwargs - def _validate_win_type(win_type, kwargs): - arg_map = { - "kaiser": ["beta"], - "gaussian": ["std"], - "general_gaussian": ["power", "width"], - "slepian": ["width"], - "exponential": ["tau"], - } - - if win_type in arg_map: - win_args = _pop_args(win_type, arg_map[win_type], kwargs) - if win_type == "exponential": - # exponential window requires the first arg (center) - # to be set to None (necessary for symmetric window) - win_args.insert(0, None) - - return tuple([win_type] + win_args) - - return win_type - - def _pop_args(win_type, arg_names, kwargs): - msg = "%s window requires %%s" % win_type - all_args = [] - for n in arg_names: - if n not in kwargs: - raise ValueError(msg % n) - all_args.append(kwargs.pop(n)) - return all_args - - win_type = _validate_win_type(self.win_type, kwargs) # GH #15662. `False` makes symmetric window, rather than periodic. return sig.get_window(win_type, window, False).astype(float) @@ -844,7 +1000,7 @@ def _get_roll_func( ) -> Callable: def func(arg, window, min_periods=None, closed=None): minp = check_minp(min_periods, len(window)) - return cfunc(arg, window, minp) + return cfunc(arg, window, minp, **kwargs) return func @@ -922,6 +1078,18 @@ def mean(self, *args, **kwargs): nv.validate_window_func("mean", args, kwargs) return self._apply("roll_weighted_mean", **kwargs) + @Substitution(name="window", versionadded="\n.. versionadded:: 1.0.0\n") + @Appender(_shared_docs["var"]) + def var(self, ddof=1, *args, **kwargs): + nv.validate_window_func("var", args, kwargs) + return self._apply("roll_weighted_var", ddof=ddof, **kwargs) + + @Substitution(name="window", versionadded="\n.. versionadded:: 1.0.0\n") + @Appender(_shared_docs["std"]) + def std(self, ddof=1, *args, **kwargs): + nv.validate_window_func("std", args, kwargs) + return _zsqrt(self.var(ddof=ddof, **kwargs)) + class _Rolling(_Window): @property @@ -1176,66 +1344,6 @@ def mean(self, *args, **kwargs): def median(self, **kwargs): return self._apply("roll_median_c", "median", **kwargs) - _shared_docs["std"] = dedent( - """ - Calculate %(name)s standard deviation. - - Normalized by N-1 by default. This can be changed using the `ddof` - argument. - - Parameters - ---------- - ddof : int, default 1 - Delta Degrees of Freedom. The divisor used in calculations - is ``N - ddof``, where ``N`` represents the number of elements. - *args, **kwargs - For NumPy compatibility. No additional arguments are used. - - Returns - ------- - Series or DataFrame - Returns the same object type as the caller of the %(name)s calculation. - - See Also - -------- - Series.%(name)s : Calling object with Series data. - DataFrame.%(name)s : Calling object with DataFrames. - Series.std : Equivalent method for Series. - DataFrame.std : Equivalent method for DataFrame. - numpy.std : Equivalent method for Numpy array. - - Notes - ----- - The default `ddof` of 1 used in Series.std is different than the default - `ddof` of 0 in numpy.std. - - A minimum of one period is required for the rolling calculation. - - Examples - -------- - >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5]) - >>> s.rolling(3).std() - 0 NaN - 1 NaN - 2 0.577350 - 3 1.000000 - 4 1.000000 - 5 1.154701 - 6 0.000000 - dtype: float64 - - >>> s.expanding(3).std() - 0 NaN - 1 NaN - 2 0.577350 - 3 0.957427 - 4 0.894427 - 5 0.836660 - 6 0.786796 - dtype: float64 - """ - ) - def std(self, ddof=1, *args, **kwargs): nv.validate_window_func("std", args, kwargs) window = self._get_window() @@ -1251,66 +1359,6 @@ def f(arg, *args, **kwargs): f, "std", check_minp=_require_min_periods(1), ddof=ddof, **kwargs ) - _shared_docs["var"] = dedent( - """ - Calculate unbiased %(name)s variance. - - Normalized by N-1 by default. This can be changed using the `ddof` - argument. - - Parameters - ---------- - ddof : int, default 1 - Delta Degrees of Freedom. The divisor used in calculations - is ``N - ddof``, where ``N`` represents the number of elements. - *args, **kwargs - For NumPy compatibility. No additional arguments are used. - - Returns - ------- - Series or DataFrame - Returns the same object type as the caller of the %(name)s calculation. - - See Also - -------- - Series.%(name)s : Calling object with Series data. - DataFrame.%(name)s : Calling object with DataFrames. - Series.var : Equivalent method for Series. - DataFrame.var : Equivalent method for DataFrame. - numpy.var : Equivalent method for Numpy array. - - Notes - ----- - The default `ddof` of 1 used in :meth:`Series.var` is different than the - default `ddof` of 0 in :func:`numpy.var`. - - A minimum of 1 period is required for the rolling calculation. - - Examples - -------- - >>> s = pd.Series([5, 5, 6, 7, 5, 5, 5]) - >>> s.rolling(3).var() - 0 NaN - 1 NaN - 2 0.333333 - 3 1.000000 - 4 1.000000 - 5 1.333333 - 6 0.000000 - dtype: float64 - - >>> s.expanding(3).var() - 0 NaN - 1 NaN - 2 0.333333 - 3 0.916667 - 4 0.800000 - 5 0.700000 - 6 0.619048 - dtype: float64 - """ - ) - def var(self, ddof=1, *args, **kwargs): nv.validate_window_func("var", args, kwargs) return self._apply( @@ -1845,13 +1893,13 @@ def mean(self, *args, **kwargs): def median(self, **kwargs): return super().median(**kwargs) - @Substitution(name="rolling") + @Substitution(name="rolling", versionadded="") @Appender(_shared_docs["std"]) def std(self, ddof=1, *args, **kwargs): nv.validate_rolling_func("std", args, kwargs) return super().std(ddof=ddof, **kwargs) - @Substitution(name="rolling") + @Substitution(name="rolling", versionadded="") @Appender(_shared_docs["var"]) def var(self, ddof=1, *args, **kwargs): nv.validate_rolling_func("var", args, kwargs) diff --git a/pandas/tests/window/test_moments.py b/pandas/tests/window/test_moments.py index 3d6cd7d10bd10..36a0ddb3e02d7 100644 --- a/pandas/tests/window/test_moments.py +++ b/pandas/tests/window/test_moments.py @@ -119,64 +119,95 @@ def test_cmov_window_corner(self): assert len(result) == 5 @td.skip_if_no_scipy - def test_cmov_window_frame(self): + @pytest.mark.parametrize( + "f,xp", + [ + ( + "mean", + [ + [np.nan, np.nan], + [np.nan, np.nan], + [9.252, 9.392], + [8.644, 9.906], + [8.87, 10.208], + [6.81, 8.588], + [7.792, 8.644], + [9.05, 7.824], + [np.nan, np.nan], + [np.nan, np.nan], + ], + ), + ( + "std", + [ + [np.nan, np.nan], + [np.nan, np.nan], + [3.789706, 4.068313], + [3.429232, 3.237411], + [3.589269, 3.220810], + [3.405195, 2.380655], + [3.281839, 2.369869], + [3.676846, 1.801799], + [np.nan, np.nan], + [np.nan, np.nan], + ], + ), + ( + "var", + [ + [np.nan, np.nan], + [np.nan, np.nan], + [14.36187, 16.55117], + [11.75963, 10.48083], + [12.88285, 10.37362], + [11.59535, 5.66752], + [10.77047, 5.61628], + [13.51920, 3.24648], + [np.nan, np.nan], + [np.nan, np.nan], + ], + ), + ( + "sum", + [ + [np.nan, np.nan], + [np.nan, np.nan], + [46.26, 46.96], + [43.22, 49.53], + [44.35, 51.04], + [34.05, 42.94], + [38.96, 43.22], + [45.25, 39.12], + [np.nan, np.nan], + [np.nan, np.nan], + ], + ), + ], + ) + def test_cmov_window_frame(self, f, xp): # Gh 8238 - vals = np.array( - [ - [12.18, 3.64], - [10.18, 9.16], - [13.24, 14.61], - [4.51, 8.11], - [6.15, 11.44], - [9.14, 6.21], - [11.31, 10.67], - [2.94, 6.51], - [9.42, 8.39], - [12.44, 7.34], - ] - ) - - xp = np.array( - [ - [np.nan, np.nan], - [np.nan, np.nan], - [9.252, 9.392], - [8.644, 9.906], - [8.87, 10.208], - [6.81, 8.588], - [7.792, 8.644], - [9.05, 7.824], - [np.nan, np.nan], - [np.nan, np.nan], - ] + df = DataFrame( + np.array( + [ + [12.18, 3.64], + [10.18, 9.16], + [13.24, 14.61], + [4.51, 8.11], + [6.15, 11.44], + [9.14, 6.21], + [11.31, 10.67], + [2.94, 6.51], + [9.42, 8.39], + [12.44, 7.34], + ] + ) ) + xp = DataFrame(np.array(xp)) - # DataFrame - rs = DataFrame(vals).rolling(5, win_type="boxcar", center=True).mean() - tm.assert_frame_equal(DataFrame(xp), rs) - - # invalid method - with pytest.raises(AttributeError): - (DataFrame(vals).rolling(5, win_type="boxcar", center=True).std()) - - # sum - xp = np.array( - [ - [np.nan, np.nan], - [np.nan, np.nan], - [46.26, 46.96], - [43.22, 49.53], - [44.35, 51.04], - [34.05, 42.94], - [38.96, 43.22], - [45.25, 39.12], - [np.nan, np.nan], - [np.nan, np.nan], - ] - ) + roll = df.rolling(5, win_type="boxcar", center=True) + rs = getattr(roll, f)() - rs = DataFrame(vals).rolling(5, win_type="boxcar", center=True).sum() - tm.assert_frame_equal(DataFrame(xp), rs) + tm.assert_frame_equal(xp, rs) @td.skip_if_no_scipy def test_cmov_window_na_min_periods(self): diff --git a/pandas/tests/window/test_window.py b/pandas/tests/window/test_window.py index f42c507e51511..39ab3ffd9319e 100644 --- a/pandas/tests/window/test_window.py +++ b/pandas/tests/window/test_window.py @@ -60,7 +60,7 @@ def test_numpy_compat(self, method): getattr(w, method)(dtype=np.float64) @td.skip_if_no_scipy - @pytest.mark.parametrize("arg", ["median", "var", "std", "kurt", "skew"]) + @pytest.mark.parametrize("arg", ["median", "kurt", "skew"]) def test_agg_function_support(self, arg): df = pd.DataFrame({"A": np.arange(5)}) roll = df.rolling(2, win_type="triang")
- [x] closes #26597 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Used West's online [algorithm](https://dl.acm.org/citation.cfm?id=359153). [Here](http://www.nowozin.net/sebastian/blog/streaming-mean-and-variance-computation.html) is an explanation of the algorithm and link to pdf of the paper. Tested implementation with `win_type="boxcar"` comparing it with the result of `Rolling.std`. Additionaly, `_get_window` function is split into two. `_get_kwargs` function is used to split kwargs for window function and rolling function (since std and var takes an additional `ddof` argument). Shared docs for `std` and `var` are moved to be used with `Window` functions
https://api.github.com/repos/pandas-dev/pandas/pulls/27682
2019-07-31T20:14:26Z
2019-11-08T14:45:02Z
2019-11-08T14:45:01Z
2019-11-09T17:15:26Z
BUG: fixes formatted value error for missing sheet (#27676)
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 8c1ce1195369d..2b4dea2e91f7d 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -356,6 +356,7 @@ I/O - Bug in :func:`read_hdf` closing stores that it didn't open when Exceptions are raised (:issue:`28699`) - Bug in :meth:`DataFrame.read_json` where using ``orient="index"`` would not maintain the order (:issue:`28557`) - Bug in :meth:`DataFrame.to_html` where the length of the ``formatters`` argument was not verified (:issue:`28469`) +- Bug in :meth:`DataFrame.read_excel` with ``engine='ods'`` when ``sheet_name`` argument references a non-existent sheet (:issue:`27676`) - Bug in :meth:`pandas.io.formats.style.Styler` formatting for floating values not displaying decimals correctly (:issue:`13257`) Plotting diff --git a/pandas/io/excel/_odfreader.py b/pandas/io/excel/_odfreader.py index 3be36663bac79..dc1d1e71ad686 100644 --- a/pandas/io/excel/_odfreader.py +++ b/pandas/io/excel/_odfreader.py @@ -60,7 +60,7 @@ def get_sheet_by_name(self, name: str): if table.getAttribute("name") == name: return table - raise ValueError("sheet {name} not found".format(name)) + raise ValueError("sheet {} not found".format(name)) def get_sheet_data(self, sheet, convert_float: bool) -> List[List[Scalar]]: """Parse an ODF Table into a list of lists diff --git a/pandas/tests/io/excel/test_odf.py b/pandas/tests/io/excel/test_odf.py index 76871eddf1cee..47e610562a388 100644 --- a/pandas/tests/io/excel/test_odf.py +++ b/pandas/tests/io/excel/test_odf.py @@ -36,3 +36,11 @@ def test_read_writer_table(): result = pd.read_excel("writertable.odt", "Table1", index_col=0) tm.assert_frame_equal(result, expected) + + +def test_nonexistent_sheetname_raises(read_ext): + # GH-27676 + # Specifying a non-existent sheet_name parameter should throw an error + # with the sheet name. + with pytest.raises(ValueError, match="sheet xyz not found"): + pd.read_excel("blank.ods", sheet_name="xyz")
Fixes a formatted message at [io.excel._odfreader line 62](https://github.com/pandas-dev/pandas/blob/master/pandas/io/excel/_odfreader.py#L63) - [x] closes #27676 - [x] tests added / passed - [x] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27677
2019-07-31T15:19:32Z
2019-10-25T17:01:30Z
2019-10-25T17:01:30Z
2019-10-28T13:56:51Z
DOC: Fix length typo
diff --git a/pandas/core/window.py b/pandas/core/window.py index 2199daa743655..4b6a1cf2e9a04 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -175,7 +175,7 @@ def _dir_additions(self): def _get_window(self, other=None, **kwargs) -> int: """ - Returns window lenght + Returns window length Parameters ---------- @@ -395,7 +395,7 @@ def _apply( name : str, optional name of this function window : int/str, default to _get_window() - window lenght or offset + window length or offset center : bool, default to self.center check_minp : function, default to _use_window **kwargs
https://api.github.com/repos/pandas-dev/pandas/pulls/27675
2019-07-31T14:09:27Z
2019-07-31T15:40:49Z
2019-07-31T15:40:49Z
2019-07-31T15:40:50Z
Handle construction of string ExtensionArray from lists
diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 9528723a6dc0f..0c25cdf121cbb 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -468,30 +468,27 @@ def sanitize_array(data, index, dtype=None, copy=False, raise_cast_failure=False else: subarr = com.asarray_tuplesafe(data, dtype=dtype) - # This is to prevent mixed-type Series getting all casted to - # NumPy string type, e.g. NaN --> '-1#IND'. - if issubclass(subarr.dtype.type, str): - # GH#16605 - # If not empty convert the data to dtype - # GH#19853: If data is a scalar, subarr has already the result - if not lib.is_scalar(data): - if not np.all(isna(data)): - data = np.array(data, dtype=dtype, copy=False) - subarr = np.array(data, dtype=object, copy=copy) - - if ( - not (is_extension_array_dtype(subarr.dtype) or is_extension_array_dtype(dtype)) - and is_object_dtype(subarr.dtype) - and not is_object_dtype(dtype) - ): - inferred = lib.infer_dtype(subarr, skipna=False) - if inferred == "period": - from pandas.core.arrays import period_array + if not (is_extension_array_dtype(subarr.dtype) or is_extension_array_dtype(dtype)): + # This is to prevent mixed-type Series getting all casted to + # NumPy string type, e.g. NaN --> '-1#IND'. + if issubclass(subarr.dtype.type, str): + # GH#16605 + # If not empty convert the data to dtype + # GH#19853: If data is a scalar, subarr has already the result + if not lib.is_scalar(data): + if not np.all(isna(data)): + data = np.array(data, dtype=dtype, copy=False) + subarr = np.array(data, dtype=object, copy=copy) - try: - subarr = period_array(subarr) - except IncompatibleFrequency: - pass + if is_object_dtype(subarr.dtype) and not is_object_dtype(dtype): + inferred = lib.infer_dtype(subarr, skipna=False) + if inferred == "period": + from pandas.core.arrays import period_array + + try: + subarr = period_array(subarr) + except IncompatibleFrequency: + pass return subarr diff --git a/pandas/tests/extension/arrow/bool.py b/pandas/tests/extension/arrow/arrays.py similarity index 80% rename from pandas/tests/extension/arrow/bool.py rename to pandas/tests/extension/arrow/arrays.py index eb75d6d968073..6a28f76e474cc 100644 --- a/pandas/tests/extension/arrow/bool.py +++ b/pandas/tests/extension/arrow/arrays.py @@ -43,18 +43,27 @@ def _is_boolean(self): return True -class ArrowBoolArray(ExtensionArray): - def __init__(self, values): - if not isinstance(values, pa.ChunkedArray): - raise ValueError +@register_extension_dtype +class ArrowStringDtype(ExtensionDtype): - assert values.type == pa.bool_() - self._data = values - self._dtype = ArrowBoolDtype() + type = str + kind = "U" + name = "arrow_string" + na_value = pa.NULL + + @classmethod + def construct_from_string(cls, string): + if string == cls.name: + return cls() + else: + raise TypeError("Cannot construct a '{}' from '{}'".format(cls, string)) + + @classmethod + def construct_array_type(cls): + return ArrowStringArray - def __repr__(self): - return "ArrowBoolArray({})".format(repr(self._data)) +class ArrowExtensionArray(ExtensionArray): @classmethod def from_scalars(cls, values): arr = pa.chunked_array([pa.array(np.asarray(values))]) @@ -69,6 +78,9 @@ def from_array(cls, arr): def _from_sequence(cls, scalars, dtype=None, copy=False): return cls.from_scalars(scalars) + def __repr__(self): + return "{cls}({data})".format(cls=type(self).__name__, data=repr(self._data)) + def __getitem__(self, item): if pd.api.types.is_scalar(item): return self._data.to_pandas()[item] @@ -142,3 +154,23 @@ def any(self, axis=0, out=None): def all(self, axis=0, out=None): return self._data.to_pandas().all() + + +class ArrowBoolArray(ArrowExtensionArray): + def __init__(self, values): + if not isinstance(values, pa.ChunkedArray): + raise ValueError + + assert values.type == pa.bool_() + self._data = values + self._dtype = ArrowBoolDtype() + + +class ArrowStringArray(ArrowExtensionArray): + def __init__(self, values): + if not isinstance(values, pa.ChunkedArray): + raise ValueError + + assert values.type == pa.string() + self._data = values + self._dtype = ArrowStringDtype() diff --git a/pandas/tests/extension/arrow/test_bool.py b/pandas/tests/extension/arrow/test_bool.py index 205edf5da5b74..cc0deca765b41 100644 --- a/pandas/tests/extension/arrow/test_bool.py +++ b/pandas/tests/extension/arrow/test_bool.py @@ -7,7 +7,7 @@ pytest.importorskip("pyarrow", minversion="0.10.0") -from .bool import ArrowBoolArray, ArrowBoolDtype # isort:skip +from .arrays import ArrowBoolArray, ArrowBoolDtype # isort:skip @pytest.fixture diff --git a/pandas/tests/extension/arrow/test_string.py b/pandas/tests/extension/arrow/test_string.py new file mode 100644 index 0000000000000..06f149aa4b75f --- /dev/null +++ b/pandas/tests/extension/arrow/test_string.py @@ -0,0 +1,13 @@ +import pytest + +import pandas as pd + +pytest.importorskip("pyarrow", minversion="0.10.0") + +from .arrays import ArrowStringDtype # isort:skip + + +def test_constructor_from_list(): + # GH 27673 + result = pd.Series(["E"], dtype=ArrowStringDtype()) + assert isinstance(result.dtype, ArrowStringDtype)
I had to add a string-based Arrow Extension array to trigger the bug but did not run the same test suite as we do on the boolean array as I don't see it adding value but just runtime at the moment. - [x] closes #27673 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27674
2019-07-31T13:18:15Z
2019-08-02T11:36:40Z
2019-08-02T11:36:40Z
2019-08-02T11:39:16Z
PERF: Improve performance of cut with IntervalIndex bins
diff --git a/asv_bench/benchmarks/reshape.py b/asv_bench/benchmarks/reshape.py index 1aed756b841a5..cc373f413fb88 100644 --- a/asv_bench/benchmarks/reshape.py +++ b/asv_bench/benchmarks/reshape.py @@ -214,6 +214,7 @@ def setup(self, bins): self.datetime_series = pd.Series( np.random.randint(N, size=N), dtype="datetime64[ns]" ) + self.interval_bins = pd.IntervalIndex.from_breaks(np.linspace(0, N, bins)) def time_cut_int(self, bins): pd.cut(self.int_series, bins) @@ -239,6 +240,14 @@ def time_qcut_timedelta(self, bins): def time_qcut_datetime(self, bins): pd.qcut(self.datetime_series, bins) + def time_cut_interval(self, bins): + # GH 27668 + pd.cut(self.int_series, self.interval_bins) + + def peakmem_cut_interval(self, bins): + # GH 27668 + pd.cut(self.int_series, self.interval_bins) + class Explode: param_names = ["n_rows", "max_list_length"] diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index cc4bab8b9a923..97b4c6cd464e5 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -71,6 +71,7 @@ Performance improvements - Performance improvement in indexing with a non-unique :class:`IntervalIndex` (:issue:`27489`) - Performance improvement in `MultiIndex.is_monotonic` (:issue:`27495`) +- Performance improvement in :func:`cut` when ``bins`` is an :class:`IntervalIndex` (:issue:`27668`) .. _whatsnew_1000.bug_fixes: diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index 949cad6073913..ab354a21a33df 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -373,8 +373,7 @@ def _bins_to_cuts( if isinstance(bins, IntervalIndex): # we have a fast-path here ids = bins.get_indexer(x) - result = algos.take_nd(bins, ids) - result = Categorical(result, categories=bins, ordered=True) + result = Categorical.from_codes(ids, categories=bins, ordered=True) return result, bins unique_bins = algos.unique(bins)
- [X] closes #27668 - [X] benchmarks added / passed - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry ASV output: ``` before after ratio [143bc34a] [d531e7b0] <master> <perf-cut-ii> - 198M 122M 0.62 reshape.Cut.peakmem_cut_interval(1000) - 197M 122M 0.62 reshape.Cut.peakmem_cut_interval(4) - 197M 122M 0.62 reshape.Cut.peakmem_cut_interval(10) - 2.11±0.02s 910±2ms 0.43 reshape.Cut.time_cut_interval(1000) - 1.95±0.01s 761±2ms 0.39 reshape.Cut.time_cut_interval(4) - 1.95±0.03s 763±10ms 0.39 reshape.Cut.time_cut_interval(10) SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. PERFORMANCE INCREASED. ```
https://api.github.com/repos/pandas-dev/pandas/pulls/27669
2019-07-31T04:06:28Z
2019-07-31T12:05:34Z
2019-07-31T12:05:34Z
2019-07-31T13:32:56Z
BUG: Allow plotting boolean values
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 58918f2d8c40e..974d14a4b424c 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -163,7 +163,7 @@ I/O Plotting ^^^^^^^^ -- +- Bug in :meth:`Series.plot` not able to plot boolean values (:issue:`23719`) - Groupby/resample/rolling diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index a3c1499845c2a..ec5c609c1b267 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -586,6 +586,8 @@ class PlotAccessor(PandasObject): mark_right : bool, default True When using a secondary_y axis, automatically mark the column labels with "(right)" in the legend + include_bool : bool, default is False + If True, boolean values can be plotted `**kwds` : keywords Options to pass to matplotlib plotting method diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index c2b37bb297ecb..50f0d16631a15 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -106,6 +106,7 @@ def __init__( colormap=None, table=False, layout=None, + include_bool=False, **kwds ): @@ -191,6 +192,7 @@ def __init__( self.colormap = colormap self.table = table + self.include_bool = include_bool self.kwds = kwds @@ -400,9 +402,12 @@ def _compute_plot_data(self): # GH16953, _convert is needed as fallback, for ``Series`` # with ``dtype == object`` data = data._convert(datetime=True, timedelta=True) - numeric_data = data.select_dtypes( - include=[np.number, "datetime", "datetimetz", "timedelta"] - ) + select_include_type = [np.number, "datetime", "datetimetz", "timedelta"] + + # GH23719, allow plotting boolean + if self.include_bool is True: + select_include_type.append(np.bool_) + numeric_data = data.select_dtypes(include=select_include_type) try: is_empty = numeric_data.empty diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index 8b4a78e9195b5..111c3a70fc09c 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -167,6 +167,15 @@ def test_label(self): ax.legend() # draw it self._check_legend_labels(ax, labels=["LABEL"]) + def test_boolean(self): + # GH 23719 + s = Series([False, False, True]) + _check_plot_works(s.plot, include_bool=True) + + msg = "no numeric data to plot" + with pytest.raises(TypeError, match=msg): + _check_plot_works(s.plot) + def test_line_area_nan_series(self): values = [1, 2, np.nan, 3] s = Series(values)
- [ ] closes #23719 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27665
2019-07-30T21:05:20Z
2019-08-12T19:00:03Z
2019-08-12T19:00:03Z
2020-01-12T21:49:40Z
issue#27482 - added a check for if obj is instance of type in _isna-new
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index fb67decb46b64..fb791eaafe25f 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -93,7 +93,7 @@ Indexing Missing ^^^^^^^ -- +- Bug in :func:`pandas.isnull` or :func:`pandas.isna` when the input is a type e.g. `type(pandas.Series())` (:issue:`27482`) - - diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index 6f599a6be6021..056cd2222af3c 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -133,6 +133,8 @@ def _isna_new(obj): # hack (for now) because MI registers as ndarray elif isinstance(obj, ABCMultiIndex): raise NotImplementedError("isna is not defined for MultiIndex") + elif isinstance(obj, type): + return False elif isinstance( obj, ( @@ -171,6 +173,8 @@ def _isna_old(obj): # hack (for now) because MI registers as ndarray elif isinstance(obj, ABCMultiIndex): raise NotImplementedError("isna is not defined for MultiIndex") + elif isinstance(obj, type): + return False elif isinstance(obj, (ABCSeries, np.ndarray, ABCIndexClass)): return _isna_ndarraylike_old(obj) elif isinstance(obj, ABCGeneric): diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index a688dec50bc95..bbc485ecf94f2 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -86,6 +86,10 @@ def test_isna_isnull(self, isna_f): assert not isna_f(np.inf) assert not isna_f(-np.inf) + # type + assert not isna_f(type(pd.Series())) + assert not isna_f(type(pd.DataFrame())) + # series for s in [ tm.makeFloatSeries(),
- [x] closes #27482 - [x] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27664
2019-07-30T20:25:02Z
2019-08-20T14:00:09Z
2019-08-20T14:00:08Z
2019-08-20T14:00:16Z
BUG: pd.crosstab not working when margin and normalize are set together
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 943a6adb7944e..792dfe4be055e 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -125,6 +125,7 @@ Reshaping ^^^^^^^^^ - A ``KeyError`` is now raised if ``.unstack()`` is called on a :class:`Series` or :class:`DataFrame` with a flat :class:`Index` passing a name which is not the correct one (:issue:`18303`) +- Bug in :meth:`DataFrame.crosstab` when ``margins`` set to ``True`` and ``normalize`` is not ``False``, an error is raised. (:issue:`27500`) - :meth:`DataFrame.join` now suppresses the ``FutureWarning`` when the sort parameter is specified (:issue:`21952`) - diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 79716520f6654..d653dd87308cf 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -611,13 +611,21 @@ def _normalize(table, normalize, margins, margins_name="All"): table = table.fillna(0) elif margins is True: - - column_margin = table.loc[:, margins_name].drop(margins_name) - index_margin = table.loc[margins_name, :].drop(margins_name) - table = table.drop(margins_name, axis=1).drop(margins_name) - # to keep index and columns names - table_index_names = table.index.names - table_columns_names = table.columns.names + # keep index and column of pivoted table + table_index = table.index + table_columns = table.columns + + # check if margin name is in (for MI cases) or equal to last + # index/column and save the column and index margin + if (margins_name not in table.iloc[-1, :].name) | ( + margins_name != table.iloc[:, -1].name + ): + raise ValueError("{} not in pivoted DataFrame".format(margins_name)) + column_margin = table.iloc[:-1, -1] + index_margin = table.iloc[-1, :-1] + + # keep the core table + table = table.iloc[:-1, :-1] # Normalize core table = _normalize(table, normalize=normalize, margins=False) @@ -627,11 +635,13 @@ def _normalize(table, normalize, margins, margins_name="All"): column_margin = column_margin / column_margin.sum() table = concat([table, column_margin], axis=1) table = table.fillna(0) + table.columns = table_columns elif normalize == "index": index_margin = index_margin / index_margin.sum() table = table.append(index_margin) table = table.fillna(0) + table.index = table_index elif normalize == "all" or normalize is True: column_margin = column_margin / column_margin.sum() @@ -641,13 +651,12 @@ def _normalize(table, normalize, margins, margins_name="All"): table = table.append(index_margin) table = table.fillna(0) + table.index = table_index + table.columns = table_columns else: raise ValueError("Not a valid normalize argument") - table.index.names = table_index_names - table.columns.names = table_columns_names - else: raise ValueError("Not a valid margins argument") diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index be82e7f595f8c..03b15d2df1a26 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -2447,3 +2447,84 @@ def test_crosstab_unsorted_order(self): [[1, 0, 0], [0, 1, 0], [0, 0, 1]], index=e_idx, columns=e_columns ) tm.assert_frame_equal(result, expected) + + def test_margin_normalize(self): + # GH 27500 + df = pd.DataFrame( + { + "A": ["foo", "foo", "foo", "foo", "foo", "bar", "bar", "bar", "bar"], + "B": ["one", "one", "one", "two", "two", "one", "one", "two", "two"], + "C": [ + "small", + "large", + "large", + "small", + "small", + "large", + "small", + "small", + "large", + ], + "D": [1, 2, 2, 3, 3, 4, 5, 6, 7], + "E": [2, 4, 5, 5, 6, 6, 8, 9, 9], + } + ) + # normalize on index + result = pd.crosstab( + [df.A, df.B], df.C, margins=True, margins_name="Sub-Total", normalize=0 + ) + expected = pd.DataFrame( + [[0.5, 0.5], [0.5, 0.5], [0.666667, 0.333333], [0, 1], [0.444444, 0.555556]] + ) + expected.index = MultiIndex( + levels=[["Sub-Total", "bar", "foo"], ["", "one", "two"]], + codes=[[1, 1, 2, 2, 0], [1, 2, 1, 2, 0]], + names=["A", "B"], + ) + expected.columns = Index(["large", "small"], dtype="object", name="C") + tm.assert_frame_equal(result, expected) + + # normalize on columns + result = pd.crosstab( + [df.A, df.B], df.C, margins=True, margins_name="Sub-Total", normalize=1 + ) + expected = pd.DataFrame( + [ + [0.25, 0.2, 0.222222], + [0.25, 0.2, 0.222222], + [0.5, 0.2, 0.333333], + [0, 0.4, 0.222222], + ] + ) + expected.columns = Index( + ["large", "small", "Sub-Total"], dtype="object", name="C" + ) + expected.index = MultiIndex( + levels=[["bar", "foo"], ["one", "two"]], + codes=[[0, 0, 1, 1], [0, 1, 0, 1]], + names=["A", "B"], + ) + tm.assert_frame_equal(result, expected) + + # normalize on both index and column + result = pd.crosstab( + [df.A, df.B], df.C, margins=True, margins_name="Sub-Total", normalize=True + ) + expected = pd.DataFrame( + [ + [0.111111, 0.111111, 0.222222], + [0.111111, 0.111111, 0.222222], + [0.222222, 0.111111, 0.333333], + [0.000000, 0.222222, 0.222222], + [0.444444, 0.555555, 1], + ] + ) + expected.columns = Index( + ["large", "small", "Sub-Total"], dtype="object", name="C" + ) + expected.index = MultiIndex( + levels=[["Sub-Total", "bar", "foo"], ["", "one", "two"]], + codes=[[1, 1, 2, 2, 0], [1, 2, 1, 2, 0]], + names=["A", "B"], + ) + tm.assert_frame_equal(result, expected)
- [ ] closes #27500 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27663
2019-07-30T19:58:02Z
2019-08-06T15:45:31Z
2019-08-06T15:45:31Z
2019-08-06T15:45:32Z
DOC: add anonymizeIp for Google analytics in docs
diff --git a/doc/source/themes/nature_with_gtoc/layout.html b/doc/source/themes/nature_with_gtoc/layout.html index b3f13f99f44d4..6e7d8ece35133 100644 --- a/doc/source/themes/nature_with_gtoc/layout.html +++ b/doc/source/themes/nature_with_gtoc/layout.html @@ -94,15 +94,15 @@ <h3 style="margin-top: 1.5em;">{{ _('Search') }}</h3> }); }); </script> -<script type="text/javascript"> - var _gaq = _gaq || []; - _gaq.push(['_setAccount', 'UA-27880019-2']); - _gaq.push(['_trackPageview']); - (function() { - var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; - ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js'; - var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); - })(); +<!-- Google Analytics --> +<script> +window.ga=window.ga||function(){(ga.q=ga.q||[]).push(arguments)};ga.l=+new Date; +ga('create', 'UA-27880019-2', 'auto'); +ga('set', 'anonymizeIp', true); +ga('send', 'pageview'); </script> +<script async src='https://www.google-analytics.com/analytics.js'></script> +<!-- End Google Analytics --> + {% endblock %}
Using a more recent snippet (following their current docs), and adding anonymization of the IP (according to their docs, this should only "slightly reduce the accuracy of geolocation"). If we do this, should do the same for main website as well.
https://api.github.com/repos/pandas-dev/pandas/pulls/27662
2019-07-30T19:50:58Z
2019-08-01T20:42:19Z
2019-08-01T20:42:19Z
2020-02-03T09:29:21Z
Backport PR #27651: DOC: improve warnings for Series.{real,imag}
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index fa9ca98f9c8d8..fb67decb46b64 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -64,7 +64,7 @@ Numeric Conversion ^^^^^^^^^^ -- +- Improved the warnings for the deprecated methods :meth:`Series.real` and :meth:`Series.imag` (:issue:`27610`) - - diff --git a/pandas/core/series.py b/pandas/core/series.py index 59ea8c6bd6c5d..42afb3537c5d8 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -958,7 +958,9 @@ def real(self): .. deprecated 0.25.0 """ warnings.warn( - "`real` has be deprecated and will be removed in a " "future verison", + "`real` is deprecated and will be removed in a future version. " + "To eliminate this warning for a Series `ser`, use " + "`np.real(ser.to_numpy())` or `ser.to_numpy().real`.", FutureWarning, stacklevel=2, ) @@ -976,7 +978,9 @@ def imag(self): .. deprecated 0.25.0 """ warnings.warn( - "`imag` has be deprecated and will be removed in a " "future verison", + "`imag` is deprecated and will be removed in a future version. " + "To eliminate this warning for a Series `ser`, use " + "`np.imag(ser.to_numpy())` or `ser.to_numpy().imag`.", FutureWarning, stacklevel=2, )
Manual backport for #27651
https://api.github.com/repos/pandas-dev/pandas/pulls/27659
2019-07-30T13:33:56Z
2019-07-30T14:46:07Z
2019-07-30T14:46:07Z
2019-07-30T14:56:16Z
BUG: Fix dir(interval_index)
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index fb67decb46b64..40fefe7ec43a8 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -78,7 +78,7 @@ Strings Interval ^^^^^^^^ - +- Bug in :class:`IntervalIndex` where `dir(obj)` would raise ``ValueError`` (:issue:`27571`) - - - diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index d430cb3d3913f..abaa1c639f048 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -925,6 +925,7 @@ _TYPE_MAP = { 'M': 'datetime64', 'timedelta64[ns]': 'timedelta64', 'm': 'timedelta64', + 'interval': 'interval', } # types only exist on certain platform diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 54882d039f135..f52f98db9fc84 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -1953,8 +1953,11 @@ def _validate(data): values = getattr(data, "values", data) # Series / Index values = getattr(values, "categories", values) # categorical / normal - # missing values obfuscate type inference -> skip - inferred_dtype = lib.infer_dtype(values, skipna=True) + try: + inferred_dtype = lib.infer_dtype(values, skipna=True) + except ValueError: + # GH#27571 mostly occurs with ExtensionArray + inferred_dtype = None if inferred_dtype not in allowed_types: raise AttributeError("Can only use .str accessor with string values!") diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index ff48ae9b3c2e5..2933dfca736be 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -1153,6 +1153,17 @@ def test_categorical(self): result = lib.infer_dtype(Series(arr), skipna=True) assert result == "categorical" + def test_interval(self): + idx = pd.IntervalIndex.from_breaks(range(5), closed="both") + inferred = lib.infer_dtype(idx, skipna=False) + assert inferred == "interval" + + inferred = lib.infer_dtype(idx._data, skipna=False) + assert inferred == "interval" + + inferred = lib.infer_dtype(pd.Series(idx), skipna=False) + assert inferred == "interval" + class TestNumberScalar: def test_is_number(self): diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index c61af1ce70aed..c1a21e6a7f152 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -1095,3 +1095,10 @@ def test_is_all_dates(self): ) year_2017_index = pd.IntervalIndex([year_2017]) assert not year_2017_index.is_all_dates + + +def test_dir(): + # GH#27571 dir(interval_index) should not raise + index = IntervalIndex.from_arrays([0, 1], [1, 2]) + result = dir(index) + assert "str" not in result
- [x] closes #27571 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27653
2019-07-30T02:31:56Z
2019-08-01T12:56:49Z
2019-08-01T12:56:49Z
2019-08-01T14:07:24Z
improve warnings for Series.{real,imag}
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index fa9ca98f9c8d8..fb67decb46b64 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -64,7 +64,7 @@ Numeric Conversion ^^^^^^^^^^ -- +- Improved the warnings for the deprecated methods :meth:`Series.real` and :meth:`Series.imag` (:issue:`27610`) - - diff --git a/pandas/core/series.py b/pandas/core/series.py index b445ff5f944de..106bb3c7d6cb4 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -955,7 +955,9 @@ def real(self): .. deprecated:: 0.25.0 """ warnings.warn( - "`real` has be deprecated and will be removed in a future version", + "`real` is deprecated and will be removed in a future version. " + "To eliminate this warning for a Series `ser`, use " + "`np.real(ser.to_numpy())` or `ser.to_numpy().real`.", FutureWarning, stacklevel=2, ) @@ -973,7 +975,9 @@ def imag(self): .. deprecated:: 0.25.0 """ warnings.warn( - "`imag` has be deprecated and will be removed in a future version", + "`imag` is deprecated and will be removed in a future version. " + "To eliminate this warning for a Series `ser`, use " + "`np.imag(ser.to_numpy())` or `ser.to_numpy().imag`.", FutureWarning, stacklevel=2, )
- [x] closes #27610 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27651
2019-07-29T22:57:10Z
2019-07-30T09:10:49Z
2019-07-30T09:10:49Z
2019-08-21T21:09:15Z
issue #27642 - timedelta merge asof with tolerance
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 680d69a9862cd..33296045fa05c 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -95,6 +95,7 @@ Reshaping ^^^^^^^^^ - A ``KeyError`` is now raised if ``.unstack()`` is called on a :class:`Series` or :class:`DataFrame` with a flat :class:`Index` passing a name which is not the correct one (:issue:`18303`) +- Bug :meth:`merge_asof` could not merge :class:`Timedelta` objects when passing `tolerance` kwarg (:issue:`27642`) - Bug in :meth:`DataFrame.crosstab` when ``margins`` set to ``True`` and ``normalize`` is not ``False``, an error is raised. (:issue:`27500`) - :meth:`DataFrame.join` now suppresses the ``FutureWarning`` when the sort parameter is specified (:issue:`21952`) - Bug in :meth:`DataFrame.join` raising with readonly arrays (:issue:`27943`) diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index f45c7693bf6ed..225de3f11cf7d 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -22,7 +22,6 @@ is_bool, is_bool_dtype, is_categorical_dtype, - is_datetime64_dtype, is_datetime64tz_dtype, is_datetimelike, is_dtype_equal, @@ -1635,7 +1634,7 @@ def _get_merge_keys(self): ) ) - if is_datetime64_dtype(lt) or is_datetime64tz_dtype(lt): + if is_datetimelike(lt): if not isinstance(self.tolerance, Timedelta): raise MergeError(msg) if self.tolerance < Timedelta(0): diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py index 6b66386bafc5e..7412b1de643a1 100644 --- a/pandas/tests/reshape/merge/test_merge_asof.py +++ b/pandas/tests/reshape/merge/test_merge_asof.py @@ -1,3 +1,5 @@ +import datetime + import numpy as np import pytest import pytz @@ -588,14 +590,23 @@ def test_non_sorted(self): # ok, though has dupes merge_asof(trades, self.quotes, on="time", by="ticker") - def test_tolerance(self): + @pytest.mark.parametrize( + "tolerance", + [ + Timedelta("1day"), + pytest.param( + datetime.timedelta(days=1), + marks=pytest.mark.xfail(reason="not implemented", strict=True), + ), + ], + ids=["pd.Timedelta", "datetime.timedelta"], + ) + def test_tolerance(self, tolerance): trades = self.trades quotes = self.quotes - result = merge_asof( - trades, quotes, on="time", by="ticker", tolerance=Timedelta("1day") - ) + result = merge_asof(trades, quotes, on="time", by="ticker", tolerance=tolerance) expected = self.tolerance assert_frame_equal(result, expected) @@ -1246,3 +1257,39 @@ def test_by_mixed_tz_aware(self): ) expected["value_y"] = np.array([np.nan], dtype=object) assert_frame_equal(result, expected) + + def test_timedelta_tolerance_nearest(self): + # GH 27642 + + left = pd.DataFrame( + list(zip([0, 5, 10, 15, 20, 25], [0, 1, 2, 3, 4, 5])), + columns=["time", "left"], + ) + + left["time"] = pd.to_timedelta(left["time"], "ms") + + right = pd.DataFrame( + list(zip([0, 3, 9, 12, 15, 18], [0, 1, 2, 3, 4, 5])), + columns=["time", "right"], + ) + + right["time"] = pd.to_timedelta(right["time"], "ms") + + expected = pd.DataFrame( + list( + zip( + [0, 5, 10, 15, 20, 25], + [0, 1, 2, 3, 4, 5], + [0, np.nan, 2, 4, np.nan, np.nan], + ) + ), + columns=["time", "left", "right"], + ) + + expected["time"] = pd.to_timedelta(expected["time"], "ms") + + result = pd.merge_asof( + left, right, on="time", tolerance=Timedelta("1ms"), direction="nearest" + ) + + assert_frame_equal(result, expected)
- [X] closes #27642 - [x] tests 2 / 1 [added / passed] - [X] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry - [ ] \(Optional) allow users to pass datetime.timedelta objects for tolerance
https://api.github.com/repos/pandas-dev/pandas/pulls/27650
2019-07-29T21:35:20Z
2019-08-22T13:09:50Z
2019-08-22T13:09:49Z
2021-06-27T18:50:43Z
CLN: all the things
diff --git a/pandas/_config/config.py b/pandas/_config/config.py index 61e926035c3f2..4f0720abd1445 100644 --- a/pandas/_config/config.py +++ b/pandas/_config/config.py @@ -110,7 +110,7 @@ def _set_option(*args, **kwargs): # must at least 1 arg deal with constraints later nargs = len(args) if not nargs or nargs % 2 != 0: - raise ValueError("Must provide an even number of non-keyword " "arguments") + raise ValueError("Must provide an even number of non-keyword arguments") # default to false silent = kwargs.pop("silent", False) @@ -395,7 +395,7 @@ class option_context: def __init__(self, *args): if not (len(args) % 2 == 0 and len(args) >= 2): raise ValueError( - "Need to invoke as" " option_context(pat, val, [(pat, val), ...])." + "Need to invoke as option_context(pat, val, [(pat, val), ...])." ) self.ops = list(zip(args[::2], args[1::2])) diff --git a/pandas/compat/numpy/function.py b/pandas/compat/numpy/function.py index 89f7d71e21e9d..c2fe7d1dd12f4 100644 --- a/pandas/compat/numpy/function.py +++ b/pandas/compat/numpy/function.py @@ -59,7 +59,7 @@ def __call__(self, args, kwargs, fname=None, max_fname_arg_count=None, method=No ) else: raise ValueError( - "invalid validation method " "'{method}'".format(method=method) + "invalid validation method '{method}'".format(method=method) ) diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 8e76ad8a375f7..2e086c8ce8c34 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -496,7 +496,7 @@ def _generate_range( if start is None and end is None: if closed is not None: raise ValueError( - "Closed has to be None if not both of startand end are defined" + "Closed has to be None if not both of start and end are defined" ) if start is NaT or end is NaT: raise ValueError("Neither `start` nor `end` can be NaT") diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 4dc1dfcae0777..da3db1c18e534 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -227,7 +227,7 @@ def aggregate(self, func, *args, **kwargs): kwargs = {} elif func is None: # nicer error message - raise TypeError("Must provide 'func' or tuples of " "'(column, aggfunc).") + raise TypeError("Must provide 'func' or tuples of '(column, aggfunc).") func = _maybe_mangle_lambdas(func) @@ -836,9 +836,7 @@ def aggregate(self, func_or_funcs=None, *args, **kwargs): relabeling = func_or_funcs is None columns = None - no_arg_message = ( - "Must provide 'func_or_funcs' or named " "aggregation **kwargs." - ) + no_arg_message = "Must provide 'func_or_funcs' or named aggregation **kwargs." if relabeling: columns = list(kwargs) if not PY36: diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 5961a7ff72832..15b94e59c065c 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -462,7 +462,7 @@ def get_converter(s): name_sample = names[0] if isinstance(index_sample, tuple): if not isinstance(name_sample, tuple): - msg = "must supply a tuple to get_group with multiple" " grouping keys" + msg = "must supply a tuple to get_group with multiple grouping keys" raise ValueError(msg) if not len(name_sample) == len(index_sample): try: @@ -715,7 +715,7 @@ def f(g): else: raise ValueError( - "func must be a callable if args or " "kwargs are supplied" + "func must be a callable if args or kwargs are supplied" ) else: f = func @@ -1872,7 +1872,7 @@ def quantile(self, q=0.5, interpolation="linear"): def pre_processor(vals: np.ndarray) -> Tuple[np.ndarray, Optional[Type]]: if is_object_dtype(vals): raise TypeError( - "'quantile' cannot be performed against " "'object' dtypes!" + "'quantile' cannot be performed against 'object' dtypes!" ) inference = None @@ -2201,9 +2201,7 @@ def _get_cythonized_result( `Series` or `DataFrame` with filled values """ if result_is_index and aggregate: - raise ValueError( - "'result_is_index' and 'aggregate' cannot both " "be True!" - ) + raise ValueError("'result_is_index' and 'aggregate' cannot both be True!") if post_processing: if not callable(pre_processing): raise ValueError("'post_processing' must be a callable!") @@ -2212,7 +2210,7 @@ def _get_cythonized_result( raise ValueError("'pre_processing' must be a callable!") if not needs_values: raise ValueError( - "Cannot use 'pre_processing' without " "specifying 'needs_values'!" + "Cannot use 'pre_processing' without specifying 'needs_values'!" ) labels, _, ngroups = grouper.group_info diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index f8417c3f01eac..1d88ebd26b1b6 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -25,6 +25,7 @@ from pandas.core.arrays import Categorical, ExtensionArray import pandas.core.common as com from pandas.core.frame import DataFrame +from pandas.core.groupby.categorical import recode_for_groupby, recode_from_groupby from pandas.core.groupby.ops import BaseGrouper from pandas.core.index import CategoricalIndex, Index, MultiIndex from pandas.core.series import Series @@ -310,8 +311,6 @@ def __init__( # a passed Categorical elif is_categorical_dtype(self.grouper): - from pandas.core.groupby.categorical import recode_for_groupby - self.grouper, self.all_grouper = recode_for_groupby( self.grouper, self.sort, observed ) @@ -361,13 +360,10 @@ def __init__( # Timestamps like if getattr(self.grouper, "dtype", None) is not None: if is_datetime64_dtype(self.grouper): - from pandas import to_datetime - - self.grouper = to_datetime(self.grouper) + self.grouper = self.grouper.astype("datetime64[ns]") elif is_timedelta64_dtype(self.grouper): - from pandas import to_timedelta - self.grouper = to_timedelta(self.grouper) + self.grouper = self.grouper.astype("timedelta64[ns]") def __repr__(self): return "Grouping({0})".format(self.name) @@ -400,8 +396,6 @@ def labels(self): @cache_readonly def result_index(self): if self.all_grouper is not None: - from pandas.core.groupby.categorical import recode_from_groupby - return recode_from_groupby(self.all_grouper, self.sort, self.group_index) return self.group_index @@ -493,12 +487,12 @@ def _get_grouper( elif nlevels == 0: raise ValueError("No group keys passed!") else: - raise ValueError("multiple levels only valid with " "MultiIndex") + raise ValueError("multiple levels only valid with MultiIndex") if isinstance(level, str): if obj.index.name != level: raise ValueError( - "level name {} is not the name of the " "index".format(level) + "level name {} is not the name of the index".format(level) ) elif level > 0 or level < -1: raise ValueError("level > 0 or level < -1 only valid with MultiIndex") diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index cc8aec4cc243b..1484feeeada64 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -467,12 +467,12 @@ def _cython_operation(self, kind, values, how, axis, min_count=-1, **kwargs): elif is_datetime64_any_dtype(values): if how in ["add", "prod", "cumsum", "cumprod"]: raise NotImplementedError( - "datetime64 type does not support {} " "operations".format(how) + "datetime64 type does not support {} operations".format(how) ) elif is_timedelta64_dtype(values): if how in ["prod", "cumprod"]: raise NotImplementedError( - "timedelta64 type does not support {} " "operations".format(how) + "timedelta64 type does not support {} operations".format(how) ) arity = self._cython_arity.get(how, 1) @@ -489,7 +489,7 @@ def _cython_operation(self, kind, values, how, axis, min_count=-1, **kwargs): values = values.T if arity > 1: raise NotImplementedError( - "arity of more than 1 is not " "supported for the 'how' argument" + "arity of more than 1 is not supported for the 'how' argument" ) out_shape = (self.ngroups,) + values.shape[1:] @@ -604,9 +604,7 @@ def _aggregate( ): if values.ndim > 3: # punting for now - raise NotImplementedError( - "number of dimensions is currently " "limited to 3" - ) + raise NotImplementedError("number of dimensions is currently limited to 3") elif values.ndim > 2: for i, chunk in enumerate(values.transpose(2, 0, 1)): @@ -631,9 +629,7 @@ def _transform( comp_ids, _, ngroups = self.group_info if values.ndim > 3: # punting for now - raise NotImplementedError( - "number of dimensions is currently " "limited to 3" - ) + raise NotImplementedError("number of dimensions is currently limited to 3") elif values.ndim > 2: for i, chunk in enumerate(values.transpose(2, 0, 1)): diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py index 5ba23990cbd51..2036728e702f3 100644 --- a/pandas/core/indexes/accessors.py +++ b/pandas/core/indexes/accessors.py @@ -340,4 +340,4 @@ def __new__(cls, data): except Exception: pass # we raise an attribute error anyway - raise AttributeError("Can only use .dt accessor with datetimelike " "values") + raise AttributeError("Can only use .dt accessor with datetimelike values") diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 745f8f3c90ea8..8cacd22fb1cb1 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -376,9 +376,7 @@ def __new__( data = maybe_cast_to_integer_array(data, dtype, copy=copy) elif inferred in ["floating", "mixed-integer-float"]: if isna(data).any(): - raise ValueError( - "cannot convert float " "NaN to integer" - ) + raise ValueError("cannot convert float NaN to integer") if inferred == "mixed-integer-float": data = maybe_cast_to_integer_array(data, dtype) @@ -1182,7 +1180,7 @@ def summary(self, name=None): .. deprecated:: 0.23.0 """ warnings.warn( - "'summary' is deprecated and will be removed in a " "future version.", + "'summary' is deprecated and will be removed in a future version.", FutureWarning, stacklevel=2, ) @@ -1521,7 +1519,7 @@ def _validate_index_level(self, level): ) elif level > 0: raise IndexError( - "Too many levels:" " Index has only 1 level, not %d" % (level + 1) + "Too many levels: Index has only 1 level, not %d" % (level + 1) ) elif level != self.name: raise KeyError( @@ -2953,7 +2951,7 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None): if not self.is_unique: raise InvalidIndexError( - "Reindexing only valid with uniquely" " valued Index objects" + "Reindexing only valid with uniquely valued Index objects" ) if method == "pad" or method == "backfill": @@ -2980,7 +2978,7 @@ def _convert_tolerance(self, tolerance, target): # override this method on subclasses tolerance = np.asarray(tolerance) if target.size != tolerance.size and tolerance.size > 1: - raise ValueError("list-like tolerance size must match " "target index size") + raise ValueError("list-like tolerance size must match target index size") return tolerance def _get_fill_indexer(self, target, method, limit=None, tolerance=None): @@ -3712,9 +3710,7 @@ def _get_leaf_sorter(labels): return lib.get_level_sorter(lab, ensure_int64(starts)) if isinstance(self, MultiIndex) and isinstance(other, MultiIndex): - raise TypeError( - "Join on level between two MultiIndex objects " "is ambiguous" - ) + raise TypeError("Join on level between two MultiIndex objects is ambiguous") left, right = self, other @@ -3728,7 +3724,7 @@ def _get_leaf_sorter(labels): if not right.is_unique: raise NotImplementedError( - "Index._join_level on non-unique index " "is not implemented" + "Index._join_level on non-unique index is not implemented" ) new_level, left_lev_indexer, right_lev_indexer = old_level.join( @@ -4554,9 +4550,7 @@ def sort(self, *args, **kwargs): """ Use sort_values instead. """ - raise TypeError( - "cannot sort an Index object in-place, use " "sort_values instead" - ) + raise TypeError("cannot sort an Index object in-place, use sort_values instead") def shift(self, periods=1, freq=None): """ @@ -5205,7 +5199,7 @@ def slice_locs(self, start=None, end=None, step=None, kind=None): pass else: if not tz_compare(ts_start.tzinfo, ts_end.tzinfo): - raise ValueError("Both dates must have the " "same UTC offset") + raise ValueError("Both dates must have the same UTC offset") start_slice = None if start is not None: @@ -5397,12 +5391,10 @@ def _validate_for_numeric_binop(self, other, op): if isinstance(other, (Index, ABCSeries, np.ndarray)): if len(self) != len(other): - raise ValueError("cannot evaluate a numeric op with " "unequal lengths") + raise ValueError("cannot evaluate a numeric op with unequal lengths") other = com.values_from_object(other) if other.dtype.kind not in ["f", "i", "u"]: - raise TypeError( - "cannot evaluate a numeric op " "with a non-numeric dtype" - ) + raise TypeError("cannot evaluate a numeric op with a non-numeric dtype") elif isinstance(other, (ABCDateOffset, np.timedelta64, timedelta)): # higher up to handle pass @@ -5571,7 +5563,7 @@ def logical_func(self, *args, **kwargs): return logical_func cls.all = _make_logical_function( - "all", "Return whether all elements " "are True.", np.all + "all", "Return whether all elements are True.", np.all ) cls.any = _make_logical_function( "any", "Return whether any element is True.", np.any diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index e14bf7f86c0be..0f6aa711adc90 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -7,6 +7,7 @@ from pandas._config import get_option from pandas._libs import index as libindex +from pandas._libs.hashtable import duplicated_int64 import pandas.compat as compat from pandas.compat.numpy import function as nv from pandas.util._decorators import Appender, cache_readonly @@ -25,7 +26,7 @@ from pandas._typing import AnyArrayLike from pandas.core import accessor from pandas.core.algorithms import take_1d -from pandas.core.arrays.categorical import Categorical, contains +from pandas.core.arrays.categorical import Categorical, _recode_for_categories, contains import pandas.core.common as com import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs @@ -290,7 +291,7 @@ def _is_dtype_compat(self, other): other = other._values if not other.is_dtype_equal(self): raise TypeError( - "categories must match existing categories " "when appending" + "categories must match existing categories when appending" ) else: values = other @@ -299,7 +300,7 @@ def _is_dtype_compat(self, other): other = CategoricalIndex(self._create_categorical(other, dtype=self.dtype)) if not other.isin(values).all(): raise TypeError( - "cannot append a non-category item to a " "CategoricalIndex" + "cannot append a non-category item to a CategoricalIndex" ) return other @@ -473,8 +474,6 @@ def unique(self, level=None): @Appender(Index.duplicated.__doc__) def duplicated(self, keep="first"): - from pandas._libs.hashtable import duplicated_int64 - codes = self.codes.astype("i8") return duplicated_int64(codes, keep) @@ -581,15 +580,15 @@ def reindex(self, target, method=None, level=None, limit=None, tolerance=None): if method is not None: raise NotImplementedError( - "argument method is not implemented for " "CategoricalIndex.reindex" + "argument method is not implemented for CategoricalIndex.reindex" ) if level is not None: raise NotImplementedError( - "argument level is not implemented for " "CategoricalIndex.reindex" + "argument level is not implemented for CategoricalIndex.reindex" ) if limit is not None: raise NotImplementedError( - "argument limit is not implemented for " "CategoricalIndex.reindex" + "argument limit is not implemented for CategoricalIndex.reindex" ) target = ibase.ensure_index(target) @@ -657,8 +656,6 @@ def _reindex_non_unique(self, target): @Appender(_index_shared_docs["get_indexer"] % _index_doc_kwargs) def get_indexer(self, target, method=None, limit=None, tolerance=None): - from pandas.core.arrays.categorical import _recode_for_categories - method = missing.clean_reindex_fill_method(method) target = ibase.ensure_index(target) @@ -672,7 +669,7 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None): ) elif method == "nearest": raise NotImplementedError( - "method='nearest' not implemented yet " "for CategoricalIndex" + "method='nearest' not implemented yet for CategoricalIndex" ) if isinstance(target, CategoricalIndex) and self.values.is_dtype_equal(target): diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 0fb8f6823ac18..af99c7a2754e5 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -325,7 +325,7 @@ def asobject(self): *this is an internal non-public method* """ warnings.warn( - "'asobject' is deprecated. Use 'astype(object)'" " instead", + "'asobject' is deprecated. Use 'astype(object)' instead", FutureWarning, stacklevel=2, ) @@ -335,7 +335,7 @@ def _convert_tolerance(self, tolerance, target): tolerance = np.asarray(to_timedelta(tolerance).to_numpy()) if target.size != tolerance.size and tolerance.size > 1: - raise ValueError("list-like tolerance size must match " "target index size") + raise ValueError("list-like tolerance size must match target index size") return tolerance def tolist(self): diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index e9296eea2b8a3..04522fde4521c 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -803,11 +803,9 @@ def _maybe_utc_convert(self, other): if isinstance(other, DatetimeIndex): if self.tz is not None: if other.tz is None: - raise TypeError( - "Cannot join tz-naive with tz-aware " "DatetimeIndex" - ) + raise TypeError("Cannot join tz-naive with tz-aware DatetimeIndex") elif other.tz is not None: - raise TypeError("Cannot join tz-naive with tz-aware " "DatetimeIndex") + raise TypeError("Cannot join tz-naive with tz-aware DatetimeIndex") if not timezones.tz_compare(self.tz, other.tz): this = self.tz_convert("UTC") @@ -1048,7 +1046,7 @@ def get_loc(self, key, method=None, tolerance=None): if isinstance(key, time): if method is not None: raise NotImplementedError( - "cannot yet lookup inexact labels " "when key is a time object" + "cannot yet lookup inexact labels when key is a time object" ) return self.indexer_at_time(key) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 66290ae54e626..d941dc547befe 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1058,7 +1058,7 @@ def insert(self, loc, item): if isinstance(item, Interval): if item.closed != self.closed: raise ValueError( - "inserted item must be closed on the same " "side as the index" + "inserted item must be closed on the same side as the index" ) left_insert = item.left right_insert = item.right @@ -1067,7 +1067,7 @@ def insert(self, loc, item): left_insert = right_insert = item else: raise ValueError( - "can only insert Interval objects and NA into " "an IntervalIndex" + "can only insert Interval objects and NA into an IntervalIndex" ) new_left = self.left.insert(loc, left_insert) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index a7c3449615299..488107690fbd6 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -8,6 +8,7 @@ from pandas._config import get_option from pandas._libs import Timestamp, algos as libalgos, index as libindex, lib, tslibs +from pandas._libs.hashtable import duplicated_int64 from pandas.compat.numpy import function as nv from pandas.errors import PerformanceWarning, UnsortedIndexError from pandas.util._decorators import Appender, cache_readonly, deprecate_kwarg @@ -29,6 +30,8 @@ from pandas.core.dtypes.missing import array_equivalent, isna import pandas.core.algorithms as algos +from pandas.core.arrays import Categorical +from pandas.core.arrays.categorical import _factorize_from_iterables import pandas.core.common as com import pandas.core.indexes.base as ibase from pandas.core.indexes.base import ( @@ -39,6 +42,12 @@ ) from pandas.core.indexes.frozen import FrozenList, _ensure_frozen import pandas.core.missing as missing +from pandas.core.sorting import ( + get_group_index, + indexer_from_factorized, + lexsort_indexer, +) +from pandas.core.util.hashing import hash_tuple, hash_tuples from pandas.io.formats.printing import ( format_object_attrs, @@ -415,8 +424,6 @@ def from_arrays(cls, arrays, sortorder=None, names=None): if len(arrays[i]) != len(arrays[i - 1]): raise ValueError("all arrays must be same length") - from pandas.core.arrays.categorical import _factorize_from_iterables - codes, levels = _factorize_from_iterables(arrays) if names is None: names = [getattr(arr, "name", None) for arr in arrays] @@ -527,7 +534,6 @@ def from_product(cls, iterables, sortorder=None, names=None): (2, 'purple')], names=['number', 'color']) """ - from pandas.core.arrays.categorical import _factorize_from_iterables from pandas.core.reshape.util import cartesian_product if not is_list_like(iterables): @@ -772,7 +778,7 @@ def codes(self): @property def labels(self): warnings.warn( - (".labels was deprecated in version 0.24.0. " "Use .codes instead."), + (".labels was deprecated in version 0.24.0. Use .codes instead."), FutureWarning, stacklevel=2, ) @@ -1213,7 +1219,7 @@ def _set_names(self, names, level=None, validate=True): raise ValueError("Length of names must match length of level.") if validate and level is None and len(names) != self.nlevels: raise ValueError( - "Length of names must match number of levels in " "MultiIndex." + "Length of names must match number of levels in MultiIndex." ) if level is None: @@ -1280,7 +1286,7 @@ def _get_level_number(self, level): count = self.names.count(level) if (count > 1) and not is_integer(level): raise ValueError( - "The name %s occurs multiple times, use a " "level number" % level + "The name %s occurs multiple times, use a level number" % level ) try: level = self.names.index(level) @@ -1399,8 +1405,6 @@ def _inferred_type_levels(self): @cache_readonly def _hashed_values(self): """ return a uint64 ndarray of my hashed values """ - from pandas.core.util.hashing import hash_tuples - return hash_tuples(self) def _hashed_indexing_key(self, key): @@ -1420,9 +1424,7 @@ def _hashed_indexing_key(self, key): Notes ----- we need to stringify if we have mixed levels - """ - from pandas.core.util.hashing import hash_tuples, hash_tuple if not isinstance(key, tuple): return hash_tuples(key) @@ -1442,9 +1444,6 @@ def f(k, stringify): @Appender(Index.duplicated.__doc__) def duplicated(self, keep="first"): - from pandas.core.sorting import get_group_index - from pandas._libs.hashtable import duplicated_int64 - shape = map(len, self.levels) ids = get_group_index(self.codes, shape, sort=False, xnull=False) @@ -1636,11 +1635,11 @@ def to_frame(self, index=True, name=None): if name is not None: if not is_list_like(name): - raise TypeError("'name' must be a list / sequence " "of column names.") + raise TypeError("'name' must be a list / sequence of column names.") if len(name) != len(self.levels): raise ValueError( - "'name' should have same length as " "number of levels on index." + "'name' should have same length as number of levels on index." ) idx_names = name else: @@ -2107,9 +2106,7 @@ def repeat(self, repeats, axis=None): ) def where(self, cond, other=None): - raise NotImplementedError( - ".where is not supported for " "MultiIndex operations" - ) + raise NotImplementedError(".where is not supported for MultiIndex operations") @deprecate_kwarg(old_arg_name="labels", new_arg_name="codes") def drop(self, codes, level=None, errors="raise"): @@ -2274,7 +2271,6 @@ def _get_codes_for_sorting(self): for sorting, where we need to disambiguate that -1 is not a valid valid """ - from pandas.core.arrays import Categorical def cats(level_codes): return np.arange( @@ -2309,8 +2305,6 @@ def sortlevel(self, level=0, ascending=True, sort_remaining=True): indexer : np.ndarray Indices of output values in original index. """ - from pandas.core.sorting import indexer_from_factorized - if isinstance(level, (str, int)): level = [level] level = [self._get_level_number(lev) for lev in level] @@ -2321,8 +2315,6 @@ def sortlevel(self, level=0, ascending=True, sort_remaining=True): if not len(level) == len(ascending): raise ValueError("level must have same length as ascending") - from pandas.core.sorting import lexsort_indexer - indexer = lexsort_indexer( [self.codes[lev] for lev in level], orders=ascending ) @@ -2419,14 +2411,12 @@ def get_indexer(self, target, method=None, limit=None, tolerance=None): ) if not self.is_unique: - raise ValueError( - "Reindexing only valid with uniquely valued " "Index objects" - ) + raise ValueError("Reindexing only valid with uniquely valued Index objects") if method == "pad" or method == "backfill": if tolerance is not None: raise NotImplementedError( - "tolerance not implemented yet " "for MultiIndex" + "tolerance not implemented yet for MultiIndex" ) indexer = self._engine.get_indexer(target, method, limit) elif method == "nearest": @@ -2766,7 +2756,7 @@ def maybe_mi_droplevels(indexer, levels, drop_level: bool): if isinstance(level, (tuple, list)): if len(key) != len(level): raise AssertionError( - "Key for location must have same " "length as number of levels" + "Key for location must have same length as number of levels" ) result = None for lev, k in zip(level, key): @@ -3323,7 +3313,7 @@ def astype(self, dtype, copy=True): raise NotImplementedError(msg) elif not is_object_dtype(dtype): msg = ( - "Setting {cls} dtype to anything other than object " "is not supported" + "Setting {cls} dtype to anything other than object is not supported" ).format(cls=self.__class__) raise TypeError(msg) elif copy is True: @@ -3369,7 +3359,7 @@ def insert(self, loc, item): if not isinstance(item, tuple): item = (item,) + ("",) * (self.nlevels - 1) elif len(item) != self.nlevels: - raise ValueError("Item must have length equal to number of " "levels.") + raise ValueError("Item must have length equal to number of levels.") new_levels = [] new_codes = [] diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index daf26d53aa6e2..1a1f8ae826ca7 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -99,7 +99,7 @@ def _convert_for_op(self, value): def _convert_tolerance(self, tolerance, target): tolerance = np.asarray(tolerance) if target.size != tolerance.size and tolerance.size > 1: - raise ValueError("list-like tolerance size must match " "target index size") + raise ValueError("list-like tolerance size must match target index size") if not np.issubdtype(tolerance.dtype, np.number): if tolerance.ndim > 0: raise ValueError( @@ -255,7 +255,7 @@ def _assert_safe_casting(cls, data, subarr): """ if not issubclass(data.dtype.type, np.signedinteger): if not np.array_equal(data, subarr): - raise TypeError("Unsafe NumPy casting, you must " "explicitly cast") + raise TypeError("Unsafe NumPy casting, you must explicitly cast") def _is_compatible_with_other(self, other): return super()._is_compatible_with_other(other) or all( @@ -329,7 +329,7 @@ def _assert_safe_casting(cls, data, subarr): """ if not issubclass(data.dtype.type, np.unsignedinteger): if not np.array_equal(data, subarr): - raise TypeError("Unsafe NumPy casting, you must " "explicitly cast") + raise TypeError("Unsafe NumPy casting, you must explicitly cast") def _is_compatible_with_other(self, other): return super()._is_compatible_with_other(other) or all( diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 04a858c8bfbdf..19fe1eb897f19 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -805,7 +805,7 @@ def _parsed_string_to_bounds(self, reso, parsed): def _get_string_slice(self, key): if not self.is_monotonic: - raise ValueError("Partial indexing only valid for " "ordered time series") + raise ValueError("Partial indexing only valid for ordered time series") key, parsed, reso = parse_time_string(key, self.freq) grp = resolution.Resolution.get_freq_group(reso) @@ -822,7 +822,7 @@ def _get_string_slice(self, key): def _convert_tolerance(self, tolerance, target): tolerance = DatetimeIndexOpsMixin._convert_tolerance(self, tolerance, target) if target.size != tolerance.size and tolerance.size > 1: - raise ValueError("list-like tolerance size must match " "target index size") + raise ValueError("list-like tolerance size must match target index size") return self._maybe_convert_timedelta(tolerance) def insert(self, loc, item): @@ -935,7 +935,7 @@ def item(self): """ warnings.warn( - "`item` has been deprecated and will be removed in a " "future version", + "`item` has been deprecated and will be removed in a future version", FutureWarning, stacklevel=2, ) @@ -943,10 +943,9 @@ def item(self): if len(self) == 1: return self[0] else: + # TODO: is this still necessary? # copy numpy's message here because Py26 raises an IndexError - raise ValueError( - "can only convert an array of size 1 to a " "Python scalar" - ) + raise ValueError("can only convert an array of size 1 to a Python scalar") @property def data(self): diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 413132db195f6..6f2e264f1a4d0 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -5,6 +5,7 @@ from pandas.util._decorators import Appender from pandas.core.dtypes.common import is_extension_type, is_list_like +from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes.generic import ABCMultiIndex from pandas.core.dtypes.missing import notna @@ -171,8 +172,6 @@ def lreshape(data, groups, dropna=True, label=None): for target, names in zip(keys, values): to_concat = [data[col].values for col in names] - from pandas.core.dtypes.concat import concat_compat - mdata[target] = concat_compat(to_concat) pivot_cols.append(target) diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 456f99a806cc5..374de6156c807 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -3,8 +3,8 @@ import numpy as np -import pandas._libs.algos as _algos -import pandas._libs.reshape as _reshape +import pandas._libs.algos as libalgos +import pandas._libs.reshape as libreshape from pandas._libs.sparse import IntIndex from pandas.core.dtypes.cast import maybe_promote @@ -150,7 +150,7 @@ def _make_sorted_values_labels(self): comp_index, obs_ids = get_compressed_ids(to_sort, sizes) ngroups = len(obs_ids) - indexer = _algos.groupsort_indexer(comp_index, ngroups)[0] + indexer = libalgos.groupsort_indexer(comp_index, ngroups)[0] indexer = ensure_platform_int(indexer) self.sorted_values = algos.take_nd(self.values, indexer, axis=0) @@ -239,7 +239,7 @@ def get_new_values(self): sorted_values = sorted_values.astype(name, copy=False) # fill in our values & mask - f = getattr(_reshape, "unstack_{name}".format(name=name)) + f = getattr(libreshape, "unstack_{name}".format(name=name)) f( sorted_values, mask.view("u1"), diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index d1bdbdf51e9f5..949cad6073913 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -5,6 +5,7 @@ import numpy as np +from pandas._libs import Timedelta, Timestamp from pandas._libs.lib import infer_dtype from pandas.core.dtypes.common import ( @@ -26,8 +27,6 @@ Interval, IntervalIndex, Series, - Timedelta, - Timestamp, to_datetime, to_timedelta, )
well, more of them
https://api.github.com/repos/pandas-dev/pandas/pulls/27647
2019-07-29T20:47:54Z
2019-07-30T07:20:25Z
2019-07-30T07:20:25Z
2019-07-30T14:33:22Z
BUG: Add mapping for pyqt for successful package installation
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index c7f8bb70e3461..71718928ee90a 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -187,6 +187,7 @@ Sparse Build Changes ^^^^^^^^^^^^^ +- Fixed pyqt development dependency issue because of different pyqt package name in conda and PyPI (:issue:`26838`) ExtensionArray diff --git a/environment.yml b/environment.yml index 93e8302b498a0..6d2cd701c3854 100644 --- a/environment.yml +++ b/environment.yml @@ -71,7 +71,7 @@ dependencies: - lxml # pandas.read_html - openpyxl # pandas.read_excel, DataFrame.to_excel, pandas.ExcelWriter, pandas.ExcelFile - pyarrow>=0.9.0 # pandas.read_paquet, DataFrame.to_parquet, pandas.read_feather, DataFrame.to_feather - - pyqt # pandas.read_clipbobard + - pyqt>=5.9.2 # pandas.read_clipboard - pytables>=3.4.2 # pandas.read_hdf, DataFrame.to_hdf - python-snappy # required by pyarrow - s3fs # pandas.read_csv... when using 's3://...' path diff --git a/requirements-dev.txt b/requirements-dev.txt index e49ad10bfc99d..cf11a3ee28258 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -45,7 +45,7 @@ html5lib lxml openpyxl pyarrow>=0.9.0 -pyqt +pyqt5>=5.9.2 tables>=3.4.2 python-snappy s3fs diff --git a/scripts/generate_pip_deps_from_conda.py b/scripts/generate_pip_deps_from_conda.py index ac73859b22598..6ae10c2cb07d2 100755 --- a/scripts/generate_pip_deps_from_conda.py +++ b/scripts/generate_pip_deps_from_conda.py @@ -20,7 +20,7 @@ EXCLUDE = {"python=3"} -RENAME = {"pytables": "tables"} +RENAME = {"pytables": "tables", "pyqt": "pyqt5"} def conda_package_to_pip(package):
- [ ] closes #26838 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27645
2019-07-29T19:32:54Z
2019-08-07T21:09:55Z
2019-08-07T21:09:54Z
2019-08-07T21:10:05Z
DOC: Add Pandas-Bokeh to pandas ecosystem page
diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst index b76dd3e0ff8e6..b1e3d8dc8a1ad 100644 --- a/doc/source/ecosystem.rst +++ b/doc/source/ecosystem.rst @@ -72,6 +72,17 @@ the latest web technologies. Its goal is to provide elegant, concise constructio graphics in the style of Protovis/D3, while delivering high-performance interactivity over large data to thin clients. +`Pandas-Bokeh <https://github.com/PatrikHlobil/Pandas-Bokeh>`__ provides a high level API +for Bokeh that can be loaded as a native Pandas plotting backend via + +.. code:: python + + pd.set_option("plotting.backend", "pandas_bokeh") + +It is very similar to the matplotlib plotting backend, but provides interactive +web-based charts and maps. + + `seaborn <https://seaborn.pydata.org>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This PR adds Pandas-Bokeh reference to Pandas ecosystem page. Best, Patrik
https://api.github.com/repos/pandas-dev/pandas/pulls/27644
2019-07-29T19:07:27Z
2019-07-30T08:26:28Z
2019-07-30T08:26:28Z
2019-07-30T09:00:28Z
Backport PR #27631 on branch 0.25.x (BUG: raise when wrong level name is passed to "unstack")
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index eb60272246ebb..fa9ca98f9c8d8 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -128,7 +128,7 @@ Groupby/resample/rolling Reshaping ^^^^^^^^^ -- +- A ``KeyError`` is now raised if ``.unstack()`` is called on a :class:`Series` or :class:`DataFrame` with a flat :class:`Index` passing a name which is not the correct one (:issue:`18303`) - - diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 74519391bac2f..12923fd790972 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1546,7 +1546,11 @@ def _validate_index_level(self, level): "Too many levels:" " Index has only 1 level, not %d" % (level + 1) ) elif level != self.name: - raise KeyError("Level %s must be same as name (%s)" % (level, self.name)) + raise KeyError( + "Requested level ({}) does not match index name ({})".format( + level, self.name + ) + ) def _get_level_number(self, level): self._validate_index_level(level) diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 540a06caec220..a24900543b81a 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -12,6 +12,7 @@ ensure_platform_int, is_bool_dtype, is_extension_array_dtype, + is_integer, is_integer_dtype, is_list_like, is_object_dtype, @@ -402,6 +403,10 @@ def unstack(obj, level, fill_value=None): else: level = level[0] + # Prioritize integer interpretation (GH #21677): + if not is_integer(level) and not level == "__placeholder__": + level = obj.index._get_level_number(level) + if isinstance(obj, DataFrame): if isinstance(obj.index, MultiIndex): return _unstack_frame(obj, level, fill_value=fill_value) diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index c57b2a6964f39..a6fd980faefcd 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -1083,7 +1083,7 @@ def test_reset_index_level(self): # Missing levels - for both MultiIndex and single-level Index: for idx_lev in ["A", "B"], ["A"]: - with pytest.raises(KeyError, match="Level E "): + with pytest.raises(KeyError, match=r"(L|l)evel \(?E\)?"): df.set_index(idx_lev).reset_index(level=["A", "E"]) with pytest.raises(IndexError, match="Too many levels"): df.set_index(idx_lev).reset_index(level=[0, 1, 2]) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index e75d80bec1fdf..c40a9bce9385b 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2004,7 +2004,7 @@ def test_isin_level_kwarg_bad_label_raises(self, label, indices): msg = "'Level {} not found'" else: index = index.rename("foo") - msg = r"'Level {} must be same as name \(foo\)'" + msg = r"Requested level \({}\) does not match index name \(foo\)" with pytest.raises(KeyError, match=msg.format(label)): index.isin([], level=label) diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py index 0e9aa07a4c05a..ae1a21e9b3980 100644 --- a/pandas/tests/indexes/test_common.py +++ b/pandas/tests/indexes/test_common.py @@ -35,7 +35,8 @@ def test_droplevel(self, indices): for level in "wrong", ["wrong"]: with pytest.raises( - KeyError, match=re.escape("'Level wrong must be same as name (None)'") + KeyError, + match=r"'Requested level \(wrong\) does not match index name \(None\)'", ): indices.droplevel(level) @@ -200,7 +201,7 @@ def test_unique(self, indices): with pytest.raises(IndexError, match=msg): indices.unique(level=3) - msg = r"Level wrong must be same as name \({}\)".format( + msg = r"Requested level \(wrong\) does not match index name \({}\)".format( re.escape(indices.name.__repr__()) ) with pytest.raises(KeyError, match=msg): diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py index 63baa6af7c02a..11add8d61deeb 100644 --- a/pandas/tests/series/test_alter_axes.py +++ b/pandas/tests/series/test_alter_axes.py @@ -322,9 +322,9 @@ def test_reset_index_drop_errors(self): # KeyError raised for series index when passed level name is missing s = Series(range(4)) - with pytest.raises(KeyError, match="must be same as name"): + with pytest.raises(KeyError, match="does not match index name"): s.reset_index("wrong", drop=True) - with pytest.raises(KeyError, match="must be same as name"): + with pytest.raises(KeyError, match="does not match index name"): s.reset_index("wrong") # KeyError raised for series when level to be dropped is missing diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index c97c69c323b56..dc4db6e7902a8 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -524,6 +524,22 @@ def test_stack_unstack_preserve_names(self): restacked = unstacked.stack() assert restacked.index.names == self.frame.index.names + @pytest.mark.parametrize("method", ["stack", "unstack"]) + def test_stack_unstack_wrong_level_name(self, method): + # GH 18303 - wrong level name should raise + + # A DataFrame with flat axes: + df = self.frame.loc["foo"] + + with pytest.raises(KeyError, match="does not match index name"): + getattr(df, method)("mistake") + + if method == "unstack": + # Same on a Series: + s = df.iloc[:, 0] + with pytest.raises(KeyError, match="does not match index name"): + getattr(s, method)("mistake") + def test_unstack_level_name(self): result = self.frame.unstack("second") expected = self.frame.unstack(level=1)
Backport PR #27631: BUG: raise when wrong level name is passed to "unstack"
https://api.github.com/repos/pandas-dev/pandas/pulls/27640
2019-07-29T16:56:15Z
2019-07-30T11:21:48Z
2019-07-30T11:21:48Z
2019-07-30T12:24:43Z
EA: implement+test EA.view
diff --git a/doc/source/reference/extensions.rst b/doc/source/reference/extensions.rst index 407aab4bb1f1b..04974f05164f8 100644 --- a/doc/source/reference/extensions.rst +++ b/doc/source/reference/extensions.rst @@ -45,6 +45,7 @@ objects. api.extensions.ExtensionArray.argsort api.extensions.ExtensionArray.astype api.extensions.ExtensionArray.copy + api.extensions.ExtensionArray.view api.extensions.ExtensionArray.dropna api.extensions.ExtensionArray.factorize api.extensions.ExtensionArray.fillna diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index e517be4f03a16..41d84b0ae4853 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -64,6 +64,7 @@ class ExtensionArray: shift take unique + view _concat_same_type _formatter _formatting_values @@ -147,7 +148,7 @@ class ExtensionArray: If implementing NumPy's ``__array_ufunc__`` interface, pandas expects that - 1. You defer by raising ``NotImplemented`` when any Series are present + 1. You defer by returning ``NotImplemented`` when any Series are present in `inputs`. Pandas will extract the arrays and call the ufunc again. 2. You define a ``_HANDLED_TYPES`` tuple as an attribute on the class. Pandas inspect this to determine whether the ufunc is valid for the @@ -862,6 +863,27 @@ def copy(self) -> ABCExtensionArray: """ raise AbstractMethodError(self) + def view(self, dtype=None) -> Union[ABCExtensionArray, np.ndarray]: + """ + Return a view on the array. + + Parameters + ---------- + dtype : str, np.dtype, or ExtensionDtype, optional + Default None + + Returns + ------- + ExtensionArray + """ + # NB: + # - This must return a *new* object referencing the same data, not self. + # - The only case that *must* be implemented is with dtype=None, + # giving a view with the same dtype as self. + if dtype is not None: + raise NotImplementedError(dtype) + return self[:] + # ------------------------------------------------------------------------ # Printing # ------------------------------------------------------------------------ diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index b16217d5d0a32..e56f623962fa3 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -517,19 +517,12 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike: return self._set_dtype(dtype) return np.array(self, dtype=dtype, copy=copy) - @cache_readonly - def ndim(self) -> int: - """ - Number of dimensions of the Categorical - """ - return self._codes.ndim - @cache_readonly def size(self) -> int: """ return the len of myself """ - return len(self) + return self._codes.size @cache_readonly def itemsize(self) -> int: @@ -1764,18 +1757,10 @@ def ravel(self, order="C"): ) return np.array(self) - def view(self): - """ - Return a view of myself. - - For internal compatibility with numpy arrays. - - Returns - ------- - view : Categorical - Returns `self`! - """ - return self + def view(self, dtype=None): + if dtype is not None: + raise NotImplementedError(dtype) + return self._constructor(values=self._codes, dtype=self.dtype, fastpath=True) def to_dense(self): """ diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 47b138a9e1604..695138ca07f77 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -554,18 +554,8 @@ def astype(self, dtype, copy=True): return np.asarray(self, dtype=dtype) def view(self, dtype=None): - """ - New view on this array with the same data. - - Parameters - ---------- - dtype : numpy dtype, optional - - Returns - ------- - ndarray - With the specified `dtype`. - """ + if dtype is None or dtype is self.dtype: + return type(self)(self._data, dtype=self.dtype) return self._data.view(dtype=dtype) # ------------------------------------------------------------------ diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 2b3c02bd1cade..9a1ed79a99146 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -739,18 +739,14 @@ def isna(self): return isna(self.left) @property - def nbytes(self): + def nbytes(self) -> int: return self.left.nbytes + self.right.nbytes @property - def size(self): + def size(self) -> int: # Avoid materializing self.values return self.left.size - @property - def shape(self): - return self.left.shape - def take(self, indices, allow_fill=False, fill_value=None, axis=None, **kwargs): """ Take elements from the IntervalArray. diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 39529177b9e35..e8397341a1a1d 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -241,11 +241,11 @@ def __setitem__(self, key, value): else: self._ndarray[key] = value - def __len__(self): + def __len__(self) -> int: return len(self._ndarray) @property - def nbytes(self): + def nbytes(self) -> int: return self._ndarray.nbytes def isna(self): diff --git a/pandas/core/arrays/sparse.py b/pandas/core/arrays/sparse.py index 47c7c72051150..7bd57c9c6ed32 100644 --- a/pandas/core/arrays/sparse.py +++ b/pandas/core/arrays/sparse.py @@ -839,7 +839,7 @@ def fill_value(self, value): self._dtype = SparseDtype(self.dtype.subtype, value) @property - def kind(self): + def kind(self) -> str: """ The kind of sparse index for this array. One of {'integer', 'block'}. """ @@ -854,7 +854,7 @@ def _valid_sp_values(self): mask = notna(sp_vals) return sp_vals[mask] - def __len__(self): + def __len__(self) -> int: return self.sp_index.length @property @@ -868,7 +868,7 @@ def _fill_value_matches(self, fill_value): return self.fill_value == fill_value @property - def nbytes(self): + def nbytes(self) -> int: return self.sp_values.nbytes + self.sp_index.nbytes @property @@ -886,7 +886,7 @@ def density(self): return r @property - def npoints(self): + def npoints(self) -> int: """ The number of non- ``fill_value`` points. diff --git a/pandas/tests/extension/arrow/test_bool.py b/pandas/tests/extension/arrow/test_bool.py index cc0deca765b41..9c53210b75d6b 100644 --- a/pandas/tests/extension/arrow/test_bool.py +++ b/pandas/tests/extension/arrow/test_bool.py @@ -41,6 +41,10 @@ def test_copy(self, data): # __setitem__ does not work, so we only have a smoke-test data.copy() + def test_view(self, data): + # __setitem__ does not work, so we only have a smoke-test + data.view() + class TestConstructors(BaseArrowTests, base.BaseConstructorsTests): def test_from_dtype(self, data): diff --git a/pandas/tests/extension/base/interface.py b/pandas/tests/extension/base/interface.py index dee8021f5375f..a29f6deeffae6 100644 --- a/pandas/tests/extension/base/interface.py +++ b/pandas/tests/extension/base/interface.py @@ -75,3 +75,18 @@ def test_copy(self, data): data[1] = data[0] assert result[1] != result[0] + + def test_view(self, data): + # view with no dtype should return a shallow copy, *not* the same + # object + assert data[1] != data[0] + + result = data.view() + assert result is not data + assert type(result) == type(data) + + result[1] = result[0] + assert data[1] == data[0] + + # check specifically that the `dtype` kwarg is accepted + data.view(dtype=None) diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index c28ff956a33a4..a1988744d76a1 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -137,11 +137,11 @@ def __setitem__(self, key, value): value = decimal.Decimal(value) self._data[key] = value - def __len__(self): + def __len__(self) -> int: return len(self._data) @property - def nbytes(self): + def nbytes(self) -> int: n = len(self) if n: return n * sys.getsizeof(self[0]) diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 21c4ac8f055a2..b64ddbd6ac84d 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -80,6 +80,9 @@ def __getitem__(self, item): elif isinstance(item, abc.Iterable): # fancy indexing return type(self)([self.data[i] for i in item]) + elif isinstance(item, slice) and item == slice(None): + # Make sure we get a view + return type(self)(self.data) else: # slice return type(self)(self.data[item]) @@ -103,11 +106,11 @@ def __setitem__(self, key, value): assert isinstance(v, self.dtype.type) self.data[k] = v - def __len__(self): + def __len__(self) -> int: return len(self.data) @property - def nbytes(self): + def nbytes(self) -> int: return sys.getsizeof(self.data) def isna(self): diff --git a/pandas/tests/extension/test_interval.py b/pandas/tests/extension/test_interval.py index 1aab71286b4a6..4fdcf930d224f 100644 --- a/pandas/tests/extension/test_interval.py +++ b/pandas/tests/extension/test_interval.py @@ -95,7 +95,10 @@ class TestGrouping(BaseInterval, base.BaseGroupbyTests): class TestInterface(BaseInterval, base.BaseInterfaceTests): - pass + def test_view(self, data): + # __setitem__ incorrectly makes a copy (GH#27147), so we only + # have a smoke-test + data.view() class TestReduce(base.BaseNoReduceTests): diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index 84d59902d2aa7..6ebe71e173ec2 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -103,6 +103,10 @@ def test_copy(self, data): # __setitem__ does not work, so we only have a smoke-test data.copy() + def test_view(self, data): + # __setitem__ does not work, so we only have a smoke-test + data.view() + class TestConstructors(BaseSparseTests, base.BaseConstructorsTests): pass
Broken off from #27142, plus some type annotations
https://api.github.com/repos/pandas-dev/pandas/pulls/27633
2019-07-29T02:44:22Z
2019-08-09T08:00:54Z
2019-08-09T08:00:53Z
2019-08-09T14:34:27Z
CLN: Assorted cleanups
diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py index f84033e9c3c90..2d4ded9e2e6ba 100644 --- a/pandas/core/accessor.py +++ b/pandas/core/accessor.py @@ -51,7 +51,7 @@ class PandasDelegate: """ def _delegate_property_get(self, name, *args, **kwargs): - raise TypeError("You cannot access the " "property {name}".format(name=name)) + raise TypeError("You cannot access the property {name}".format(name=name)) def _delegate_property_set(self, name, value, *args, **kwargs): raise TypeError("The property {name} cannot be set".format(name=name)) @@ -271,8 +271,7 @@ def plot(self): @Appender( _doc % dict( - klass="DataFrame", - others=("register_series_accessor, " "register_index_accessor"), + klass="DataFrame", others=("register_series_accessor, register_index_accessor") ) ) def register_dataframe_accessor(name): @@ -284,8 +283,7 @@ def register_dataframe_accessor(name): @Appender( _doc % dict( - klass="Series", - others=("register_dataframe_accessor, " "register_index_accessor"), + klass="Series", others=("register_dataframe_accessor, register_index_accessor") ) ) def register_series_accessor(name): @@ -297,8 +295,7 @@ def register_series_accessor(name): @Appender( _doc % dict( - klass="Index", - others=("register_dataframe_accessor, " "register_series_accessor"), + klass="Index", others=("register_dataframe_accessor, register_series_accessor") ) ) def register_index_accessor(name): diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index ee796f9896b52..e517be4f03a16 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -14,14 +14,17 @@ from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError from pandas.util._decorators import Appender, Substitution +from pandas.util._validators import validate_fillna_kwargs -from pandas.core.dtypes.common import is_list_like +from pandas.core.dtypes.common import is_array_like, is_list_like from pandas.core.dtypes.dtypes import ExtensionDtype from pandas.core.dtypes.generic import ABCExtensionArray, ABCIndexClass, ABCSeries from pandas.core.dtypes.missing import isna from pandas._typing import ArrayLike from pandas.core import ops +from pandas.core.algorithms import _factorize_array, unique +from pandas.core.missing import backfill_1d, pad_1d from pandas.core.sorting import nargsort _not_implemented_message = "{} does not implement {}." @@ -484,10 +487,6 @@ def fillna(self, value=None, method=None, limit=None): ------- filled : ExtensionArray with NA/NaN filled """ - from pandas.api.types import is_array_like - from pandas.util._validators import validate_fillna_kwargs - from pandas.core.missing import pad_1d, backfill_1d - value, method = validate_fillna_kwargs(value, method) mask = self.isna() @@ -584,8 +583,6 @@ def unique(self): ------- uniques : ExtensionArray """ - from pandas import unique - uniques = unique(self.astype(object)) return self._from_sequence(uniques, dtype=self.dtype) @@ -700,8 +697,6 @@ def factorize(self, na_sentinel: int = -1) -> Tuple[np.ndarray, ABCExtensionArra # original ExtensionArray. # 2. ExtensionArray.factorize. # Complete control over factorization. - from pandas.core.algorithms import _factorize_array - arr, na_value = self._values_for_factorize() labels, uniques = _factorize_array( @@ -874,7 +869,7 @@ def copy(self) -> ABCExtensionArray: def __repr__(self): from pandas.io.formats.printing import format_object_summary - template = "{class_name}" "{data}\n" "Length: {length}, dtype: {dtype}" + template = "{class_name}{data}\nLength: {length}, dtype: {dtype}" # the short repr has no trailing newline, while the truncated # repr does. So we include a newline in our template, and strip # any trailing newlines from format_object_summary diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index c22f7e0429433..b16217d5d0a32 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -93,13 +93,13 @@ def f(self, other): if not self.ordered: if op in ["__lt__", "__gt__", "__le__", "__ge__"]: raise TypeError( - "Unordered Categoricals can only compare " "equality or not" + "Unordered Categoricals can only compare equality or not" ) if isinstance(other, Categorical): # Two Categoricals can only be be compared if the categories are # the same (maybe up to ordering, depending on ordered) - msg = "Categoricals can only be compared if " "'categories' are the same." + msg = "Categoricals can only be compared if 'categories' are the same." if len(self.categories) != len(other.categories): raise TypeError(msg + " Categories are different lengths") elif self.ordered and not (self.categories == other.categories).all(): @@ -109,7 +109,7 @@ def f(self, other): if not (self.ordered == other.ordered): raise TypeError( - "Categoricals can only be compared if " "'ordered' is the same" + "Categoricals can only be compared if 'ordered' is the same" ) if not self.ordered and not self.categories.equals(other.categories): # both unordered and different order @@ -387,7 +387,7 @@ def __init__( # FIXME raise NotImplementedError( - "> 1 ndim Categorical are not " "supported at this time" + "> 1 ndim Categorical are not supported at this time" ) # we're inferring from values @@ -694,7 +694,7 @@ def from_codes(cls, codes, categories=None, ordered=None, dtype=None): raise ValueError(msg) if len(codes) and (codes.max() >= len(dtype.categories) or codes.min() < -1): - raise ValueError("codes need to be between -1 and " "len(categories)-1") + raise ValueError("codes need to be between -1 and len(categories)-1") return cls(codes, dtype=dtype, fastpath=True) @@ -1019,7 +1019,7 @@ def reorder_categories(self, new_categories, ordered=None, inplace=False): inplace = validate_bool_kwarg(inplace, "inplace") if set(self.dtype.categories) != set(new_categories): raise ValueError( - "items in new_categories are not the same as in " "old categories" + "items in new_categories are not the same as in old categories" ) return self.set_categories(new_categories, ordered=ordered, inplace=inplace) @@ -1481,7 +1481,7 @@ def put(self, *args, **kwargs): """ Replace specific elements in the Categorical with given values. """ - raise NotImplementedError(("'put' is not yet implemented " "for Categorical")) + raise NotImplementedError(("'put' is not yet implemented for Categorical")) def dropna(self): """ @@ -1827,7 +1827,7 @@ def fillna(self, value=None, method=None, limit=None): value = np.nan if limit is not None: raise NotImplementedError( - "specifying a limit for fillna has not " "been implemented yet" + "specifying a limit for fillna has not been implemented yet" ) codes = self._codes @@ -1963,7 +1963,7 @@ def take_nd(self, indexer, allow_fill=None, fill_value=None): if fill_value in self.categories: fill_value = self.categories.get_loc(fill_value) else: - msg = "'fill_value' ('{}') is not in this Categorical's " "categories." + msg = "'fill_value' ('{}') is not in this Categorical's categories." raise TypeError(msg.format(fill_value)) codes = take(self._codes, indexer, allow_fill=allow_fill, fill_value=fill_value) @@ -2168,12 +2168,12 @@ def __setitem__(self, key, value): # in a 2-d case be passd (slice(None),....) if len(key) == 2: if not com.is_null_slice(key[0]): - raise AssertionError("invalid slicing for a 1-ndim " "categorical") + raise AssertionError("invalid slicing for a 1-ndim categorical") key = key[1] elif len(key) == 1: key = key[0] else: - raise AssertionError("invalid slicing for a 1-ndim " "categorical") + raise AssertionError("invalid slicing for a 1-ndim categorical") # slicing in Series or Categorical elif isinstance(key, slice): @@ -2561,9 +2561,7 @@ def __init__(self, data): @staticmethod def _validate(data): if not is_categorical_dtype(data.dtype): - raise AttributeError( - "Can only use .cat accessor with a " "'category' dtype" - ) + raise AttributeError("Can only use .cat accessor with a 'category' dtype") def _delegate_property_get(self, name): return getattr(self._parent, name) @@ -2607,7 +2605,7 @@ def name(self): # need to be updated. `name` will need to be removed from # `ok_for_cat`. warn( - "`Series.cat.name` has been deprecated. Use `Series.name` " "instead.", + "`Series.cat.name` has been deprecated. Use `Series.name` instead.", FutureWarning, stacklevel=2, ) @@ -2619,7 +2617,7 @@ def index(self): # need to be updated. `index` will need to be removed from # ok_for_cat`. warn( - "`Series.cat.index` has been deprecated. Use `Series.index` " "instead.", + "`Series.cat.index` has been deprecated. Use `Series.index` instead.", FutureWarning, stacklevel=2, ) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 932d96a37c04c..f86b307e5ede3 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1097,7 +1097,7 @@ def _sub_period_array(self, other): ) if len(self) != len(other): - raise ValueError("cannot subtract arrays/indices of " "unequal length") + raise ValueError("cannot subtract arrays/indices of unequal length") if self.freq != other.freq: msg = DIFFERENT_FREQ.format( cls=type(self).__name__, own_freq=self.freqstr, other_freq=other.freqstr diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 5b540dcce53c8..8e76ad8a375f7 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -478,7 +478,7 @@ def _generate_range( periods = dtl.validate_periods(periods) if freq is None and any(x is None for x in [periods, start, end]): - raise ValueError("Must provide freq argument if no data is " "supplied") + raise ValueError("Must provide freq argument if no data is supplied") if com.count_not_none(start, end, periods, freq) != 3: raise ValueError( @@ -496,7 +496,7 @@ def _generate_range( if start is None and end is None: if closed is not None: raise ValueError( - "Closed has to be None if not both of start" "and end are defined" + "Closed has to be None if not both of startand end are defined" ) if start is NaT or end is NaT: raise ValueError("Neither `start` nor `end` can be NaT") @@ -786,11 +786,11 @@ def _assert_tzawareness_compat(self, other): elif self.tz is None: if other_tz is not None: raise TypeError( - "Cannot compare tz-naive and tz-aware " "datetime-like objects." + "Cannot compare tz-naive and tz-aware datetime-like objects." ) elif other_tz is None: raise TypeError( - "Cannot compare tz-naive and tz-aware " "datetime-like objects" + "Cannot compare tz-naive and tz-aware datetime-like objects" ) # ----------------------------------------------------------------- @@ -833,7 +833,7 @@ def _add_offset(self, offset): except NotImplementedError: warnings.warn( - "Non-vectorized DateOffset being applied to Series " "or DatetimeIndex", + "Non-vectorized DateOffset being applied to Series or DatetimeIndex", PerformanceWarning, ) result = self.astype("O") + offset @@ -851,7 +851,7 @@ def _sub_datetimelike_scalar(self, other): if not self._has_same_tz(other): # require tz compat raise TypeError( - "Timestamp subtraction must have the same " "timezones or no timezones" + "Timestamp subtraction must have the same timezones or no timezones" ) i8 = self.asi8 @@ -957,7 +957,7 @@ def tz_convert(self, tz): if self.tz is None: # tz naive, use tz_localize raise TypeError( - "Cannot convert tz-naive timestamps, use " "tz_localize to localize" + "Cannot convert tz-naive timestamps, use tz_localize to localize" ) # No conversion since timestamps are all UTC to begin with @@ -1125,7 +1125,7 @@ def tz_localize(self, tz, ambiguous="raise", nonexistent="raise", errors=None): nonexistent = "raise" else: raise ValueError( - "The errors argument must be either 'coerce' " "or 'raise'." + "The errors argument must be either 'coerce' or 'raise'." ) nonexistent_options = ("raise", "NaT", "shift_forward", "shift_backward") @@ -1274,7 +1274,7 @@ def to_period(self, freq=None): if freq is None: raise ValueError( - "You must pass a freq argument as " "current index has none." + "You must pass a freq argument as current index has none." ) freq = get_period_alias(freq) @@ -2047,7 +2047,7 @@ def maybe_convert_dtype(data, copy): # Note: without explicitly raising here, PeriodIndex # test_setops.test_join_does_not_recur fails raise TypeError( - "Passing PeriodDtype data is invalid. " "Use `data.to_timestamp()` instead" + "Passing PeriodDtype data is invalid. Use `data.to_timestamp()` instead" ) elif is_categorical_dtype(data): @@ -2177,7 +2177,7 @@ def validate_tz_from_dtype(dtype, tz): dtz = getattr(dtype, "tz", None) if dtz is not None: if tz is not None and not timezones.tz_compare(tz, dtz): - raise ValueError("cannot supply both a tz and a dtype" " with a tz") + raise ValueError("cannot supply both a tz and a dtype with a tz") tz = dtz if tz is not None and is_datetime64_dtype(dtype): @@ -2216,7 +2216,7 @@ def _infer_tz_from_endpoints(start, end, tz): inferred_tz = timezones.infer_tzinfo(start, end) except Exception: raise TypeError( - "Start and end cannot both be tz-aware with " "different timezones" + "Start and end cannot both be tz-aware with different timezones" ) inferred_tz = timezones.maybe_get_tz(inferred_tz) @@ -2224,7 +2224,7 @@ def _infer_tz_from_endpoints(start, end, tz): if tz is not None and inferred_tz is not None: if not timezones.tz_compare(inferred_tz, tz): - raise AssertionError("Inferred time zone not equal to passed " "time zone") + raise AssertionError("Inferred time zone not equal to passed time zone") elif inferred_tz is not None: tz = inferred_tz diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 2a0d2c8770063..2b3c02bd1cade 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -33,6 +33,7 @@ ) from pandas.core.dtypes.missing import isna, notna +from pandas.core.algorithms import take, value_counts from pandas.core.arrays.base import ExtensionArray, _extension_array_shared_docs from pandas.core.arrays.categorical import Categorical import pandas.core.common as com @@ -206,7 +207,7 @@ def _simple_new( left = left.astype(right.dtype) if type(left) != type(right): - msg = "must not have differing left [{ltype}] and right " "[{rtype}] types" + msg = "must not have differing left [{ltype}] and right [{rtype}] types" raise ValueError( msg.format(ltype=type(left).__name__, rtype=type(right).__name__) ) @@ -458,13 +459,13 @@ def from_tuples(cls, data, closed="right", copy=False, dtype=None): lhs, rhs = d except ValueError: msg = ( - "{name}.from_tuples requires tuples of " "length 2, got {tpl}" + "{name}.from_tuples requires tuples of length 2, got {tpl}" ).format(name=name, tpl=d) raise ValueError(msg) except TypeError: - msg = ( - "{name}.from_tuples received an invalid " "item, {tpl}" - ).format(name=name, tpl=d) + msg = ("{name}.from_tuples received an invalid item, {tpl}").format( + name=name, tpl=d + ) raise TypeError(msg) left.append(lhs) right.append(rhs) @@ -590,7 +591,7 @@ def fillna(self, value=None, method=None, limit=None): filled : IntervalArray with NA/NaN filled """ if method is not None: - raise TypeError("Filling by method is not supported for " "IntervalArray.") + raise TypeError("Filling by method is not supported for IntervalArray.") if limit is not None: raise TypeError("limit is not supported for IntervalArray.") @@ -796,8 +797,6 @@ def take(self, indices, allow_fill=False, fill_value=None, axis=None, **kwargs): When `indices` contains negative values other than ``-1`` and `allow_fill` is True. """ - from pandas.core.algorithms import take - nv.validate_take(tuple(), kwargs) fill_left = fill_right = fill_value @@ -843,8 +842,6 @@ def value_counts(self, dropna=True): Series.value_counts """ # TODO: implement this is a non-naive way! - from pandas.core.algorithms import value_counts - return value_counts(np.asarray(self), dropna=dropna) # Formatting diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index b0336c46d1953..c290391278def 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -286,13 +286,13 @@ def _generate_range(cls, start, end, periods, freq, fields): if start is not None or end is not None: if field_count > 0: raise ValueError( - "Can either instantiate from fields " "or endpoints, but not both" + "Can either instantiate from fields or endpoints, but not both" ) subarr, freq = _get_ordinal_range(start, end, periods, freq) elif field_count > 0: subarr, freq = _range_from_fields(freq=freq, **fields) else: - raise ValueError("Not enough parameters to construct " "Period range") + raise ValueError("Not enough parameters to construct Period range") return subarr, freq @@ -839,7 +839,7 @@ def period_array( dtype = None if is_float_dtype(data) and len(data) > 0: - raise TypeError("PeriodIndex does not allow " "floating point in construction") + raise TypeError("PeriodIndex does not allow floating point in construction") data = ensure_object(data) @@ -875,7 +875,7 @@ def validate_dtype_freq(dtype, freq): if freq is None: freq = dtype.freq elif freq != dtype.freq: - raise IncompatibleFrequency("specified freq and dtype " "are different") + raise IncompatibleFrequency("specified freq and dtype are different") return freq diff --git a/pandas/core/arrays/sparse.py b/pandas/core/arrays/sparse.py index 048f6c6f5c680..47c7c72051150 100644 --- a/pandas/core/arrays/sparse.py +++ b/pandas/core/arrays/sparse.py @@ -121,7 +121,7 @@ def __init__(self, dtype: Dtype = np.float64, fill_value: Any = None) -> None: if not is_scalar(fill_value): raise ValueError( - "fill_value must be a scalar. Got {} " "instead".format(fill_value) + "fill_value must be a scalar. Got {} instead".format(fill_value) ) self._dtype = dtype self._fill_value = fill_value @@ -1139,7 +1139,7 @@ def _get_val_at(self, loc): def take(self, indices, allow_fill=False, fill_value=None): if is_scalar(indices): raise ValueError( - "'indices' must be an array, not a " "scalar '{}'.".format(indices) + "'indices' must be an array, not a scalar '{}'.".format(indices) ) indices = np.asarray(indices, dtype=np.int32) @@ -1176,7 +1176,7 @@ def _take_with_fill(self, indices, fill_value=None): taken.fill(fill_value) return taken else: - raise IndexError("cannot do a non-empty take from an empty " "axes.") + raise IndexError("cannot do a non-empty take from an empty axes.") sp_indexer = self.sp_index.lookup_array(indices) @@ -1226,7 +1226,7 @@ def _take_without_fill(self, indices): if (indices.max() >= n) or (indices.min() < -n): if n == 0: - raise IndexError("cannot do a non-empty take from an " "empty axes.") + raise IndexError("cannot do a non-empty take from an empty axes.") else: raise IndexError("out of bounds value in 'indices'.") diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 9d622d92e0979..dd0b9a79c6dca 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -290,7 +290,7 @@ def _generate_range(cls, start, end, periods, freq, closed=None): periods = dtl.validate_periods(periods) if freq is None and any(x is None for x in [periods, start, end]): - raise ValueError("Must provide freq argument if no data is " "supplied") + raise ValueError("Must provide freq argument if no data is supplied") if com.count_not_none(start, end, periods, freq) != 3: raise ValueError( @@ -307,7 +307,7 @@ def _generate_range(cls, start, end, periods, freq, closed=None): if start is None and end is None: if closed is not None: raise ValueError( - "Closed has to be None if not both of start" "and end are defined" + "Closed has to be None if not both of startand end are defined" ) left_closed, right_closed = dtl.validate_endpoints(closed) @@ -862,17 +862,17 @@ def to_pytimedelta(self): seconds = _field_accessor( "seconds", "seconds", - "Number of seconds (>= 0 and less than 1 day) " "for each element.", + "Number of seconds (>= 0 and less than 1 day) for each element.", ) microseconds = _field_accessor( "microseconds", "microseconds", - "Number of microseconds (>= 0 and less " "than 1 second) for each element.", + "Number of microseconds (>= 0 and less than 1 second) for each element.", ) nanoseconds = _field_accessor( "nanoseconds", "nanoseconds", - "Number of nanoseconds (>= 0 and less " "than 1 microsecond) for each element.", + "Number of nanoseconds (>= 0 and less than 1 microsecond) for each element.", ) @property @@ -1131,7 +1131,7 @@ def _generate_regular_range(start, end, periods, offset): b = e - periods * stride else: raise ValueError( - "at least 'start' or 'end' should be specified " "if a 'period' is given." + "at least 'start' or 'end' should be specified if a 'period' is given." ) data = np.arange(b, e, stride, dtype=np.int64) diff --git a/pandas/core/base.py b/pandas/core/base.py index ce993a513f569..cfa8d25210129 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -4,7 +4,7 @@ import builtins from collections import OrderedDict import textwrap -from typing import Optional +from typing import Dict, Optional import warnings import numpy as np @@ -37,7 +37,7 @@ from pandas.core.arrays import ExtensionArray import pandas.core.nanops as nanops -_shared_docs = dict() +_shared_docs = dict() # type: Dict[str, str] _indexops_doc_kwargs = dict( klass="IndexOpsMixin", inplace="", @@ -437,7 +437,7 @@ def _agg_1dim(name, how, subset=None): colg = self._gotitem(name, ndim=1, subset=subset) if colg.ndim != 1: raise SpecificationError( - "nested dictionary is ambiguous " "in aggregation" + "nested dictionary is ambiguous in aggregation" ) return colg.aggregate(how, _level=(_level or 0) + 1) @@ -634,9 +634,7 @@ def _aggregate_multiple_funcs(self, arg, _level, _axis): result = Series(results, index=keys, name=self.name) if is_nested_object(result): - raise ValueError( - "cannot combine transform and " "aggregation operations" - ) + raise ValueError("cannot combine transform and aggregation operations") return result def _shallow_copy(self, obj=None, obj_type=None, **kwargs): @@ -735,7 +733,7 @@ def item(self): The first element of %(klass)s. """ warnings.warn( - "`item` has been deprecated and will be removed in a " "future version", + "`item` has been deprecated and will be removed in a future version", FutureWarning, stacklevel=2, ) diff --git a/pandas/core/common.py b/pandas/core/common.py index f9a19291b8ad9..c12bfecc46518 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -443,7 +443,7 @@ def random_state(state=None): return np.random else: raise ValueError( - "random_state must be an integer, a numpy " "RandomState, or None" + "random_state must be an integer, a numpy RandomState, or None" ) diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index 456ecf4b2594f..8614230c4811f 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -333,7 +333,7 @@ def eval( " if all expressions contain an assignment" ) elif inplace: - raise ValueError("Cannot operate inplace " "if there is no assignment") + raise ValueError("Cannot operate inplace if there is no assignment") # assign if needed assigner = parsed_expr.assigner diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index 772fb547567e3..e10d189bc3c6f 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -296,7 +296,7 @@ def _node_not_implemented(node_name, cls): def f(self, *args, **kwargs): raise NotImplementedError( - "{name!r} nodes are not " "implemented".format(name=node_name) + "{name!r} nodes are not implemented".format(name=node_name) ) return f @@ -433,7 +433,7 @@ def visit(self, node, **kwargs): from keyword import iskeyword if any(iskeyword(x) for x in clean.split()): - e.msg = "Python keyword not valid identifier" " in numexpr query" + e.msg = "Python keyword not valid identifier in numexpr query" raise e method = "visit_" + node.__class__.__name__ @@ -642,9 +642,7 @@ def visit_Assign(self, node, **kwargs): if len(node.targets) != 1: raise SyntaxError("can only assign a single expression") if not isinstance(node.targets[0], ast.Name): - raise SyntaxError( - "left hand side of an assignment must be a " "single name" - ) + raise SyntaxError("left hand side of an assignment must be a single name") if self.env.target is None: raise ValueError("cannot assign without a target object") @@ -656,7 +654,7 @@ def visit_Assign(self, node, **kwargs): self.assigner = getattr(assigner, "name", assigner) if self.assigner is None: raise SyntaxError( - "left hand side of an assignment must be a " "single resolvable name" + "left hand side of an assignment must be a single resolvable name" ) return self.visit(node.value, **kwargs) diff --git a/pandas/core/computation/expressions.py b/pandas/core/computation/expressions.py index ea61467080291..d9dc194d484ae 100644 --- a/pandas/core/computation/expressions.py +++ b/pandas/core/computation/expressions.py @@ -197,7 +197,7 @@ def _bool_arith_check( if op_str in not_allowed: raise NotImplementedError( - "operator {op!r} not implemented for " "bool dtypes".format(op=op_str) + "operator {op!r} not implemented for bool dtypes".format(op=op_str) ) return True diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index 59ed7143e6cd2..870acc3cc9956 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -97,7 +97,7 @@ def _resolve_name(self): if hasattr(res, "ndim") and res.ndim > 2: raise NotImplementedError( - "N-dimensional objects, where N > 2," " are not supported with eval" + "N-dimensional objects, where N > 2, are not supported with eval" ) return res diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index 8ba01670bd879..60cf35163bcf4 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -306,7 +306,7 @@ def invert(self): # self.condition = "~(%s)" % self.condition # return self raise NotImplementedError( - "cannot use an invert condition when " "passing to numexpr" + "cannot use an invert condition when passing to numexpr" ) def format(self): @@ -474,9 +474,7 @@ def _validate_where(w): """ if not (isinstance(w, (Expr, str)) or is_list_like(w)): - raise TypeError( - "where must be passed as a string, Expr, " "or list-like of Exprs" - ) + raise TypeError("where must be passed as a string, Expr, or list-like of Exprs") return w diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 33066ccef0687..5980e3d133374 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1173,9 +1173,7 @@ def from_dict(cls, data, orient="columns", dtype=None, columns=None): data, index = list(data.values()), list(data.keys()) elif orient == "columns": if columns is not None: - raise ValueError( - "cannot use columns parameter with " "orient='columns'" - ) + raise ValueError("cannot use columns parameter with orient='columns'") else: # pragma: no cover raise ValueError("only recognize index or columns for orient") @@ -1327,7 +1325,7 @@ def to_dict(self, orient="dict", into=dict): """ if not self.columns.is_unique: warnings.warn( - "DataFrame columns are not unique, some " "columns will be omitted.", + "DataFrame columns are not unique, some columns will be omitted.", UserWarning, stacklevel=2, ) @@ -1808,9 +1806,9 @@ def to_records( formats.append(dtype_mapping) else: element = "row" if i < index_len else "column" - msg = ( - "Invalid dtype {dtype} specified for " "{element} {name}" - ).format(dtype=dtype_mapping, element=element, name=name) + msg = ("Invalid dtype {dtype} specified for {element} {name}").format( + dtype=dtype_mapping, element=element, name=name + ) raise ValueError(msg) return np.rec.fromarrays(arrays, dtype={"names": names, "formats": formats}) @@ -2086,9 +2084,7 @@ def to_stata( raise ValueError("Only formats 114 and 117 supported.") if version == 114: if convert_strl is not None: - raise ValueError( - "strl support is only available when using " "format 117" - ) + raise ValueError("strl support is only available when using format 117") from pandas.io.stata import StataWriter as statawriter else: from pandas.io.stata import StataWriter117 as statawriter @@ -2502,7 +2498,7 @@ def _sizeof_fmt(num, size_qualifier): # returns size in human readable format for x in ["bytes", "KB", "MB", "GB", "TB"]: if num < 1024.0: - return "{num:3.1f}{size_q} " "{x}".format( + return "{num:3.1f}{size_q} {x}".format( num=num, size_q=size_qualifier, x=x ) num /= 1024.0 @@ -2887,7 +2883,7 @@ def _getitem_bool_array(self, key): # with all other indexing behavior if isinstance(key, Series) and not key.index.equals(self.index): warnings.warn( - "Boolean Series key will be reindexed to match " "DataFrame index.", + "Boolean Series key will be reindexed to match DataFrame index.", UserWarning, stacklevel=3, ) @@ -3461,7 +3457,7 @@ def _get_info_slice(obj, indexer): selection = tuple(map(frozenset, (include, exclude))) if not any(selection): - raise ValueError("at least one of include or exclude must be " "nonempty") + raise ValueError("at least one of include or exclude must be nonempty") # convert the myriad valid dtypes object to a single representation include, exclude = map( @@ -3654,7 +3650,7 @@ def reindexer(value): # other raise TypeError( - "incompatible index of inserted column " "with frame index" + "incompatible index of inserted column with frame index" ) return value @@ -4337,7 +4333,7 @@ def set_index( found = col in self.columns except TypeError: raise TypeError( - err_msg + " Received column of " "type {}".format(type(col)) + err_msg + " Received column of type {}".format(type(col)) ) else: if not found: @@ -5714,9 +5710,7 @@ def update( if join != "left": # pragma: no cover raise NotImplementedError("Only left join is supported") if errors not in ["ignore", "raise"]: - raise ValueError( - "The parameter errors must be either " "'ignore' or 'raise'" - ) + raise ValueError("The parameter errors must be either 'ignore' or 'raise'") if not isinstance(other, DataFrame): other = DataFrame(other) @@ -7213,7 +7207,7 @@ def _join_compat( else: if on is not None: raise ValueError( - "Joining multiple DataFrames only supported" " for joining on index" + "Joining multiple DataFrames only supported for joining on index" ) frames = [self] + list(other) @@ -7374,7 +7368,7 @@ def _series_round(s, decimals): # Dispatch to Series.round new_cols = [_series_round(v, decimals) for _, v in self.items()] else: - raise TypeError("decimals must be an integer, a dict-like or a " "Series") + raise TypeError("decimals must be an integer, a dict-like or a Series") if len(new_cols) > 0: return self._constructor( @@ -8376,11 +8370,11 @@ def isin(self, values): ) elif isinstance(values, Series): if not values.index.is_unique: - raise ValueError("cannot compute isin with " "a duplicate axis.") + raise ValueError("cannot compute isin with a duplicate axis.") return self.eq(values.reindex_like(self), axis="index") elif isinstance(values, DataFrame): if not (values.columns.is_unique and values.index.is_unique): - raise ValueError("cannot compute isin with " "a duplicate axis.") + raise ValueError("cannot compute isin with a duplicate axis.") return self.eq(values.reindex_like(self)) else: if not is_list_like(values): diff --git a/pandas/core/generic.py b/pandas/core/generic.py index df97d34ee349a..821c35e0cce2f 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5,6 +5,7 @@ import json import operator import pickle +import re from textwrap import dedent from typing import Callable, Dict, FrozenSet, List, Optional, Set import warnings @@ -380,7 +381,7 @@ def _construct_axes_from_arguments( kwargs[a] = args.pop(0) except IndexError: if require_all: - raise TypeError("not enough/duplicate arguments " "specified!") + raise TypeError("not enough/duplicate arguments specified!") axes = {a: kwargs.pop(a, sentinel) for a in self._AXIS_ORDERS} return axes, kwargs @@ -1297,7 +1298,7 @@ class name if non_mapper: return self._set_axis_name(mapper, axis=axis, inplace=inplace) else: - raise ValueError("Use `.rename` to alter labels " "with a mapper.") + raise ValueError("Use `.rename` to alter labels with a mapper.") else: # Use new behavior. Means that index and/or columns # is specified @@ -3869,16 +3870,14 @@ def drop( if labels is not None: if index is not None or columns is not None: - raise ValueError( - "Cannot specify both 'labels' and " "'index'/'columns'" - ) + raise ValueError("Cannot specify both 'labels' and 'index'/'columns'") axis_name = self._get_axis_name(axis) axes = {axis_name: labels} elif index is not None or columns is not None: axes, _ = self._construct_axes_from_arguments((index, columns), {}) else: raise ValueError( - "Need to specify at least one of 'labels', " "'index' or 'columns'" + "Need to specify at least one of 'labels', 'index' or 'columns'" ) obj = self @@ -4615,8 +4614,6 @@ def filter(self, items=None, like=None, regex=None, axis=None): one two three rabbit 4 5 6 """ - import re - nkw = com.count_not_none(items, like, regex) if nkw > 1: raise TypeError( @@ -4886,7 +4883,7 @@ def sample( weights = self[weights] except KeyError: raise KeyError( - "String passed to weights not a " "valid column" + "String passed to weights not a valid column" ) else: raise ValueError( @@ -4904,14 +4901,14 @@ def sample( if len(weights) != axis_length: raise ValueError( - "Weights and axis to be sampled must be of " "same length" + "Weights and axis to be sampled must be of same length" ) if (weights == np.inf).any() or (weights == -np.inf).any(): raise ValueError("weight vector may not include `inf` values") if (weights < 0).any(): - raise ValueError("weight vector many not include negative " "values") + raise ValueError("weight vector many not include negative values") # If has nan, set to zero. weights = weights.fillna(0) @@ -4933,12 +4930,12 @@ def sample( elif n is None and frac is not None: n = int(round(frac * axis_length)) elif n is not None and frac is not None: - raise ValueError("Please enter a value for `frac` OR `n`, not " "both") + raise ValueError("Please enter a value for `frac` OR `n`, not both") # Check for negative sizes if n < 0: raise ValueError( - "A negative number of rows requested. Please " "provide positive value." + "A negative number of rows requested. Please provide positive value." ) locs = rs.choice(axis_length, size=n, replace=replace, p=weights) @@ -5565,7 +5562,7 @@ def get_ftype_counts(self): dtype: int64 """ warnings.warn( - "get_ftype_counts is deprecated and will " "be removed in a future version", + "get_ftype_counts is deprecated and will be removed in a future version", FutureWarning, stacklevel=2, ) @@ -5686,7 +5683,7 @@ def as_blocks(self, copy=True): values : a dict of dtype -> Constructor Types """ warnings.warn( - "as_blocks is deprecated and will " "be removed in a future version", + "as_blocks is deprecated and will be removed in a future version", FutureWarning, stacklevel=2, ) @@ -6598,9 +6595,7 @@ def replace( ): inplace = validate_bool_kwarg(inplace, "inplace") if not is_bool(regex) and to_replace is not None: - raise AssertionError( - "'to_replace' must be 'None' if 'regex' is " "not a bool" - ) + raise AssertionError("'to_replace' must be 'None' if 'regex' is not a bool") self._consolidate_inplace() @@ -6698,7 +6693,7 @@ def replace( convert=convert, ) else: - raise TypeError("value argument must be scalar, dict, or " "Series") + raise TypeError("value argument must be scalar, dict, or Series") elif is_list_like(to_replace): # [NA, ''] -> [0, 'missing'] if is_list_like(value): @@ -6984,7 +6979,7 @@ def interpolate( if isinstance(_maybe_transposed_self.index, MultiIndex) and method != "linear": raise ValueError( - "Only `method=linear` interpolation is supported " "on MultiIndexes." + "Only `method=linear` interpolation is supported on MultiIndexes." ) if _maybe_transposed_self._data.get_dtype_counts().get("object") == len( @@ -7146,9 +7141,7 @@ def asof(self, where, subset=None): 2018-02-27 09:04:30 40.0 NaN """ if isinstance(where, str): - from pandas import to_datetime - - where = to_datetime(where) + where = Timestamp(where) if not self.index.is_monotonic: raise ValueError("asof requires a sorted index") @@ -7598,7 +7591,7 @@ def clip_upper(self, threshold, axis=None, inplace=False): dtype: int64 """ warnings.warn( - "clip_upper(threshold) is deprecated, " "use clip(upper=threshold) instead", + "clip_upper(threshold) is deprecated, use clip(upper=threshold) instead", FutureWarning, stacklevel=2, ) @@ -7717,7 +7710,7 @@ def clip_lower(self, threshold, axis=None, inplace=False): 2 5 6 """ warnings.warn( - "clip_lower(threshold) is deprecated, " "use clip(lower=threshold) instead", + "clip_lower(threshold) is deprecated, use clip(lower=threshold) instead", FutureWarning, stacklevel=2, ) @@ -8720,12 +8713,10 @@ def align( fill_axis=0, broadcast_axis=None, ): - from pandas import DataFrame, Series - method = missing.clean_fill_method(method) if broadcast_axis == 1 and self.ndim != other.ndim: - if isinstance(self, Series): + if isinstance(self, ABCSeries): # this means other is a DataFrame, and we need to broadcast # self cons = self._constructor_expanddim @@ -8743,7 +8734,7 @@ def align( limit=limit, fill_axis=fill_axis, ) - elif isinstance(other, Series): + elif isinstance(other, ABCSeries): # this means self is a DataFrame, and we need to broadcast # other cons = other._constructor_expanddim @@ -8764,7 +8755,7 @@ def align( if axis is not None: axis = self._get_axis_number(axis) - if isinstance(other, DataFrame): + if isinstance(other, ABCDataFrame): return self._align_frame( other, join=join, @@ -8776,7 +8767,7 @@ def align( limit=limit, fill_axis=fill_axis, ) - elif isinstance(other, Series): + elif isinstance(other, ABCSeries): return self._align_series( other, join=join, @@ -8869,7 +8860,7 @@ def _align_series( # series/series compat, other must always be a Series if is_series: if axis: - raise ValueError("cannot align series to a series other than " "axis 0") + raise ValueError("cannot align series to a series other than axis 0") # equal if self.index.equals(other.index): @@ -8959,7 +8950,7 @@ def _where( if not hasattr(cond, "shape"): cond = np.asanyarray(cond) if cond.shape != self.shape: - raise ValueError("Array conditional must be same shape as " "self") + raise ValueError("Array conditional must be same shape as self") cond = self._constructor(cond, **self._construct_axes_dict()) # make sure we are boolean @@ -8999,7 +8990,7 @@ def _where( # slice me out of the other else: raise NotImplementedError( - "cannot align with a higher " "dimensional NDFrame" + "cannot align with a higher dimensional NDFrame" ) if isinstance(other, np.ndarray): @@ -9042,12 +9033,12 @@ def _where( else: raise ValueError( - "Length of replacements must equal " "series length" + "Length of replacements must equal series length" ) else: raise ValueError( - "other must be the same shape as self " "when an ndarray" + "other must be the same shape as self when an ndarray" ) # we are the same shape, so create an actual object for alignment @@ -9641,7 +9632,7 @@ def _tz_convert(ax, tz): if len(ax) > 0: ax_name = self._get_axis_name(axis) raise TypeError( - "%s is not a valid DatetimeIndex or " "PeriodIndex" % ax_name + "%s is not a valid DatetimeIndex or PeriodIndex" % ax_name ) else: ax = DatetimeIndex([], tz=tz) @@ -9805,7 +9796,7 @@ def _tz_localize(ax, tz, ambiguous, nonexistent): if len(ax) > 0: ax_name = self._get_axis_name(axis) raise TypeError( - "%s is not a valid DatetimeIndex or " "PeriodIndex" % ax_name + "%s is not a valid DatetimeIndex or PeriodIndex" % ax_name ) else: ax = DatetimeIndex([], tz=tz) @@ -10249,7 +10240,7 @@ def _check_percentile(self, q): Validate percentiles (used by describe and quantile). """ - msg = "percentiles should all be in the interval [0, 1]. " "Try {0} instead." + msg = "percentiles should all be in the interval [0, 1]. Try {0} instead." q = np.asarray(q) if q.ndim == 0: if not 0 <= q <= 1: @@ -10769,7 +10760,7 @@ def ewm( def transform(self, func, *args, **kwargs): result = self.agg(func, *args, **kwargs) if is_scalar(result) or len(result) != len(self): - raise ValueError("transforms cannot produce " "aggregated results") + raise ValueError("transforms cannot produce aggregated results") return result @@ -11669,7 +11660,7 @@ def logical_func(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs if level is not None: if bool_only is not None: raise NotImplementedError( - "Option bool_only is not " "implemented with option level." + "Option bool_only is not implemented with option level." ) return self._agg_by_level(name, axis=axis, level=level, skipna=skipna) return self._reduce( diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 8f0abc91f7aef..5edf9504157c7 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -119,7 +119,7 @@ def clean_interp_method(method, **kwargs): "from_derivatives", ] if method in ("spline", "polynomial") and order is None: - raise ValueError("You must specify the order of the spline or " "polynomial.") + raise ValueError("You must specify the order of the spline or polynomial.") if method not in valid: raise ValueError( "method must be one of {valid}. Got '{method}' " @@ -176,7 +176,7 @@ def interpolate_1d( valid_limit_directions = ["forward", "backward", "both"] limit_direction = limit_direction.lower() if limit_direction not in valid_limit_directions: - msg = "Invalid limit_direction: expecting one of {valid!r}, " "got {invalid!r}." + msg = "Invalid limit_direction: expecting one of {valid!r}, got {invalid!r}." raise ValueError( msg.format(valid=valid_limit_directions, invalid=limit_direction) ) @@ -322,7 +322,7 @@ def _interpolate_scipy_wrapper( alt_methods["pchip"] = interpolate.pchip_interpolate except AttributeError: raise ImportError( - "Your version of Scipy does not support " "PCHIP interpolation." + "Your version of Scipy does not support PCHIP interpolation." ) elif method == "akima": alt_methods["akima"] = _akima_interpolate @@ -470,7 +470,7 @@ def interpolate_2d( ndim = values.ndim if values.ndim == 1: if axis != 0: # pragma: no cover - raise AssertionError("cannot interpolate on a ndim == 1 with " "axis != 0") + raise AssertionError("cannot interpolate on a ndim == 1 with axis != 0") values = values.reshape(tuple((1,) + values.shape)) if fill_value is None: diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 50da5e4057210..3a5dfe6700bd2 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -1139,7 +1139,7 @@ def wrapper(self, other, axis=None): return NotImplemented elif isinstance(other, ABCSeries) and not self._indexed_same(other): - raise ValueError("Can only compare identically-labeled " "Series objects") + raise ValueError("Can only compare identically-labeled Series objects") elif is_categorical_dtype(self): # Dispatch to Categorical implementation; pd.CategoricalIndex @@ -1169,9 +1169,7 @@ def wrapper(self, other, axis=None): if op in {operator.lt, operator.le, operator.gt, operator.ge}: future = "a TypeError will be raised" else: - future = ( - "'the values will not compare equal to the " "'datetime.date'" - ) + future = "'the values will not compare equal to the 'datetime.date'" msg = "\n".join(textwrap.wrap(msg.format(future=future))) warnings.warn(msg, FutureWarning, stacklevel=2) other = Timestamp(other) @@ -1404,9 +1402,7 @@ def _align_method_FRAME(left, right, axis): """ convert rhs to meet lhs dims if input is list, tuple or np.ndarray """ def to_series(right): - msg = ( - "Unable to coerce to Series, length must be {req_len}: " "given {given_len}" - ) + msg = "Unable to coerce to Series, length must be {req_len}: given {given_len}" if axis is not None and left._get_axis_name(axis) == "index": if len(left.index) != len(right): raise ValueError( @@ -1564,7 +1560,7 @@ def f(self, other): # Another DataFrame if not self._indexed_same(other): raise ValueError( - "Can only compare identically-labeled " "DataFrame objects" + "Can only compare identically-labeled DataFrame objects" ) return dispatch_to_series(self, other, func, str_rep) diff --git a/pandas/core/reshape/concat.py b/pandas/core/reshape/concat.py index ca4175e4a474a..ce2d2ac41d3ec 100644 --- a/pandas/core/reshape/concat.py +++ b/pandas/core/reshape/concat.py @@ -290,7 +290,7 @@ def __init__( self.intersect = True else: # pragma: no cover raise ValueError( - "Only can inner (intersect) or outer (union) " "join the other axis" + "Only can inner (intersect) or outer (union) join the other axis" ) if isinstance(objs, dict): diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 187a1913c3e15..413132db195f6 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -39,7 +39,7 @@ def melt( id_vars = [id_vars] elif isinstance(frame.columns, ABCMultiIndex) and not isinstance(id_vars, list): raise ValueError( - "id_vars must be a list of tuples when columns" " are a MultiIndex" + "id_vars must be a list of tuples when columns are a MultiIndex" ) else: # Check that `id_vars` are in frame @@ -61,7 +61,7 @@ def melt( value_vars, list ): raise ValueError( - "value_vars must be a list of tuples when" " columns are a MultiIndex" + "value_vars must be a list of tuples when columns are a MultiIndex" ) else: value_vars = list(value_vars) diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 5f8801619faec..fc32a8f0dd044 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -1556,7 +1556,7 @@ def _validate_specification(self): # set 'by' columns if self.by is not None: if self.left_by is not None or self.right_by is not None: - raise MergeError("Can only pass by OR left_by " "and right_by") + raise MergeError("Can only pass by OR left_by and right_by") self.left_by = self.right_by = self.by if self.left_by is None and self.right_by is not None: raise MergeError("missing left_by") diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 1f519d4c0867d..0519a1159cda3 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -133,9 +133,7 @@ def __init__( num_cells = np.multiply(num_rows, num_columns, dtype=np.int32) if num_rows > 0 and num_columns > 0 and num_cells <= 0: - raise ValueError( - "Unstacked DataFrame is too big, " "causing int32 overflow" - ) + raise ValueError("Unstacked DataFrame is too big, causing int32 overflow") self._make_sorted_values_labels() self._make_selectors() @@ -176,7 +174,7 @@ def _make_selectors(self): mask.put(selector, True) if mask.sum() < len(self.index): - raise ValueError("Index contains duplicate entries, " "cannot reshape") + raise ValueError("Index contains duplicate entries, cannot reshape") self.group_index = comp_index self.mask = mask diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index 0446f53345671..d1bdbdf51e9f5 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -230,7 +230,7 @@ def cut( if np.isinf(mn) or np.isinf(mx): # GH 24314 raise ValueError( - "cannot specify integer `bins` when input data " "contains infinity" + "cannot specify integer `bins` when input data contains infinity" ) elif mn == mx: # adjust end points before binning mn -= 0.001 * abs(mn) if mn != 0 else 0.001 @@ -406,7 +406,7 @@ def _bins_to_cuts( else: if len(labels) != len(bins) - 1: raise ValueError( - "Bin labels must be one fewer than " "the number of bin edges" + "Bin labels must be one fewer than the number of bin edges" ) if not is_categorical_dtype(labels): labels = Categorical(labels, categories=labels, ordered=True) diff --git a/pandas/core/series.py b/pandas/core/series.py index 5ae2bfa03923b..b445ff5f944de 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2614,9 +2614,7 @@ def dot(self, other): >>> s.dot(arr) array([24, 14]) """ - from pandas.core.frame import DataFrame - - if isinstance(other, (Series, DataFrame)): + if isinstance(other, (Series, ABCDataFrame)): common = self.index.union(other.index) if len(common) > len(self.index) or len(common) > len(other.index): raise ValueError("matrices are not aligned") @@ -2633,7 +2631,7 @@ def dot(self, other): "Dot product shape mismatch, %s vs %s" % (lvals.shape, rvals.shape) ) - if isinstance(other, DataFrame): + if isinstance(other, ABCDataFrame): return self._constructor( np.dot(lvals, rvals), index=other.columns ).__finalize__(self) diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index 46e8e97c7de8a..5db31fe6664ea 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -436,7 +436,7 @@ def safe_sort(values, labels=None, na_sentinel=-1, assume_unique=False, verify=T """ if not is_list_like(values): raise TypeError( - "Only list-like objects are allowed to be passed to" "safe_sort as values" + "Only list-like objects are allowed to be passed to safe_sort as values" ) if not isinstance(values, np.ndarray) and not is_extension_array_dtype(values): diff --git a/pandas/core/sparse/frame.py b/pandas/core/sparse/frame.py index f2d3e0012e635..f5add426297a7 100644 --- a/pandas/core/sparse/frame.py +++ b/pandas/core/sparse/frame.py @@ -425,7 +425,7 @@ def sp_maker(x, index=None): elif isinstance(value, SparseArray): if len(value) != len(self.index): - raise ValueError("Length of values does not match " "length of index") + raise ValueError("Length of values does not match length of index") clean = value elif hasattr(value, "__iter__"): @@ -435,9 +435,7 @@ def sp_maker(x, index=None): clean = sp_maker(clean) else: if len(value) != len(self.index): - raise ValueError( - "Length of values does not match " "length of index" - ) + raise ValueError("Length of values does not match length of index") clean = sp_maker(value) # Scalar @@ -732,7 +730,7 @@ def _reindex_with_indexers( if method is not None or limit is not None: raise NotImplementedError( - "cannot reindex with a method or limit " "with sparse" + "cannot reindex with a method or limit with sparse" ) if fill_value is None: @@ -765,9 +763,7 @@ def _join_compat( self, other, on=None, how="left", lsuffix="", rsuffix="", sort=False ): if on is not None: - raise NotImplementedError( - "'on' keyword parameter is not yet " "implemented" - ) + raise NotImplementedError("'on' keyword parameter is not yet implemented") return self._join_index(other, how, lsuffix, rsuffix) def _join_index(self, other, how, lsuffix, rsuffix): diff --git a/pandas/core/sparse/scipy_sparse.py b/pandas/core/sparse/scipy_sparse.py index 73638f5965119..e8d8996fdd6ad 100644 --- a/pandas/core/sparse/scipy_sparse.py +++ b/pandas/core/sparse/scipy_sparse.py @@ -99,7 +99,7 @@ def _sparse_series_to_coo(ss, row_levels=(0,), column_levels=(1,), sort_labels=F raise ValueError("to_coo requires MultiIndex with nlevels > 2") if not ss.index.is_unique: raise ValueError( - "Duplicate index entries are not allowed in to_coo " "transformation." + "Duplicate index entries are not allowed in to_coo transformation." ) # to keep things simple, only rely on integer indexing (not labels) diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py index 5eb9cfbd01ede..0c417133b0538 100644 --- a/pandas/core/sparse/series.py +++ b/pandas/core/sparse/series.py @@ -590,7 +590,7 @@ def dropna(self, axis=0, inplace=False, **kwargs): dense_valid = self.to_dense().dropna() if inplace: raise NotImplementedError( - "Cannot perform inplace dropna" " operations on a SparseSeries" + "Cannot perform inplace dropna operations on a SparseSeries" ) if isna(self.fill_value): return dense_valid diff --git a/pandas/core/strings.py b/pandas/core/strings.py index ad8226e56e09f..54882d039f135 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -603,7 +603,7 @@ def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True): if is_compiled_re: if (case is not None) or (flags != 0): raise ValueError( - "case and flags cannot be set" " when pat is a compiled regex" + "case and flags cannot be set when pat is a compiled regex" ) else: # not a compiled regex @@ -623,10 +623,10 @@ def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True): else: if is_compiled_re: raise ValueError( - "Cannot use a compiled regex as replacement " "pattern with regex=False" + "Cannot use a compiled regex as replacement pattern with regex=False" ) if callable(repl): - raise ValueError("Cannot use a callable replacement when " "regex=False") + raise ValueError("Cannot use a callable replacement when regex=False") f = lambda x: x.replace(pat, repl, n) return _na_map(f, arr) @@ -1944,7 +1944,7 @@ def _validate(data): """ if isinstance(data, ABCMultiIndex): raise AttributeError( - "Can only use .str accessor with Index, " "not MultiIndex" + "Can only use .str accessor with Index, not MultiIndex" ) # see _libs/lib.pyx for list of inferred types @@ -1957,7 +1957,7 @@ def _validate(data): inferred_dtype = lib.infer_dtype(values, skipna=True) if inferred_dtype not in allowed_types: - raise AttributeError("Can only use .str accessor with string " "values!") + raise AttributeError("Can only use .str accessor with string values!") return inferred_dtype def __getitem__(self, key): @@ -2653,7 +2653,7 @@ def rsplit(self, pat=None, n=-1, expand=False): "side": "first", "return": "3 elements containing the string itself, followed by two " "empty strings", - "also": "rpartition : Split the string at the last occurrence of " "`sep`.", + "also": "rpartition : Split the string at the last occurrence of `sep`.", } ) @deprecate_kwarg(old_arg_name="pat", new_arg_name="sep") @@ -2669,7 +2669,7 @@ def partition(self, sep=" ", expand=True): "side": "last", "return": "3 elements containing two empty strings, followed by the " "string itself", - "also": "partition : Split the string at the first occurrence of " "`sep`.", + "also": "partition : Split the string at the first occurrence of `sep`.", } ) @deprecate_kwarg(old_arg_name="pat", new_arg_name="sep") diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 20c4b9422459c..172084e97a959 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -365,7 +365,7 @@ def _convert_listlike_datetimes( return result elif getattr(arg, "ndim", 1) > 1: raise TypeError( - "arg must be a string, datetime, list, tuple, " "1-d array, or Series" + "arg must be a string, datetime, list, tuple, 1-d array, or Series" ) # warn if passing timedelta64, raise for PeriodDtype @@ -402,9 +402,7 @@ def _convert_listlike_datetimes( orig_arg = ensure_object(orig_arg) result = _attempt_YYYYMMDD(orig_arg, errors=errors) except (ValueError, TypeError, tslibs.OutOfBoundsDatetime): - raise ValueError( - "cannot convert the input to " "'%Y%m%d' date format" - ) + raise ValueError("cannot convert the input to '%Y%m%d' date format") # fallback if result is None: @@ -503,7 +501,7 @@ def _adjust_to_origin(arg, origin, unit): try: arg = arg - j0 except TypeError: - raise ValueError("incompatible 'arg' type for given " "'origin'='julian'") + raise ValueError("incompatible 'arg' type for given 'origin'='julian'") # preemptively check this for a nice range j_max = Timestamp.max.to_julian_date() - j0 @@ -897,7 +895,7 @@ def coerce(values): try: values = to_datetime(values, format="%Y%m%d", errors=errors, utc=tz) except (TypeError, ValueError) as e: - raise ValueError("cannot assemble the " "datetimes: {error}".format(error=e)) + raise ValueError("cannot assemble the datetimes: {error}".format(error=e)) for u in ["h", "m", "s", "ms", "us", "ns"]: value = unit_rev.get(u) @@ -1029,7 +1027,7 @@ def _convert_listlike(arg, format): elif getattr(arg, "ndim", 1) > 1: raise TypeError( - "arg must be a string, datetime, list, tuple, " "1-d array, or Series" + "arg must be a string, datetime, list, tuple, 1-d array, or Series" ) arg = ensure_object(arg) @@ -1074,7 +1072,7 @@ def _convert_listlike(arg, format): times.append(time_object) elif errors == "raise": raise ValueError( - "Cannot convert arg {arg} to " "a time".format(arg=arg) + "Cannot convert arg {arg} to a time".format(arg=arg) ) elif errors == "ignore": return arg diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index 2c594a3df27ea..cc31317980ca8 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -97,11 +97,11 @@ def to_timedelta(arg, unit="ns", box=True, errors="raise"): unit = parse_timedelta_unit(unit) if errors not in ("ignore", "raise", "coerce"): - raise ValueError("errors must be one of 'ignore', " "'raise', or 'coerce'}") + raise ValueError("errors must be one of 'ignore', 'raise', or 'coerce'}") if unit in {"Y", "y", "M"}: warnings.warn( - "M and Y units are deprecated and " "will be removed in a future version.", + "M and Y units are deprecated and will be removed in a future version.", FutureWarning, stacklevel=2, ) @@ -120,7 +120,7 @@ def to_timedelta(arg, unit="ns", box=True, errors="raise"): return _convert_listlike(arg, unit=unit, box=box, errors=errors) elif getattr(arg, "ndim", 1) > 1: raise TypeError( - "arg must be a string, timedelta, list, tuple, " "1-d array, or Series" + "arg must be a string, timedelta, list, tuple, 1-d array, or Series" ) # ...so it must be a scalar value. Return scalar. diff --git a/pandas/core/window.py b/pandas/core/window.py index 4721d6cfc6dda..323eba36e4678 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -120,7 +120,7 @@ def validate(self): "left", "neither", ]: - raise ValueError("closed must be 'right', 'left', 'both' or " "'neither'") + raise ValueError("closed must be 'right', 'left', 'both' or 'neither'") def _create_blocks(self): """ @@ -232,9 +232,7 @@ def _prep_values(self, values: Optional[np.ndarray] = None) -> np.ndarray: try: values = ensure_float64(values) except (ValueError, TypeError): - raise TypeError( - "cannot handle this type -> {0}" "".format(values.dtype) - ) + raise TypeError("cannot handle this type -> {0}".format(values.dtype)) # Always convert inf to nan values[np.isinf(values)] = np.NaN @@ -327,9 +325,7 @@ def _center_window(self, result, window) -> np.ndarray: Center the result in the window. """ if self.axis > result.ndim - 1: - raise ValueError( - "Requested axis is larger then no. of argument " "dimensions" - ) + raise ValueError("Requested axis is larger then no. of argument dimensions") offset = _offset(window, True) if offset > 0: @@ -1734,7 +1730,7 @@ def validate(self): if not self.is_datetimelike and self.closed is not None: raise ValueError( - "closed only implemented for datetimelike " "and offset based windows" + "closed only implemented for datetimelike and offset based windows" ) def _validate_monotonic(self): @@ -1743,7 +1739,7 @@ def _validate_monotonic(self): """ if not self._on.is_monotonic: formatted = self.on or "index" - raise ValueError("{0} must be " "monotonic".format(formatted)) + raise ValueError("{0} must be monotonic".format(formatted)) def _validate_freq(self): """ @@ -2738,7 +2734,7 @@ def dataframe_from_int_dict(data, frame_template): def _get_center_of_mass(comass, span, halflife, alpha): valid_count = com.count_not_none(comass, span, halflife, alpha) if valid_count > 1: - raise ValueError("comass, span, halflife, and alpha " "are mutually exclusive") + raise ValueError("comass, span, halflife, and alpha are mutually exclusive") # Convert to center of mass; domain checks ensure 0 < alpha <= 1 if comass is not None:
Mostly post-black cleanup
https://api.github.com/repos/pandas-dev/pandas/pulls/27632
2019-07-29T00:24:06Z
2019-07-29T16:52:39Z
2019-07-29T16:52:39Z
2019-07-29T16:54:35Z
BUG: raise when wrong level name is passed to "unstack"
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index eb60272246ebb..fa9ca98f9c8d8 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -128,7 +128,7 @@ Groupby/resample/rolling Reshaping ^^^^^^^^^ -- +- A ``KeyError`` is now raised if ``.unstack()`` is called on a :class:`Series` or :class:`DataFrame` with a flat :class:`Index` passing a name which is not the correct one (:issue:`18303`) - - diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 8042f71c2754e..745f8f3c90ea8 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1524,7 +1524,11 @@ def _validate_index_level(self, level): "Too many levels:" " Index has only 1 level, not %d" % (level + 1) ) elif level != self.name: - raise KeyError("Level %s must be same as name (%s)" % (level, self.name)) + raise KeyError( + "Requested level ({}) does not match index name ({})".format( + level, self.name + ) + ) def _get_level_number(self, level): self._validate_index_level(level) diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 1f519d4c0867d..f5c46429d9d49 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -12,6 +12,7 @@ ensure_platform_int, is_bool_dtype, is_extension_array_dtype, + is_integer, is_integer_dtype, is_list_like, is_object_dtype, @@ -402,6 +403,10 @@ def unstack(obj, level, fill_value=None): else: level = level[0] + # Prioritize integer interpretation (GH #21677): + if not is_integer(level) and not level == "__placeholder__": + level = obj.index._get_level_number(level) + if isinstance(obj, DataFrame): if isinstance(obj.index, MultiIndex): return _unstack_frame(obj, level, fill_value=fill_value) diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 6a274c8369328..00b59fd4dc087 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -1083,7 +1083,7 @@ def test_reset_index_level(self): # Missing levels - for both MultiIndex and single-level Index: for idx_lev in ["A", "B"], ["A"]: - with pytest.raises(KeyError, match="Level E "): + with pytest.raises(KeyError, match=r"(L|l)evel \(?E\)?"): df.set_index(idx_lev).reset_index(level=["A", "E"]) with pytest.raises(IndexError, match="Too many levels"): df.set_index(idx_lev).reset_index(level=[0, 1, 2]) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index e75d80bec1fdf..c40a9bce9385b 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2004,7 +2004,7 @@ def test_isin_level_kwarg_bad_label_raises(self, label, indices): msg = "'Level {} not found'" else: index = index.rename("foo") - msg = r"'Level {} must be same as name \(foo\)'" + msg = r"Requested level \({}\) does not match index name \(foo\)" with pytest.raises(KeyError, match=msg.format(label)): index.isin([], level=label) diff --git a/pandas/tests/indexes/test_common.py b/pandas/tests/indexes/test_common.py index 0e9aa07a4c05a..ae1a21e9b3980 100644 --- a/pandas/tests/indexes/test_common.py +++ b/pandas/tests/indexes/test_common.py @@ -35,7 +35,8 @@ def test_droplevel(self, indices): for level in "wrong", ["wrong"]: with pytest.raises( - KeyError, match=re.escape("'Level wrong must be same as name (None)'") + KeyError, + match=r"'Requested level \(wrong\) does not match index name \(None\)'", ): indices.droplevel(level) @@ -200,7 +201,7 @@ def test_unique(self, indices): with pytest.raises(IndexError, match=msg): indices.unique(level=3) - msg = r"Level wrong must be same as name \({}\)".format( + msg = r"Requested level \(wrong\) does not match index name \({}\)".format( re.escape(indices.name.__repr__()) ) with pytest.raises(KeyError, match=msg): diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py index f58462c0f3576..0a25d6ba203cb 100644 --- a/pandas/tests/series/test_alter_axes.py +++ b/pandas/tests/series/test_alter_axes.py @@ -319,9 +319,9 @@ def test_reset_index_drop_errors(self): # KeyError raised for series index when passed level name is missing s = Series(range(4)) - with pytest.raises(KeyError, match="must be same as name"): + with pytest.raises(KeyError, match="does not match index name"): s.reset_index("wrong", drop=True) - with pytest.raises(KeyError, match="must be same as name"): + with pytest.raises(KeyError, match="does not match index name"): s.reset_index("wrong") # KeyError raised for series when level to be dropped is missing diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index c97c69c323b56..dc4db6e7902a8 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -524,6 +524,22 @@ def test_stack_unstack_preserve_names(self): restacked = unstacked.stack() assert restacked.index.names == self.frame.index.names + @pytest.mark.parametrize("method", ["stack", "unstack"]) + def test_stack_unstack_wrong_level_name(self, method): + # GH 18303 - wrong level name should raise + + # A DataFrame with flat axes: + df = self.frame.loc["foo"] + + with pytest.raises(KeyError, match="does not match index name"): + getattr(df, method)("mistake") + + if method == "unstack": + # Same on a Series: + s = df.iloc[:, 0] + with pytest.raises(KeyError, match="does not match index name"): + getattr(s, method)("mistake") + def test_unstack_level_name(self): result = self.frame.unstack("second") expected = self.frame.unstack(level=1)
- [x] closes #18303 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Notice that I profited to make the error message a bit more understandable.
https://api.github.com/repos/pandas-dev/pandas/pulls/27631
2019-07-28T15:16:26Z
2019-07-29T16:55:40Z
2019-07-29T16:55:40Z
2019-08-03T11:44:30Z
DOC: Validate docstring directives
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 06d45e38bfcdb..333136ddfddd9 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -263,8 +263,8 @@ fi ### DOCSTRINGS ### if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then - MSG='Validate docstrings (GL03, GL04, GL05, GL06, GL07, GL09, SS04, SS05, PR03, PR04, PR05, PR10, EX04, RT01, RT04, RT05, SA05)' ; echo $MSG - $BASE_DIR/scripts/validate_docstrings.py --format=azure --errors=GL03,GL04,GL05,GL06,GL07,GL09,SS04,SS05,PR03,PR04,PR05,PR10,EX04,RT01,RT04,RT05,SA05 + MSG='Validate docstrings (GL03, GL04, GL05, GL06, GL07, GL09, GL10, SS04, SS05, PR03, PR04, PR05, PR10, EX04, RT01, RT04, RT05, SA05)' ; echo $MSG + $BASE_DIR/scripts/validate_docstrings.py --format=azure --errors=GL03,GL04,GL05,GL06,GL07,GL09,GL10,SS04,SS05,PR03,PR04,PR05,PR10,EX04,RT01,RT04,RT05,SA05 RET=$(($RET + $?)) ; echo $MSG "DONE" fi diff --git a/scripts/tests/test_validate_docstrings.py b/scripts/tests/test_validate_docstrings.py index f3364e6725a20..35aaf10458f44 100644 --- a/scripts/tests/test_validate_docstrings.py +++ b/scripts/tests/test_validate_docstrings.py @@ -200,7 +200,7 @@ def contains(self, pat, case=True, na=np.nan): def mode(self, axis, numeric_only): """ - Ensure sphinx directives don't affect checks for trailing periods. + Ensure reST directives don't affect checks for leading periods. Parameters ---------- @@ -447,6 +447,27 @@ def deprecation_in_wrong_order(self): def method_wo_docstrings(self): pass + def directives_without_two_colons(self, first, second): + """ + Ensure reST directives have trailing colons. + + Parameters + ---------- + first : str + Sentence ending in period, followed by single directive w/o colons. + + .. versionchanged 0.1.2 + + second : bool + Sentence ending in period, followed by multiple directives w/o + colons. + + .. versionadded 0.1.2 + .. deprecated 0.00.0 + + """ + pass + class BadSummaries: def wrong_line(self): @@ -840,6 +861,7 @@ def test_bad_class(self, capsys): "plot", "method", "private_classes", + "directives_without_two_colons", ], ) def test_bad_generic_functions(self, capsys, func): @@ -879,6 +901,14 @@ def test_bad_generic_functions(self, capsys, func): "deprecation_in_wrong_order", ("Deprecation warning should precede extended summary",), ), + ( + "BadGenericDocStrings", + "directives_without_two_colons", + ( + "reST directives ['versionchanged', 'versionadded', " + "'deprecated'] must be followed by two colons", + ), + ), ( "BadSeeAlso", "desc_no_period", diff --git a/scripts/validate_docstrings.py b/scripts/validate_docstrings.py index 37623d32db685..bf5d861281a36 100755 --- a/scripts/validate_docstrings.py +++ b/scripts/validate_docstrings.py @@ -59,6 +59,7 @@ PRIVATE_CLASSES = ["NDFrame", "IndexOpsMixin"] DIRECTIVES = ["versionadded", "versionchanged", "deprecated"] +DIRECTIVE_PATTERN = re.compile(rf"^\s*\.\. ({'|'.join(DIRECTIVES)})(?!::)", re.I | re.M) ALLOWED_SECTIONS = [ "Parameters", "Attributes", @@ -93,6 +94,7 @@ "GL07": "Sections are in the wrong order. Correct order is: " "{correct_sections}", "GL08": "The object does not have a docstring", "GL09": "Deprecation warning should precede extended summary", + "GL10": "reST directives {directives} must be followed by two colons", "SS01": "No summary found (a short summary in a single line should be " "present at the beginning of the docstring)", "SS02": "Summary does not start with a capital letter", @@ -478,6 +480,10 @@ def parameter_mismatches(self): def correct_parameters(self): return not bool(self.parameter_mismatches) + @property + def directives_without_two_colons(self): + return DIRECTIVE_PATTERN.findall(self.raw_doc) + def parameter_type(self, param): return self.doc_parameters[param][0] @@ -697,6 +703,10 @@ def get_validation_data(doc): if doc.deprecated and not doc.extended_summary.startswith(".. deprecated:: "): errs.append(error("GL09")) + directives_without_two_colons = doc.directives_without_two_colons + if directives_without_two_colons: + errs.append(error("GL10", directives=directives_without_two_colons)) + if not doc.summary: errs.append(error("SS01")) else:
- [X] closes #27629 - [x] tests added / passed - [x] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27630
2019-07-28T10:58:57Z
2019-08-06T20:55:16Z
2019-08-06T20:55:16Z
2019-08-07T04:34:18Z
Make interpolate_2d handle datetime64 correctly
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 4ca867b1088e7..98397e81d7bea 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1223,7 +1223,6 @@ def _interpolate_with_fill( fill_value=fill_value, dtype=self.dtype, ) - values = self._try_coerce_result(values) blocks = [self.make_block_same_class(values, ndim=self.ndim)] return self._maybe_downcast(blocks, downcast) @@ -2293,13 +2292,6 @@ def _try_coerce_args(self, other): return other - def _try_coerce_result(self, result): - """ reverse of try_coerce_args """ - if isinstance(result, np.ndarray) and result.dtype.kind == "i": - # needed for _interpolate_with_ffill - result = result.view("M8[ns]") - return result - def to_native_types( self, slicer=None, na_rep=None, date_format=None, quoting=None, **kwargs ): diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 8f0abc91f7aef..19e4c3166da71 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -463,6 +463,7 @@ def interpolate_2d( Perform an actual interpolation of values, values will be make 2-d if needed fills inplace, returns the result. """ + orig_values = values transf = (lambda x: x) if axis == 0 else (lambda x: x.T) @@ -470,7 +471,7 @@ def interpolate_2d( ndim = values.ndim if values.ndim == 1: if axis != 0: # pragma: no cover - raise AssertionError("cannot interpolate on a ndim == 1 with " "axis != 0") + raise AssertionError("cannot interpolate on a ndim == 1 with axis != 0") values = values.reshape(tuple((1,) + values.shape)) if fill_value is None: @@ -490,6 +491,10 @@ def interpolate_2d( if ndim == 1: values = values[0] + if orig_values.dtype.kind == "M": + # convert float back to datetime64 + values = values.astype(orig_values.dtype) + return values diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index 929bd1725b30a..fb3d428bcf4bf 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -885,7 +885,7 @@ def test_resample_dtype_preservation(): assert result.val.dtype == np.int32 -def test_resample_dtype_coerceion(): +def test_resample_dtype_coercion(): pytest.importorskip("scipy.interpolate") diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index 8f4c89ee72ae1..f1b84acf68755 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -1533,6 +1533,17 @@ def test_interp_datetime64(self, method, tz_naive_fixture): ) assert_series_equal(result, expected) + def test_interp_pad_datetime64tz_values(self): + # GH#27628 missing.interpolate_2d should handle datetimetz values + dti = pd.date_range("2015-04-05", periods=3, tz="US/Central") + ser = pd.Series(dti) + ser[1] = pd.NaT + result = ser.interpolate(method="pad") + + expected = pd.Series(dti) + expected[1] = expected[0] + tm.assert_series_equal(result, expected) + def test_interp_limit_no_nans(self): # GH 7173 s = pd.Series([1.0, 2.0, 3.0])
Broken off from #27626 because I decided that is poorly scoped.
https://api.github.com/repos/pandas-dev/pandas/pulls/27628
2019-07-28T01:11:51Z
2019-07-31T20:22:12Z
2019-07-31T20:22:12Z
2019-07-31T20:35:11Z
CLN: de-kludge Block.quantile
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 4ca867b1088e7..62b08fd1712c8 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1526,18 +1526,7 @@ def quantile(self, qs, interpolation="linear", axis=0): # We should always have ndim == 2 becase Series dispatches to DataFrame assert self.ndim == 2 - if self.is_datetimetz: - # TODO: cleanup this special case. - # We need to operate on i8 values for datetimetz - # but `Block.get_values()` returns an ndarray of objects - # right now. We need an API for "values to do numeric-like ops on" - values = self.values.view("M8[ns]") - - # TODO: NonConsolidatableMixin shape - # Usual shape inconsistencies for ExtensionBlocks - values = values[None, :] - else: - values = self.get_values() + values = self.get_values() is_empty = values.shape[axis] == 0 orig_scalar = not is_list_like(qs) @@ -1576,7 +1565,6 @@ def quantile(self, qs, interpolation="linear", axis=0): result = lib.item_from_zerodim(result) ndim = getattr(result, "ndim", None) or 0 - result = self._try_coerce_result(result) return make_block(result, placement=np.arange(len(result)), ndim=ndim) def _replace_coerce( @@ -2477,21 +2465,9 @@ def _try_coerce_result(self, result): result = self._holder._from_sequence( result.astype(np.int64), freq=None, dtype=self.values.dtype ) - elif result.dtype == "M8[ns]": - # otherwise we get here via quantile and already have M8[ns] - result = self._holder._simple_new( - result, freq=None, dtype=self.values.dtype - ) - elif isinstance(result, np.datetime64): - # also for post-quantile - result = self._box_func(result) return result - @property - def _box_func(self): - return lambda x: tslibs.Timestamp(x, tz=self.dtype.tz) - def diff(self, n, axis=0): """1st discrete difference @@ -2564,6 +2540,19 @@ def equals(self, other): return False return (self.values.view("i8") == other.values.view("i8")).all() + def quantile(self, qs, interpolation="linear", axis=0): + naive = self.values.view("M8[ns]") + + # kludge for 2D block with 1D values + naive = naive.reshape(self.shape) + + blk = self.make_block(naive) + res_blk = blk.quantile(qs, interpolation=interpolation, axis=axis) + + # ravel is kludge for 2D block with 1D values, assumes column-like + aware = self._holder(res_blk.values.ravel(), dtype=self.dtype) + return self.make_block_same_class(aware, ndim=res_blk.ndim) + class TimeDeltaBlock(DatetimeLikeBlockMixin, IntBlock): __slots__ = ()
Broken off from #27626 since I decided that is poorly scoped.
https://api.github.com/repos/pandas-dev/pandas/pulls/27627
2019-07-28T01:07:25Z
2019-07-31T12:17:59Z
2019-07-31T12:17:59Z
2019-07-31T13:27:13Z
remove undesired values kwarg
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 4ca867b1088e7..990a24ef8d904 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -552,10 +552,10 @@ def f(m, v, i): return self.split_and_operate(None, f, False) - def astype(self, dtype, copy=False, errors="raise", values=None, **kwargs): - return self._astype(dtype, copy=copy, errors=errors, values=values, **kwargs) + def astype(self, dtype, copy=False, errors="raise", **kwargs): + return self._astype(dtype, copy=copy, errors=errors, **kwargs) - def _astype(self, dtype, copy=False, errors="raise", values=None, **kwargs): + def _astype(self, dtype, copy=False, errors="raise", **kwargs): """Coerce to the new type Parameters @@ -616,42 +616,39 @@ def _astype(self, dtype, copy=False, errors="raise", values=None, **kwargs): return self.copy() return self - if values is None: - try: - # force the copy here - if self.is_extension: - values = self.values.astype(dtype) - else: - if issubclass(dtype.type, str): - - # use native type formatting for datetime/tz/timedelta - if self.is_datelike: - values = self.to_native_types() + try: + # force the copy here + if self.is_extension: + values = self.values.astype(dtype) + else: + if issubclass(dtype.type, str): - # astype formatting - else: - values = self.get_values() + # use native type formatting for datetime/tz/timedelta + if self.is_datelike: + values = self.to_native_types() + # astype formatting else: - values = self.get_values(dtype=dtype) + values = self.get_values() - # _astype_nansafe works fine with 1-d only - vals1d = values.ravel() - values = astype_nansafe(vals1d, dtype, copy=True, **kwargs) + else: + values = self.get_values(dtype=dtype) - # TODO(extension) - # should we make this attribute? - if isinstance(values, np.ndarray): - values = values.reshape(self.shape) + # _astype_nansafe works fine with 1-d only + vals1d = values.ravel() + values = astype_nansafe(vals1d, dtype, copy=True, **kwargs) - except Exception: - # e.g. astype_nansafe can fail on object-dtype of strings - # trying to convert to float - if errors == "raise": - raise - newb = self.copy() if copy else self - else: - newb = make_block(values, placement=self.mgr_locs, ndim=self.ndim) + # TODO(extension) + # should we make this attribute? + if isinstance(values, np.ndarray): + values = values.reshape(self.shape) + + except Exception: + # e.g. astype_nansafe can fail on object-dtype of strings + # trying to convert to float + if errors == "raise": + raise + newb = self.copy() if copy else self else: newb = make_block(values, placement=self.mgr_locs, ndim=self.ndim)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27625
2019-07-27T19:38:45Z
2019-07-31T12:20:16Z
2019-07-31T12:20:16Z
2019-07-31T13:26:32Z
Fix docstrings
diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 1c35298fcc6b8..39529177b9e35 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -90,7 +90,7 @@ class PandasArray(ExtensionArray, ExtensionOpsMixin, NDArrayOperatorsMixin): """ A pandas ExtensionArray for NumPy data. - .. versionadded :: 0.24.0 + .. versionadded:: 0.24.0 This is mostly for internal compatibility, and is not especially useful on its own. diff --git a/pandas/core/arrays/sparse.py b/pandas/core/arrays/sparse.py index f6aa8bbd77614..048f6c6f5c680 100644 --- a/pandas/core/arrays/sparse.py +++ b/pandas/core/arrays/sparse.py @@ -2102,7 +2102,7 @@ class SparseFrameAccessor(BaseAccessor, PandasDelegate): """ DataFrame accessor for sparse data. - .. versionadded :: 0.25.0 + .. versionadded:: 0.25.0 """ def _validate(self, data): diff --git a/pandas/core/base.py b/pandas/core/base.py index 89a3d9cfea5ab..ce993a513f569 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -727,7 +727,7 @@ def item(self): """ Return the first element of the underlying data as a python scalar. - .. deprecated 0.25.0 + .. deprecated:: 0.25.0 Returns ------- @@ -1559,7 +1559,7 @@ def factorize(self, sort=False, na_sentinel=-1): A scalar or array of insertion points with the same shape as `value`. - .. versionchanged :: 0.24.0 + .. versionchanged:: 0.24.0 If `value` is a scalar, an int is now always returned. Previously, scalar inputs returned an 1-item array for :class:`Series` and :class:`Categorical`. diff --git a/pandas/core/frame.py b/pandas/core/frame.py index cdbe0e9d22eb4..d060ac0d193ad 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -310,11 +310,11 @@ class DataFrame(NDFrame): data : ndarray (structured or homogeneous), Iterable, dict, or DataFrame Dict can contain Series, arrays, constants, or list-like objects - .. versionchanged :: 0.23.0 + .. versionchanged:: 0.23.0 If data is a dict, column order follows insertion-order for Python 3.6 and later. - .. versionchanged :: 0.25.0 + .. versionchanged:: 0.25.0 If data is a list of dicts, column order follows insertion-order Python 3.6 and later. @@ -3560,7 +3560,7 @@ def assign(self, **kwargs): or modified columns. All items are computed first, and then assigned in alphabetical order. - .. versionchanged :: 0.23.0 + .. versionchanged:: 0.23.0 Keyword argument order is maintained for Python 3.6 and later. @@ -5628,7 +5628,7 @@ def update( If 'raise', will raise a ValueError if the DataFrame and `other` both contain non-NA data in the same place. - .. versionchanged :: 0.24.0 + .. versionchanged:: 0.24.0 Changed from `raise_conflict=False|True` to `errors='ignore'|'raise'`. @@ -5774,7 +5774,7 @@ def update( specified, all remaining columns will be used and the result will have hierarchically indexed columns. - .. versionchanged :: 0.23.0 + .. versionchanged:: 0.23.0 Also accept list of column names. Returns @@ -5903,7 +5903,7 @@ def pivot(self, index=None, columns=None, values=None): If True: only show observed values for categorical groupers. If False: show all values for categorical groupers. - .. versionchanged :: 0.25.0 + .. versionchanged:: 0.25.0 Returns ------- diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 97a0b04146297..df97d34ee349a 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -11490,7 +11490,7 @@ def _doc_parms(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. - .. versionadded :: 0.22.0 + .. versionadded:: 0.22.0 Added with the default being 0. This means the sum of an all-NA or empty Series is 0, and the product of an all-NA or empty diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 47cf0f26f9ca5..04a858c8bfbdf 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -931,7 +931,7 @@ def item(self): return the first element of the underlying data as a python scalar - .. deprecated 0.25.0 + .. deprecated:: 0.25.0 """ warnings.warn( diff --git a/pandas/core/series.py b/pandas/core/series.py index c7fcab56e1fe5..c83a626ce9b8d 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -156,7 +156,7 @@ class Series(base.IndexOpsMixin, generic.NDFrame): data : array-like, Iterable, dict, or scalar value Contains data stored in Series. - .. versionchanged :: 0.23.0 + .. versionchanged:: 0.23.0 If data is a dict, argument order is maintained for Python 3.6 and later. @@ -370,7 +370,7 @@ def from_array( """ Construct Series from array. - .. deprecated :: 0.23.0 + .. deprecated:: 0.23.0 Use pd.Series(..) constructor instead. Returns @@ -597,7 +597,7 @@ def asobject(self): """ Return object Series which contains boxed values. - .. deprecated :: 0.23.0 + .. deprecated:: 0.23.0 Use ``astype(object)`` instead. @@ -952,7 +952,7 @@ def real(self): """ Return the real value of vector. - .. deprecated 0.25.0 + .. deprecated:: 0.25.0 """ warnings.warn( "`real` has be deprecated and will be removed in a future version", @@ -970,7 +970,7 @@ def imag(self): """ Return imag value of vector. - .. deprecated 0.25.0 + .. deprecated:: 0.25.0 """ warnings.warn( "`imag` has be deprecated and will be removed in a future version", diff --git a/pandas/core/sparse/frame.py b/pandas/core/sparse/frame.py index 3e44a7f941a86..f2d3e0012e635 100644 --- a/pandas/core/sparse/frame.py +++ b/pandas/core/sparse/frame.py @@ -49,7 +49,7 @@ class SparseDataFrame(DataFrame): Parameters ---------- data : same types as can be passed to DataFrame or scipy.sparse.spmatrix - .. versionchanged :: 0.23.0 + .. versionchanged:: 0.23.0 If data is a dict, argument order is maintained for Python 3.6 and later. diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py index fc51c06b149fd..9064aa3ba1260 100644 --- a/pandas/core/sparse/series.py +++ b/pandas/core/sparse/series.py @@ -55,7 +55,7 @@ class SparseSeries(Series): Parameters ---------- data : {array-like, Series, SparseSeries, dict} - .. versionchanged :: 0.23.0 + .. versionchanged:: 0.23.0 If data is a dict, argument order is maintained for Python 3.6 and later. diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py index 296b1eef68d7d..35a62b627823a 100644 --- a/pandas/io/feather_format.py +++ b/pandas/io/feather_format.py @@ -71,7 +71,7 @@ def read_feather(path, columns=None, use_threads=True): """ Load a feather-format object from the file path. - .. versionadded 0.20.0 + .. versionadded:: 0.20.0 Parameters ---------- @@ -90,16 +90,16 @@ def read_feather(path, columns=None, use_threads=True): columns : sequence, default None If not provided, all columns are read. - .. versionadded 0.24.0 + .. versionadded:: 0.24.0 nthreads : int, default 1 Number of CPU threads to use when reading to pandas.DataFrame. - .. versionadded 0.21.0 - .. deprecated 0.24.0 + .. versionadded:: 0.21.0 + .. deprecated:: 0.24.0 use_threads : bool, default True Whether to parallelize reading using multiple threads. - .. versionadded 0.24.0 + .. versionadded:: 0.24.0 Returns ------- diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index 617f4f44ae8af..82c460300582b 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -231,7 +231,7 @@ def to_parquet( ``False``, they will not be written to the file. If ``None``, the engine's default behavior will be used. - .. versionadded 0.24.0 + .. versionadded:: 0.24.0 partition_cols : list, optional, default None Column names by which to partition the dataset @@ -257,7 +257,7 @@ def read_parquet(path, engine="auto", columns=None, **kwargs): """ Load a parquet object from the file path, returning a DataFrame. - .. versionadded 0.21.0 + .. versionadded:: 0.21.0 Parameters ---------- @@ -281,7 +281,7 @@ def read_parquet(path, engine="auto", columns=None, **kwargs): columns : list, default=None If not None, only these columns will be read from the file. - .. versionadded 0.21.1 + .. versionadded:: 0.21.1 **kwargs Any additional kwargs are passed to the engine. diff --git a/pandas/io/spss.py b/pandas/io/spss.py index 983ac1c818c42..4f13349a819c3 100644 --- a/pandas/io/spss.py +++ b/pandas/io/spss.py @@ -15,7 +15,7 @@ def read_spss( """ Load an SPSS file from the file path, returning a DataFrame. - .. versionadded 0.25.0 + .. versionadded:: 0.25.0 Parameters ----------
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry This fixes some docstring formatting issues: e.g. some deprecated directives do not appear in current docs because the two colons are missing `.. deprecated 0.25.0`.
https://api.github.com/repos/pandas-dev/pandas/pulls/27621
2019-07-27T10:16:26Z
2019-07-28T09:54:48Z
2019-07-28T09:54:48Z
2019-07-28T09:54:48Z
DEPR: remove ix
diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py index 9647693d4ed6b..ae6c07107f4a0 100644 --- a/asv_bench/benchmarks/frame_methods.py +++ b/asv_bench/benchmarks/frame_methods.py @@ -321,10 +321,9 @@ class Dropna: def setup(self, how, axis): self.df = DataFrame(np.random.randn(10000, 1000)) - with warnings.catch_warnings(record=True): - self.df.ix[50:1000, 20:50] = np.nan - self.df.ix[2000:3000] = np.nan - self.df.ix[:, 60:70] = np.nan + self.df.iloc[50:1000, 20:50] = np.nan + self.df.iloc[2000:3000] = np.nan + self.df.iloc[:, 60:70] = np.nan self.df_mixed = self.df.copy() self.df_mixed["foo"] = "bar" @@ -342,10 +341,9 @@ class Count: def setup(self, axis): self.df = DataFrame(np.random.randn(10000, 1000)) - with warnings.catch_warnings(record=True): - self.df.ix[50:1000, 20:50] = np.nan - self.df.ix[2000:3000] = np.nan - self.df.ix[:, 60:70] = np.nan + self.df.iloc[50:1000, 20:50] = np.nan + self.df.iloc[2000:3000] = np.nan + self.df.iloc[:, 60:70] = np.nan self.df_mixed = self.df.copy() self.df_mixed["foo"] = "bar" diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index ac35139c1954a..c78c2fa92827e 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -67,22 +67,6 @@ def time_iloc_scalar(self, index, index_structure): def time_iloc_slice(self, index, index_structure): self.data.iloc[:800000] - def time_ix_array(self, index, index_structure): - with warnings.catch_warnings(record=True): - self.data.ix[self.array] - - def time_ix_list_like(self, index, index_structure): - with warnings.catch_warnings(record=True): - self.data.ix[[800000]] - - def time_ix_scalar(self, index, index_structure): - with warnings.catch_warnings(record=True): - self.data.ix[800000] - - def time_ix_slice(self, index, index_structure): - with warnings.catch_warnings(record=True): - self.data.ix[:800000] - def time_loc_array(self, index, index_structure): self.data.loc[self.array] @@ -148,10 +132,6 @@ def setup(self): self.bool_indexer = self.df[self.col_scalar] > 0 self.bool_obj_indexer = self.bool_indexer.astype(object) - def time_ix(self): - with warnings.catch_warnings(record=True): - self.df.ix[self.idx_scalar, self.col_scalar] - def time_loc(self): self.df.loc[self.idx_scalar, self.col_scalar] @@ -228,14 +208,6 @@ def setup(self): self.idx = IndexSlice[20000:30000, 20:30, 35:45, 30000:40000] self.mdt = self.mdt.set_index(["A", "B", "C", "D"]).sort_index() - def time_series_ix(self): - with warnings.catch_warnings(record=True): - self.s.ix[999] - - def time_frame_ix(self): - with warnings.catch_warnings(record=True): - self.df.ix[999] - def time_index_slice(self): self.mdt.loc[self.idx, :] @@ -310,10 +282,6 @@ def setup_cache(self): def time_lookup_iloc(self, s): s.iloc - def time_lookup_ix(self, s): - with warnings.catch_warnings(record=True): - s.ix - def time_lookup_loc(self, s): s.loc diff --git a/doc/source/reference/index.rst b/doc/source/reference/index.rst index 12ca318c815d3..9d5649c37e92f 100644 --- a/doc/source/reference/index.rst +++ b/doc/source/reference/index.rst @@ -49,7 +49,6 @@ public functions related to data types in pandas. api/pandas.DataFrame.blocks api/pandas.DataFrame.as_matrix - api/pandas.DataFrame.ix api/pandas.Index.asi8 api/pandas.Index.data api/pandas.Index.flags @@ -60,7 +59,6 @@ public functions related to data types in pandas. api/pandas.Series.asobject api/pandas.Series.blocks api/pandas.Series.from_array - api/pandas.Series.ix api/pandas.Series.imag api/pandas.Series.real diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 19fb4bdcd9536..d87053eeda691 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -533,6 +533,7 @@ or ``matplotlib.Axes.plot``. See :ref:`plotting.formatters` for more. - :meth:`DataFrame.hist` and :meth:`Series.hist` no longer allows ``figsize="default"``, specify figure size by passinig a tuple instead (:issue:`30003`) - Floordiv of integer-dtyped array by :class:`Timedelta` now raises ``TypeError`` (:issue:`21036`) - :func:`pandas.api.types.infer_dtype` argument ``skipna`` defaults to ``True`` instead of ``False`` (:issue:`24050`) +- Removed the previously deprecated :attr:`Series.ix` and :attr:`DataFrame.ix` (:issue:`26438`) - Removed the previously deprecated :meth:`Index.summary` (:issue:`18217`) - Removed the previously deprecated "fastpath" keyword from the :class:`Index` constructor (:issue:`23110`) - Removed the previously deprecated :meth:`Series.get_value`, :meth:`Series.set_value`, :meth:`DataFrame.get_value`, :meth:`DataFrame.set_value` (:issue:`17739`) diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index a9269a5e0efa1..341262313ddff 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1,6 +1,4 @@ -import textwrap from typing import Tuple -import warnings import numpy as np @@ -10,10 +8,8 @@ from pandas.util._decorators import Appender from pandas.core.dtypes.common import ( - ensure_platform_int, is_float, is_integer, - is_integer_dtype, is_iterator, is_list_like, is_numeric_dtype, @@ -34,7 +30,6 @@ def get_indexers_list(): return [ - ("ix", _IXIndexer), ("iloc", _iLocIndexer), ("loc", _LocIndexer), ("at", _AtIndexer), @@ -112,9 +107,7 @@ def __call__(self, axis=None): new_self.axis = axis return new_self - def __iter__(self): - raise NotImplementedError("ix is not iterable") - + # TODO: remove once geopandas no longer needs this def __getitem__(self, key): # Used in ix and downstream in geopandas _CoordinateIndexer if type(key) is tuple: @@ -921,9 +914,6 @@ def _getitem_lowerdim(self, tup: Tuple): if len(tup) > self.ndim: raise IndexingError("Too many indexers. handle elsewhere") - # to avoid wasted computation - # df.ix[d1:d2, 0] -> columns first (True) - # df.ix[0, ['C', 'B', A']] -> rows first (False) for i, key in enumerate(tup): if is_label_like(key) or isinstance(key, tuple): section = self._getitem_axis(key, axis=i) @@ -1004,6 +994,7 @@ def _getitem_nested_tuple(self, tup: Tuple): return obj + # TODO: remove once geopandas no longer needs __getitem__ def _getitem_axis(self, key, axis: int): if is_iterator(key): key = list(key) @@ -1292,106 +1283,6 @@ def _get_slice_axis(self, slice_obj: slice, axis: int): return self._slice(indexer, axis=axis, kind="iloc") -class _IXIndexer(_NDFrameIndexer): - """ - A primarily label-location based indexer, with integer position fallback. - - Warning: Starting in 0.20.0, the .ix indexer is deprecated, in - favor of the more strict .iloc and .loc indexers. - - ``.ix[]`` supports mixed integer and label based access. It is - primarily label based, but will fall back to integer positional - access unless the corresponding axis is of integer type. - - ``.ix`` is the most general indexer and will support any of the - inputs in ``.loc`` and ``.iloc``. ``.ix`` also supports floating - point label schemes. ``.ix`` is exceptionally useful when dealing - with mixed positional and label based hierarchical indexes. - - However, when an axis is integer based, ONLY label based access - and not positional access is supported. Thus, in such cases, it's - usually better to be explicit and use ``.iloc`` or ``.loc``. - - See more at :ref:`Advanced Indexing <advanced>`. - """ - - _ix_deprecation_warning = textwrap.dedent( - """ - .ix is deprecated. Please use - .loc for label based indexing or - .iloc for positional indexing - - See the documentation here: - http://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#ix-indexer-is-deprecated""" # noqa: E501 - ) - - def __init__(self, name, obj): - warnings.warn(self._ix_deprecation_warning, FutureWarning, stacklevel=2) - super().__init__(name, obj) - - @Appender(_NDFrameIndexer._validate_key.__doc__) - def _validate_key(self, key, axis: int) -> bool: - """ - Returns - ------- - bool - """ - if isinstance(key, slice): - return True - - elif com.is_bool_indexer(key): - return True - - elif is_list_like_indexer(key): - return True - - else: - - self._convert_scalar_indexer(key, axis) - - return True - - def _convert_for_reindex(self, key, axis: int): - """ - Transform a list of keys into a new array ready to be used as axis of - the object we return (e.g. including NaNs). - - Parameters - ---------- - key : list-like - Targeted labels. - axis: int - Where the indexing is being made. - - Returns - ------- - list-like of labels. - """ - labels = self.obj._get_axis(axis) - - if com.is_bool_indexer(key): - key = check_bool_indexer(labels, key) - return labels[key] - - if isinstance(key, Index): - keyarr = labels._convert_index_indexer(key) - else: - # asarray can be unsafe, NumPy strings are weird - keyarr = com.asarray_tuplesafe(key) - - if is_integer_dtype(keyarr): - # Cast the indexer to uint64 if possible so - # that the values returned from indexing are - # also uint64. - keyarr = labels._convert_arr_indexer(keyarr) - - if not labels.is_integer(): - keyarr = ensure_platform_int(keyarr) - return labels.take(keyarr) - - return keyarr - - class _LocationIndexer(_NDFrameIndexer): def __getitem__(self, key): if type(key) is tuple: diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 716be92ebca3f..cd384d6fdbfad 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1,6 +1,5 @@ from datetime import date, datetime, time, timedelta import re -from warnings import catch_warnings, simplefilter import numpy as np import pytest @@ -396,10 +395,8 @@ def test_getitem_ix_mixed_integer(self): expected = df.loc[df.index[:-1]] tm.assert_frame_equal(result, expected) - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = df.ix[[1, 10]] - expected = df.ix[Index([1, 10], dtype=object)] + result = df.loc[[1, 10]] + expected = df.loc[Index([1, 10])] tm.assert_frame_equal(result, expected) # 11320 @@ -419,53 +416,6 @@ def test_getitem_ix_mixed_integer(self): expected = df.iloc[:, [1]] tm.assert_frame_equal(result, expected) - def test_getitem_setitem_ix_negative_integers(self, float_frame): - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = float_frame.ix[:, -1] - tm.assert_series_equal(result, float_frame["D"]) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = float_frame.ix[:, [-1]] - tm.assert_frame_equal(result, float_frame[["D"]]) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = float_frame.ix[:, [-1, -2]] - tm.assert_frame_equal(result, float_frame[["D", "C"]]) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - float_frame.ix[:, [-1]] = 0 - assert (float_frame["D"] == 0).all() - - df = DataFrame(np.random.randn(8, 4)) - # ix does label-based indexing when having an integer index - msg = "\"None of [Int64Index([-1], dtype='int64')] are in the [index]\"" - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - with pytest.raises(KeyError, match=re.escape(msg)): - df.ix[[-1]] - - msg = "\"None of [Int64Index([-1], dtype='int64')] are in the [columns]\"" - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - with pytest.raises(KeyError, match=re.escape(msg)): - df.ix[:, [-1]] - - # #1942 - a = DataFrame(np.random.randn(20, 2), index=[chr(x + 65) for x in range(20)]) - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - a.ix[-1] = a.ix[-2] - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - tm.assert_series_equal(a.ix[-1], a.ix[-2], check_names=False) - assert a.ix[-1].name == "T" - assert a.ix[-2].name == "S" - def test_getattr(self, float_frame): tm.assert_series_equal(float_frame.A, float_frame["A"]) msg = "'DataFrame' object has no attribute 'NONEXISTENT_NAME'" @@ -848,55 +798,6 @@ def test_delitem_corner(self, float_frame): del f["B"] assert len(f.columns) == 2 - def test_getitem_fancy_2d(self, float_frame): - f = float_frame - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - tm.assert_frame_equal(f.ix[:, ["B", "A"]], f.reindex(columns=["B", "A"])) - - subidx = float_frame.index[[5, 4, 1]] - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - tm.assert_frame_equal( - f.ix[subidx, ["B", "A"]], f.reindex(index=subidx, columns=["B", "A"]) - ) - - # slicing rows, etc. - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - tm.assert_frame_equal(f.ix[5:10], f[5:10]) - tm.assert_frame_equal(f.ix[5:10, :], f[5:10]) - tm.assert_frame_equal( - f.ix[:5, ["A", "B"]], f.reindex(index=f.index[:5], columns=["A", "B"]) - ) - - # slice rows with labels, inclusive! - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - expected = f.ix[5:11] - result = f.ix[f.index[5] : f.index[10]] - tm.assert_frame_equal(expected, result) - - # slice columns - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - tm.assert_frame_equal(f.ix[:, :2], f.reindex(columns=["A", "B"])) - - # get view - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - exp = f.copy() - f.ix[5:10].values[:] = 5 - exp.values[5:10] = 5 - tm.assert_frame_equal(f, exp) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - msg = "Cannot index with multidimensional key" - with pytest.raises(ValueError, match=msg): - f.ix[f > 0.5] - def test_slice_floats(self): index = [52195.504153, 52196.303147, 52198.369883] df = DataFrame(np.random.rand(3, 2), index=index) @@ -945,119 +846,6 @@ def test_getitem_setitem_integer_slice_keyerrors(self): with pytest.raises(KeyError, match=r"^3$"): df2.loc[3:11] = 0 - def test_setitem_fancy_2d(self, float_frame): - - # case 1 - frame = float_frame.copy() - expected = frame.copy() - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - frame.ix[:, ["B", "A"]] = 1 - expected["B"] = 1.0 - expected["A"] = 1.0 - tm.assert_frame_equal(frame, expected) - - # case 2 - frame = float_frame.copy() - frame2 = float_frame.copy() - - expected = frame.copy() - - subidx = float_frame.index[[5, 4, 1]] - values = np.random.randn(3, 2) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - frame.ix[subidx, ["B", "A"]] = values - frame2.ix[[5, 4, 1], ["B", "A"]] = values - - expected["B"].ix[subidx] = values[:, 0] - expected["A"].ix[subidx] = values[:, 1] - - tm.assert_frame_equal(frame, expected) - tm.assert_frame_equal(frame2, expected) - - # case 3: slicing rows, etc. - frame = float_frame.copy() - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - expected1 = float_frame.copy() - frame.ix[5:10] = 1.0 - expected1.values[5:10] = 1.0 - tm.assert_frame_equal(frame, expected1) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - expected2 = float_frame.copy() - arr = np.random.randn(5, len(frame.columns)) - frame.ix[5:10] = arr - expected2.values[5:10] = arr - tm.assert_frame_equal(frame, expected2) - - # case 4 - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - frame = float_frame.copy() - frame.ix[5:10, :] = 1.0 - tm.assert_frame_equal(frame, expected1) - frame.ix[5:10, :] = arr - tm.assert_frame_equal(frame, expected2) - - # case 5 - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - frame = float_frame.copy() - frame2 = float_frame.copy() - - expected = float_frame.copy() - values = np.random.randn(5, 2) - - frame.ix[:5, ["A", "B"]] = values - expected["A"][:5] = values[:, 0] - expected["B"][:5] = values[:, 1] - tm.assert_frame_equal(frame, expected) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - frame2.ix[:5, [0, 1]] = values - tm.assert_frame_equal(frame2, expected) - - # case 6: slice rows with labels, inclusive! - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - frame = float_frame.copy() - expected = float_frame.copy() - - frame.ix[frame.index[5] : frame.index[10]] = 5.0 - expected.values[5:11] = 5 - tm.assert_frame_equal(frame, expected) - - # case 7: slice columns - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - frame = float_frame.copy() - frame2 = float_frame.copy() - expected = float_frame.copy() - - # slice indices - frame.ix[:, 1:3] = 4.0 - expected.values[:, 1:3] = 4.0 - tm.assert_frame_equal(frame, expected) - - # slice with labels - frame.ix[:, "B":"C"] = 4.0 - tm.assert_frame_equal(frame, expected) - - # new corner case of boolean slicing / setting - frame = DataFrame(zip([2, 3, 9, 6, 7], [np.nan] * 5), columns=["a", "b"]) - lst = [100] - lst.extend([np.nan] * 4) - expected = DataFrame(zip([100, 3, 9, 6, 7], lst), columns=["a", "b"]) - frame[frame["a"] == 2] = 100 - tm.assert_frame_equal(frame, expected) - def test_fancy_getitem_slice_mixed(self, float_frame, float_string_frame): sliced = float_string_frame.iloc[:, -3:] assert sliced["D"].dtype == np.float64 @@ -1071,194 +859,6 @@ def test_fancy_getitem_slice_mixed(self, float_frame, float_string_frame): assert (float_frame["C"] == 4).all() - def test_fancy_setitem_int_labels(self): - # integer index defers to label-based indexing - - df = DataFrame(np.random.randn(10, 5), index=np.arange(0, 20, 2)) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - tmp = df.copy() - exp = df.copy() - tmp.ix[[0, 2, 4]] = 5 - exp.values[:3] = 5 - tm.assert_frame_equal(tmp, exp) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - tmp = df.copy() - exp = df.copy() - tmp.ix[6] = 5 - exp.values[3] = 5 - tm.assert_frame_equal(tmp, exp) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - tmp = df.copy() - exp = df.copy() - tmp.ix[:, 2] = 5 - - # tmp correctly sets the dtype - # so match the exp way - exp[2] = 5 - tm.assert_frame_equal(tmp, exp) - - def test_fancy_getitem_int_labels(self): - df = DataFrame(np.random.randn(10, 5), index=np.arange(0, 20, 2)) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = df.ix[[4, 2, 0], [2, 0]] - expected = df.reindex(index=[4, 2, 0], columns=[2, 0]) - tm.assert_frame_equal(result, expected) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = df.ix[[4, 2, 0]] - expected = df.reindex(index=[4, 2, 0]) - tm.assert_frame_equal(result, expected) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = df.ix[4] - expected = df.xs(4) - tm.assert_series_equal(result, expected) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = df.ix[:, 3] - expected = df[3] - tm.assert_series_equal(result, expected) - - def test_fancy_index_int_labels_exceptions(self, float_frame): - df = DataFrame(np.random.randn(10, 5), index=np.arange(0, 20, 2)) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - - # labels that aren't contained - with pytest.raises(KeyError, match=r"\[1\] not in index"): - df.ix[[0, 1, 2], [2, 3, 4]] = 5 - - # try to set indices not contained in frame - msg = ( - r"None of \[Index\(\['foo', 'bar', 'baz'\]," - r" dtype='object'\)\] are in the \[index\]" - ) - with pytest.raises(KeyError, match=msg): - float_frame.ix[["foo", "bar", "baz"]] = 1 - msg = ( - r"None of \[Index\(\['E'\], dtype='object'\)\] are in the" - r" \[columns\]" - ) - with pytest.raises(KeyError, match=msg): - float_frame.ix[:, ["E"]] = 1 - - # FIXME: don't leave commented-out - # partial setting now allows this GH2578 - # pytest.raises(KeyError, float_frame.ix.__setitem__, - # (slice(None, None), 'E'), 1) - - def test_setitem_fancy_mixed_2d(self, float_string_frame): - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - float_string_frame.ix[:5, ["C", "B", "A"]] = 5 - result = float_string_frame.ix[:5, ["C", "B", "A"]] - assert (result.values == 5).all() - - float_string_frame.ix[5] = np.nan - assert isna(float_string_frame.ix[5]).all() - - float_string_frame.ix[5] = float_string_frame.ix[6] - tm.assert_series_equal( - float_string_frame.ix[5], float_string_frame.ix[6], check_names=False - ) - - # #1432 - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - df = DataFrame({1: [1.0, 2.0, 3.0], 2: [3, 4, 5]}) - assert df._is_mixed_type - - df.ix[1] = [5, 10] - - expected = DataFrame({1: [1.0, 5.0, 3.0], 2: [3, 10, 5]}) - - tm.assert_frame_equal(df, expected) - - def test_ix_align(self): - b = Series(np.random.randn(10), name=0).sort_values() - df_orig = DataFrame(np.random.randn(10, 4)) - df = df_orig.copy() - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - df.ix[:, 0] = b - tm.assert_series_equal(df.ix[:, 0].reindex(b.index), b) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - dft = df_orig.T - dft.ix[0, :] = b - tm.assert_series_equal(dft.ix[0, :].reindex(b.index), b) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - df = df_orig.copy() - df.ix[:5, 0] = b - s = df.ix[:5, 0] - tm.assert_series_equal(s, b.reindex(s.index)) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - dft = df_orig.T - dft.ix[0, :5] = b - s = dft.ix[0, :5] - tm.assert_series_equal(s, b.reindex(s.index)) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - df = df_orig.copy() - idx = [0, 1, 3, 5] - df.ix[idx, 0] = b - s = df.ix[idx, 0] - tm.assert_series_equal(s, b.reindex(s.index)) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - dft = df_orig.T - dft.ix[0, idx] = b - s = dft.ix[0, idx] - tm.assert_series_equal(s, b.reindex(s.index)) - - def test_ix_frame_align(self): - b = DataFrame(np.random.randn(3, 4)) - df_orig = DataFrame(np.random.randn(10, 4)) - df = df_orig.copy() - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - df.ix[:3] = b - out = b.ix[:3] - tm.assert_frame_equal(out, b) - - b.sort_index(inplace=True) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - df = df_orig.copy() - df.ix[[0, 1, 2]] = b - out = df.ix[[0, 1, 2]].reindex(b.index) - tm.assert_frame_equal(out, b) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - df = df_orig.copy() - df.ix[:3] = b - out = df.ix[:3] - tm.assert_frame_equal(out, b.reindex(out.index)) - def test_getitem_setitem_non_ix_labels(self): df = tm.makeTimeDataFrame() @@ -1285,6 +885,7 @@ def test_ix_multi_take(self): xp = df.reindex([0]) tm.assert_frame_equal(rs, xp) + # FIXME: dont leave commented-out """ #1321 df = DataFrame(np.random.randn(3, 2)) rs = df.loc[df.index==0, df.columns==1] @@ -1292,168 +893,6 @@ def test_ix_multi_take(self): tm.assert_frame_equal(rs, xp) """ - def test_ix_multi_take_nonint_index(self): - df = DataFrame(np.random.randn(3, 2), index=["x", "y", "z"], columns=["a", "b"]) - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - rs = df.ix[[0], [0]] - xp = df.reindex(["x"], columns=["a"]) - tm.assert_frame_equal(rs, xp) - - def test_ix_multi_take_multiindex(self): - df = DataFrame( - np.random.randn(3, 2), - index=["x", "y", "z"], - columns=[["a", "b"], ["1", "2"]], - ) - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - rs = df.ix[[0], [0]] - xp = df.reindex(["x"], columns=[("a", "1")]) - tm.assert_frame_equal(rs, xp) - - def test_ix_dup(self): - idx = Index(["a", "a", "b", "c", "d", "d"]) - df = DataFrame(np.random.randn(len(idx), 3), idx) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - sub = df.ix[:"d"] - tm.assert_frame_equal(sub, df) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - sub = df.ix["a":"c"] - tm.assert_frame_equal(sub, df.ix[0:4]) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - sub = df.ix["b":"d"] - tm.assert_frame_equal(sub, df.ix[2:]) - - def test_getitem_fancy_1d(self, float_frame, float_string_frame): - f = float_frame - - # return self if no slicing...for now - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - assert f.ix[:, :] is f - - # low dimensional slice - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - xs1 = f.ix[2, ["C", "B", "A"]] - xs2 = f.xs(f.index[2]).reindex(["C", "B", "A"]) - tm.assert_series_equal(xs1, xs2) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - ts1 = f.ix[5:10, 2] - ts2 = f[f.columns[2]][5:10] - tm.assert_series_equal(ts1, ts2) - - # positional xs - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - xs1 = f.ix[0] - xs2 = f.xs(f.index[0]) - tm.assert_series_equal(xs1, xs2) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - xs1 = f.ix[f.index[5]] - xs2 = f.xs(f.index[5]) - tm.assert_series_equal(xs1, xs2) - - # single column - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - tm.assert_series_equal(f.ix[:, "A"], f["A"]) - - # return view - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - exp = f.copy() - exp.values[5] = 4 - f.ix[5][:] = 4 - tm.assert_frame_equal(exp, f) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - exp.values[:, 1] = 6 - f.ix[:, 1][:] = 6 - tm.assert_frame_equal(exp, f) - - # slice of mixed-frame - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - xs = float_string_frame.ix[5] - exp = float_string_frame.xs(float_string_frame.index[5]) - tm.assert_series_equal(xs, exp) - - def test_setitem_fancy_1d(self, float_frame): - - # case 1: set cross-section for indices - frame = float_frame.copy() - expected = float_frame.copy() - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - frame.ix[2, ["C", "B", "A"]] = [1.0, 2.0, 3.0] - expected["C"][2] = 1.0 - expected["B"][2] = 2.0 - expected["A"][2] = 3.0 - tm.assert_frame_equal(frame, expected) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - frame2 = float_frame.copy() - frame2.ix[2, [3, 2, 1]] = [1.0, 2.0, 3.0] - tm.assert_frame_equal(frame, expected) - - # case 2, set a section of a column - frame = float_frame.copy() - expected = float_frame.copy() - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - vals = np.random.randn(5) - expected.values[5:10, 2] = vals - frame.ix[5:10, 2] = vals - tm.assert_frame_equal(frame, expected) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - frame2 = float_frame.copy() - frame2.ix[5:10, "B"] = vals - tm.assert_frame_equal(frame, expected) - - # case 3: full xs - frame = float_frame.copy() - expected = float_frame.copy() - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - frame.ix[4] = 5.0 - expected.values[4] = 5.0 - tm.assert_frame_equal(frame, expected) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - frame.ix[frame.index[4]] = 6.0 - expected.values[4] = 6.0 - tm.assert_frame_equal(frame, expected) - - # single column - frame = float_frame.copy() - expected = float_frame.copy() - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - frame.ix[:, "A"] = 7.0 - expected["A"] = 7.0 - tm.assert_frame_equal(frame, expected) - def test_getitem_fancy_scalar(self, float_frame): f = float_frame ix = f.loc @@ -1975,15 +1414,11 @@ def test_get_set_value_no_partial_indexing(self): with pytest.raises(KeyError, match=r"^0$"): df._get_value(0, 1) + # TODO: rename? remove? def test_single_element_ix_dont_upcast(self, float_frame): float_frame["E"] = 1 assert issubclass(float_frame["E"].dtype.type, (int, np.integer)) - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = float_frame.ix[float_frame.index[5], "E"] - assert is_integer(result) - result = float_frame.loc[float_frame.index[5], "E"] assert is_integer(result) @@ -1991,18 +1426,10 @@ def test_single_element_ix_dont_upcast(self, float_frame): df = pd.DataFrame(dict(a=[1.23])) df["b"] = 666 - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = df.ix[0, "b"] - assert is_integer(result) result = df.loc[0, "b"] assert is_integer(result) expected = Series([666], [0], name="b") - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = df.ix[[0], "b"] - tm.assert_series_equal(result, expected) result = df.loc[[0], "b"] tm.assert_series_equal(result, expected) @@ -2070,45 +1497,12 @@ def test_iloc_duplicates(self): df = DataFrame(np.random.rand(3, 3), columns=list("ABC"), index=list("aab")) result = df.iloc[0] - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result2 = df.ix[0] assert isinstance(result, Series) tm.assert_almost_equal(result.values, df.values[0]) - tm.assert_series_equal(result, result2) - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = df.T.iloc[:, 0] - result2 = df.T.ix[:, 0] + result = df.T.iloc[:, 0] assert isinstance(result, Series) tm.assert_almost_equal(result.values, df.values[0]) - tm.assert_series_equal(result, result2) - - # multiindex - df = DataFrame( - np.random.randn(3, 3), - columns=[["i", "i", "j"], ["A", "A", "B"]], - index=[["i", "i", "j"], ["X", "X", "Y"]], - ) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - rs = df.iloc[0] - xp = df.ix[0] - tm.assert_series_equal(rs, xp) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - rs = df.iloc[:, 0] - xp = df.T.ix[0] - tm.assert_series_equal(rs, xp) - - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - rs = df.iloc[:, [0]] - xp = df.ix[:, [0]] - tm.assert_frame_equal(rs, xp) # #2259 df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=[1, 1, 2]) @@ -2353,9 +1747,6 @@ def test_getitem_ix_float_duplicates(self): ) expect = df.iloc[1:] tm.assert_frame_equal(df.loc[0.2], expect) - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - tm.assert_frame_equal(df.ix[0.2], expect) expect = df.iloc[1:, 0] tm.assert_series_equal(df.loc[0.2, "a"], expect) @@ -2363,9 +1754,6 @@ def test_getitem_ix_float_duplicates(self): df.index = [1, 0.2, 0.2] expect = df.iloc[1:] tm.assert_frame_equal(df.loc[0.2], expect) - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - tm.assert_frame_equal(df.ix[0.2], expect) expect = df.iloc[1:, 0] tm.assert_series_equal(df.loc[0.2, "a"], expect) @@ -2375,9 +1763,6 @@ def test_getitem_ix_float_duplicates(self): ) expect = df.iloc[1:-1] tm.assert_frame_equal(df.loc[0.2], expect) - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - tm.assert_frame_equal(df.ix[0.2], expect) expect = df.iloc[1:-1, 0] tm.assert_series_equal(df.loc[0.2, "a"], expect) @@ -2385,9 +1770,6 @@ def test_getitem_ix_float_duplicates(self): df.index = [0.1, 0.2, 2, 0.2] expect = df.iloc[[1, -1]] tm.assert_frame_equal(df.loc[0.2], expect) - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - tm.assert_frame_equal(df.ix[0.2], expect) expect = df.iloc[[1, -1], 0] tm.assert_series_equal(df.loc[0.2, "a"], expect) @@ -2616,11 +1998,6 @@ def test_index_namedtuple(self): index = Index([idx1, idx2], name="composite_index", tupleize_cols=False) df = DataFrame([(1, 2), (3, 4)], index=index, columns=["A", "B"]) - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - result = df.ix[IndexType("foo", "bar")]["A"] - assert result == 1 - result = df.loc[IndexType("foo", "bar")]["A"] assert result == 1 diff --git a/pandas/tests/indexing/common.py b/pandas/tests/indexing/common.py index e5b2c83f29030..08e8dbad4e102 100644 --- a/pandas/tests/indexing/common.py +++ b/pandas/tests/indexing/common.py @@ -1,6 +1,6 @@ """ common utilities """ import itertools -from warnings import catch_warnings, filterwarnings +from warnings import catch_warnings import numpy as np @@ -136,21 +136,18 @@ def get_result(self, obj, method, key, axis): return xp - def get_value(self, f, i, values=False): + def get_value(self, name, f, i, values=False): """ return the value for the location i """ # check against values if values: return f.values[i] - # this is equiv of f[col][row]..... - # v = f - # for a in reversed(i): - # v = v.__getitem__(a) - # return v - with catch_warnings(record=True): - filterwarnings("ignore", "\\n.ix", FutureWarning) - return f.ix[i] + elif name == "iat": + return f.iloc[i] + else: + assert name == "at" + return f.loc[i] def check_values(self, f, func, values=False): @@ -183,16 +180,11 @@ def _eq(axis, obj, key1, key2): try: rs = getattr(obj, method1).__getitem__(_axify(obj, key1, axis)) - with catch_warnings(record=True): - filterwarnings("ignore", "\\n.ix", FutureWarning) - try: - xp = self.get_result( - obj=obj, method=method2, key=key2, axis=axis - ) - except (KeyError, IndexError): - # TODO: why is this allowed? - result = "no comp" - return + try: + xp = self.get_result(obj=obj, method=method2, key=key2, axis=axis) + except (KeyError, IndexError): + # TODO: why is this allowed? + return if is_scalar(rs) and is_scalar(xp): assert rs == xp diff --git a/pandas/tests/indexing/multiindex/test_slice.py b/pandas/tests/indexing/multiindex/test_slice.py index f279b5517c3f6..ee0f160b33cf1 100644 --- a/pandas/tests/indexing/multiindex/test_slice.py +++ b/pandas/tests/indexing/multiindex/test_slice.py @@ -1,5 +1,3 @@ -from warnings import catch_warnings - import numpy as np import pytest @@ -12,7 +10,6 @@ import pandas.util.testing as tm -@pytest.mark.filterwarnings("ignore:\\n.ix:FutureWarning") class TestMultiIndexSlicers: def test_per_axis_per_level_getitem(self): @@ -675,8 +672,6 @@ def test_multiindex_label_slicing_with_negative_step(self): def assert_slices_equivalent(l_slc, i_slc): tm.assert_series_equal(s.loc[l_slc], s.iloc[i_slc]) tm.assert_series_equal(s[l_slc], s.iloc[i_slc]) - with catch_warnings(record=True): - tm.assert_series_equal(s.ix[l_slc], s.iloc[i_slc]) assert_slices_equivalent(SLC[::-1], SLC[::-1]) diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index 6e26d407ab0ec..760bb655534b2 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -361,13 +361,12 @@ def check(result, expected): result4 = df["A"].iloc[2] check(result4, expected) - @pytest.mark.filterwarnings("ignore::FutureWarning") def test_cache_updating(self): # GH 4939, make sure to update the cache on setitem df = tm.makeDataFrame() df["A"] # cache series - df.ix["Hello Friend"] = df.ix[0] + df.loc["Hello Friend"] = df.iloc[0] assert "Hello Friend" in df["A"].index assert "Hello Friend" in df["B"].index diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py index 0a3b513ff0167..d004441690c8c 100644 --- a/pandas/tests/indexing/test_floats.py +++ b/pandas/tests/indexing/test_floats.py @@ -132,9 +132,8 @@ def test_scalar_non_numeric(self): elif s.index.inferred_type in ["datetime64", "timedelta64", "period"]: # these should prob work - # and are inconsisten between series/dataframe ATM - # for idxr in [lambda x: x.ix, - # lambda x: x]: + # and are inconsistent between series/dataframe ATM + # for idxr in [lambda x: x]: # s2 = s.copy() # # with pytest.raises(TypeError): diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index f9bded5b266f1..2f27757d6a754 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -1,6 +1,6 @@ """ test positional based indexing with iloc """ -from warnings import catch_warnings, filterwarnings, simplefilter +from warnings import catch_warnings, simplefilter import numpy as np import pytest @@ -135,26 +135,22 @@ def test_iloc_non_integer_raises(self, index, columns, index_vals, column_vals): df.iloc[index_vals, column_vals] def test_iloc_getitem_int(self): - # integer - self.check_result("iloc", 2, "ix", {0: 4, 1: 6, 2: 8}, typs=["ints", "uints"]) self.check_result( "iloc", 2, - "indexer", + "iloc", 2, typs=["labels", "mixed", "ts", "floats", "empty"], fails=IndexError, ) def test_iloc_getitem_neg_int(self): - # neg integer - self.check_result("iloc", -1, "ix", {0: 6, 1: 9, 2: 12}, typs=["ints", "uints"]) self.check_result( "iloc", -1, - "indexer", + "iloc", -1, typs=["labels", "mixed", "ts", "floats", "empty"], fails=IndexError, @@ -187,51 +183,17 @@ def test_iloc_array_not_mutating_negative_indices(self): tm.assert_numpy_array_equal(array_with_neg_numbers, array_copy) def test_iloc_getitem_list_int(self): - - # list of ints self.check_result( "iloc", [0, 1, 2], - "ix", - {0: [0, 2, 4], 1: [0, 3, 6], 2: [0, 4, 8]}, - typs=["ints", "uints"], - ) - self.check_result( - "iloc", [2], "ix", {0: [4], 1: [6], 2: [8]}, typs=["ints", "uints"], - ) - self.check_result( "iloc", [0, 1, 2], - "indexer", - [0, 1, 2], typs=["labels", "mixed", "ts", "floats", "empty"], fails=IndexError, ) # array of ints (GH5006), make sure that a single indexer is returning # the correct type - self.check_result( - "iloc", - np.array([0, 1, 2]), - "ix", - {0: [0, 2, 4], 1: [0, 3, 6], 2: [0, 4, 8]}, - typs=["ints", "uints"], - ) - self.check_result( - "iloc", - np.array([2]), - "ix", - {0: [4], 1: [6], 2: [8]}, - typs=["ints", "uints"], - ) - self.check_result( - "iloc", - np.array([0, 1, 2]), - "indexer", - [0, 1, 2], - typs=["labels", "mixed", "ts", "floats", "empty"], - fails=IndexError, - ) def test_iloc_getitem_neg_int_can_reach_first_index(self): # GH10547 and GH10779 @@ -261,15 +223,6 @@ def test_iloc_getitem_neg_int_can_reach_first_index(self): tm.assert_series_equal(result, expected) def test_iloc_getitem_dups(self): - - self.check_result( - "iloc", - [0, 1, 1, 3], - "ix", - {0: [0, 2, 2, 6], 1: [0, 3, 3, 9]}, - typs=["ints", "uints"], - ) - # GH 6766 df1 = DataFrame([{"A": None, "B": 1}, {"A": 2, "B": 2}]) df2 = DataFrame([{"A": 3, "B": 3}, {"A": 4, "B": 4}]) @@ -284,30 +237,12 @@ def test_iloc_getitem_dups(self): tm.assert_series_equal(result, expected) def test_iloc_getitem_array(self): - - # array like - s = Series(index=range(1, 4), dtype=object) - self.check_result( - "iloc", - s.index, - "ix", - {0: [2, 4, 6], 1: [3, 6, 9], 2: [4, 8, 12]}, - typs=["ints", "uints"], - ) + # TODO: test something here? + pass def test_iloc_getitem_bool(self): - - # boolean indexers - b = [True, False, True, False] - self.check_result("iloc", b, "ix", b, typs=["ints", "uints"]) - self.check_result( - "iloc", - b, - "ix", - b, - typs=["labels", "mixed", "ts", "floats", "empty"], - fails=IndexError, - ) + # TODO: test something here? + pass @pytest.mark.parametrize("index", [[True, False], [True, False, True, False]]) def test_iloc_getitem_bool_diff_len(self, index): @@ -320,23 +255,8 @@ def test_iloc_getitem_bool_diff_len(self, index): _ = s.iloc[index] def test_iloc_getitem_slice(self): - - # slices - self.check_result( - "iloc", - slice(1, 3), - "ix", - {0: [2, 4], 1: [3, 6], 2: [4, 8]}, - typs=["ints", "uints"], - ) - self.check_result( - "iloc", - slice(1, 3), - "indexer", - slice(1, 3), - typs=["labels", "mixed", "ts", "floats", "empty"], - fails=IndexError, - ) + # TODO: test something here? + pass def test_iloc_getitem_slice_dups(self): @@ -441,69 +361,53 @@ def test_iloc_setitem_dups(self): df.iloc[[1, 0], [0, 1]] = df.iloc[[1, 0], [0, 1]].reset_index(drop=True) tm.assert_frame_equal(df, expected) + # TODO: GH#27620 this test used to compare iloc against ix; check if this + # is redundant with another test comparing iloc against loc def test_iloc_getitem_frame(self): df = DataFrame( np.random.randn(10, 4), index=range(0, 20, 2), columns=range(0, 8, 2) ) result = df.iloc[2] - with catch_warnings(record=True): - filterwarnings("ignore", "\\n.ix", FutureWarning) - exp = df.ix[4] + exp = df.loc[4] tm.assert_series_equal(result, exp) result = df.iloc[2, 2] - with catch_warnings(record=True): - filterwarnings("ignore", "\\n.ix", FutureWarning) - exp = df.ix[4, 4] + exp = df.loc[4, 4] assert result == exp # slice result = df.iloc[4:8] - with catch_warnings(record=True): - filterwarnings("ignore", "\\n.ix", FutureWarning) - expected = df.ix[8:14] + expected = df.loc[8:14] tm.assert_frame_equal(result, expected) result = df.iloc[:, 2:3] - with catch_warnings(record=True): - filterwarnings("ignore", "\\n.ix", FutureWarning) - expected = df.ix[:, 4:5] + expected = df.loc[:, 4:5] tm.assert_frame_equal(result, expected) # list of integers result = df.iloc[[0, 1, 3]] - with catch_warnings(record=True): - filterwarnings("ignore", "\\n.ix", FutureWarning) - expected = df.ix[[0, 2, 6]] + expected = df.loc[[0, 2, 6]] tm.assert_frame_equal(result, expected) result = df.iloc[[0, 1, 3], [0, 1]] - with catch_warnings(record=True): - filterwarnings("ignore", "\\n.ix", FutureWarning) - expected = df.ix[[0, 2, 6], [0, 2]] + expected = df.loc[[0, 2, 6], [0, 2]] tm.assert_frame_equal(result, expected) # neg indices result = df.iloc[[-1, 1, 3], [-1, 1]] - with catch_warnings(record=True): - filterwarnings("ignore", "\\n.ix", FutureWarning) - expected = df.ix[[18, 2, 6], [6, 2]] + expected = df.loc[[18, 2, 6], [6, 2]] tm.assert_frame_equal(result, expected) # dups indices result = df.iloc[[-1, -1, 1, 3], [-1, 1]] - with catch_warnings(record=True): - filterwarnings("ignore", "\\n.ix", FutureWarning) - expected = df.ix[[18, 18, 2, 6], [6, 2]] + expected = df.loc[[18, 18, 2, 6], [6, 2]] tm.assert_frame_equal(result, expected) # with index-like s = Series(index=range(1, 5), dtype=object) result = df.iloc[s.index] - with catch_warnings(record=True): - filterwarnings("ignore", "\\n.ix", FutureWarning) - expected = df.ix[[2, 4, 6, 8]] + expected = df.loc[[2, 4, 6, 8]] tm.assert_frame_equal(result, expected) def test_iloc_getitem_labelled_frame(self): diff --git a/pandas/tests/indexing/test_ix.py b/pandas/tests/indexing/test_ix.py deleted file mode 100644 index a46cd65162f4e..0000000000000 --- a/pandas/tests/indexing/test_ix.py +++ /dev/null @@ -1,354 +0,0 @@ -""" test indexing with ix """ - -from warnings import catch_warnings - -import numpy as np -import pytest - -from pandas.core.dtypes.common import is_scalar - -import pandas as pd -from pandas import DataFrame, Series, option_context -import pandas.util.testing as tm - - -def test_ix_deprecation(): - # GH 15114 - - df = DataFrame({"A": [1, 2, 3]}) - with tm.assert_produces_warning(FutureWarning, check_stacklevel=True): - df.ix[1, "A"] - - -@pytest.mark.filterwarnings("ignore:\\n.ix:FutureWarning") -class TestIX: - def test_ix_loc_setitem_consistency(self): - - # GH 5771 - # loc with slice and series - s = Series(0, index=[4, 5, 6]) - s.loc[4:5] += 1 - expected = Series([1, 1, 0], index=[4, 5, 6]) - tm.assert_series_equal(s, expected) - - # GH 5928 - # chained indexing assignment - df = DataFrame({"a": [0, 1, 2]}) - expected = df.copy() - with catch_warnings(record=True): - expected.ix[[0, 1, 2], "a"] = -expected.ix[[0, 1, 2], "a"] - - with catch_warnings(record=True): - df["a"].ix[[0, 1, 2]] = -df["a"].ix[[0, 1, 2]] - tm.assert_frame_equal(df, expected) - - df = DataFrame({"a": [0, 1, 2], "b": [0, 1, 2]}) - with catch_warnings(record=True): - df["a"].ix[[0, 1, 2]] = -df["a"].ix[[0, 1, 2]].astype("float64") + 0.5 - expected = DataFrame({"a": [0.5, -0.5, -1.5], "b": [0, 1, 2]}) - tm.assert_frame_equal(df, expected) - - # GH 8607 - # ix setitem consistency - df = DataFrame( - { - "delta": [1174, 904, 161], - "elapsed": [7673, 9277, 1470], - "timestamp": [1413840976, 1413842580, 1413760580], - } - ) - expected = DataFrame( - { - "delta": [1174, 904, 161], - "elapsed": [7673, 9277, 1470], - "timestamp": pd.to_datetime( - [1413840976, 1413842580, 1413760580], unit="s" - ), - } - ) - - df2 = df.copy() - df2["timestamp"] = pd.to_datetime(df["timestamp"], unit="s") - tm.assert_frame_equal(df2, expected) - - df2 = df.copy() - df2.loc[:, "timestamp"] = pd.to_datetime(df["timestamp"], unit="s") - tm.assert_frame_equal(df2, expected) - - df2 = df.copy() - with catch_warnings(record=True): - df2.ix[:, 2] = pd.to_datetime(df["timestamp"], unit="s") - tm.assert_frame_equal(df2, expected) - - def test_ix_loc_consistency(self): - - # GH 8613 - # some edge cases where ix/loc should return the same - # this is not an exhaustive case - - def compare(result, expected): - if is_scalar(expected): - assert result == expected - else: - assert expected.equals(result) - - # failure cases for .loc, but these work for .ix - df = DataFrame(np.random.randn(5, 4), columns=list("ABCD")) - for key in [ - slice(1, 3), - tuple([slice(0, 2), slice(0, 2)]), - tuple([slice(0, 2), df.columns[0:2]]), - ]: - - for index in [ - tm.makeStringIndex, - tm.makeUnicodeIndex, - tm.makeDateIndex, - tm.makePeriodIndex, - tm.makeTimedeltaIndex, - ]: - df.index = index(len(df.index)) - with catch_warnings(record=True): - df.ix[key] - - msg = ( - r"cannot do slice indexing" - r" on {klass} with these indexers \[(0|1)\] of" - r" {kind}".format(klass=type(df.index), kind=str(int)) - ) - with pytest.raises(TypeError, match=msg): - df.loc[key] - - df = DataFrame( - np.random.randn(5, 4), - columns=list("ABCD"), - index=pd.date_range("2012-01-01", periods=5), - ) - - for key in [ - "2012-01-03", - "2012-01-31", - slice("2012-01-03", "2012-01-03"), - slice("2012-01-03", "2012-01-04"), - slice("2012-01-03", "2012-01-06", 2), - slice("2012-01-03", "2012-01-31"), - tuple([[True, True, True, False, True]]), - ]: - - # getitem - - # if the expected raises, then compare the exceptions - try: - with catch_warnings(record=True): - expected = df.ix[key] - except KeyError: - with pytest.raises(KeyError, match=r"^'2012-01-31'$"): - df.loc[key] - continue - - result = df.loc[key] - compare(result, expected) - - # setitem - df1 = df.copy() - df2 = df.copy() - - with catch_warnings(record=True): - df1.ix[key] = 10 - df2.loc[key] = 10 - compare(df2, df1) - - # edge cases - s = Series([1, 2, 3, 4], index=list("abde")) - - result1 = s["a":"c"] - with catch_warnings(record=True): - result2 = s.ix["a":"c"] - result3 = s.loc["a":"c"] - tm.assert_series_equal(result1, result2) - tm.assert_series_equal(result1, result3) - - # now work rather than raising KeyError - s = Series(range(5), [-2, -1, 1, 2, 3]) - - with catch_warnings(record=True): - result1 = s.ix[-10:3] - result2 = s.loc[-10:3] - tm.assert_series_equal(result1, result2) - - with catch_warnings(record=True): - result1 = s.ix[0:3] - result2 = s.loc[0:3] - tm.assert_series_equal(result1, result2) - - def test_ix_weird_slicing(self): - # http://stackoverflow.com/q/17056560/1240268 - df = DataFrame({"one": [1, 2, 3, np.nan, np.nan], "two": [1, 2, 3, 4, 5]}) - df.loc[df["one"] > 1, "two"] = -df["two"] - - expected = DataFrame( - { - "one": {0: 1.0, 1: 2.0, 2: 3.0, 3: np.nan, 4: np.nan}, - "two": {0: 1, 1: -2, 2: -3, 3: 4, 4: 5}, - } - ) - tm.assert_frame_equal(df, expected) - - def test_ix_assign_column_mixed(self, float_frame): - # GH #1142 - df = float_frame - df["foo"] = "bar" - - orig = df.loc[:, "B"].copy() - df.loc[:, "B"] = df.loc[:, "B"] + 1 - tm.assert_series_equal(df.B, orig + 1) - - # GH 3668, mixed frame with series value - df = DataFrame({"x": np.arange(10), "y": np.arange(10, 20), "z": "bar"}) - expected = df.copy() - - for i in range(5): - indexer = i * 2 - v = 1000 + i * 200 - expected.loc[indexer, "y"] = v - assert expected.loc[indexer, "y"] == v - - df.loc[df.x % 2 == 0, "y"] = df.loc[df.x % 2 == 0, "y"] * 100 - tm.assert_frame_equal(df, expected) - - # GH 4508, making sure consistency of assignments - df = DataFrame({"a": [1, 2, 3], "b": [0, 1, 2]}) - df.loc[[0, 2], "b"] = [100, -100] - expected = DataFrame({"a": [1, 2, 3], "b": [100, 1, -100]}) - tm.assert_frame_equal(df, expected) - - df = DataFrame({"a": list(range(4))}) - df["b"] = np.nan - df.loc[[1, 3], "b"] = [100, -100] - expected = DataFrame({"a": [0, 1, 2, 3], "b": [np.nan, 100, np.nan, -100]}) - tm.assert_frame_equal(df, expected) - - # ok, but chained assignments are dangerous - # if we turn off chained assignment it will work - with option_context("chained_assignment", None): - df = DataFrame({"a": list(range(4))}) - df["b"] = np.nan - df["b"].loc[[1, 3]] = [100, -100] - tm.assert_frame_equal(df, expected) - - def test_ix_get_set_consistency(self): - - # GH 4544 - # ix/loc get/set not consistent when - # a mixed int/string index - df = DataFrame( - np.arange(16).reshape((4, 4)), - columns=["a", "b", 8, "c"], - index=["e", 7, "f", "g"], - ) - - with catch_warnings(record=True): - assert df.ix["e", 8] == 2 - assert df.loc["e", 8] == 2 - - with catch_warnings(record=True): - df.ix["e", 8] = 42 - assert df.ix["e", 8] == 42 - assert df.loc["e", 8] == 42 - - df.loc["e", 8] = 45 - with catch_warnings(record=True): - assert df.ix["e", 8] == 45 - assert df.loc["e", 8] == 45 - - def test_ix_slicing_strings(self): - # see gh-3836 - data = { - "Classification": ["SA EQUITY CFD", "bbb", "SA EQUITY", "SA SSF", "aaa"], - "Random": [1, 2, 3, 4, 5], - "X": ["correct", "wrong", "correct", "correct", "wrong"], - } - df = DataFrame(data) - x = df[~df.Classification.isin(["SA EQUITY CFD", "SA EQUITY", "SA SSF"])] - with catch_warnings(record=True): - df.ix[x.index, "X"] = df["Classification"] - - expected = DataFrame( - { - "Classification": { - 0: "SA EQUITY CFD", - 1: "bbb", - 2: "SA EQUITY", - 3: "SA SSF", - 4: "aaa", - }, - "Random": {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, - "X": {0: "correct", 1: "bbb", 2: "correct", 3: "correct", 4: "aaa"}, - } - ) # bug was 4: 'bbb' - - tm.assert_frame_equal(df, expected) - - def test_ix_setitem_out_of_bounds_axis_0(self): - df = DataFrame( - np.random.randn(2, 5), - index=["row{i}".format(i=i) for i in range(2)], - columns=["col{i}".format(i=i) for i in range(5)], - ) - with catch_warnings(record=True): - msg = "cannot set by positional indexing with enlargement" - with pytest.raises(ValueError, match=msg): - df.ix[2, 0] = 100 - - def test_ix_setitem_out_of_bounds_axis_1(self): - df = DataFrame( - np.random.randn(5, 2), - index=["row{i}".format(i=i) for i in range(5)], - columns=["col{i}".format(i=i) for i in range(2)], - ) - with catch_warnings(record=True): - msg = "cannot set by positional indexing with enlargement" - with pytest.raises(ValueError, match=msg): - df.ix[0, 2] = 100 - - def test_ix_empty_list_indexer_is_ok(self): - with catch_warnings(record=True): - - df = tm.makeCustomDataframe(5, 2) - # vertical empty - tm.assert_frame_equal( - df.ix[:, []], - df.iloc[:, :0], - check_index_type=True, - check_column_type=True, - ) - # horizontal empty - tm.assert_frame_equal( - df.ix[[], :], - df.iloc[:0, :], - check_index_type=True, - check_column_type=True, - ) - # horizontal empty - tm.assert_frame_equal( - df.ix[[]], df.iloc[:0, :], check_index_type=True, check_column_type=True - ) - - def test_ix_duplicate_returns_series(self): - df = DataFrame( - np.random.randn(3, 3), index=[0.1, 0.2, 0.2], columns=list("abc") - ) - with catch_warnings(record=True): - r = df.ix[0.2, "a"] - e = df.loc[0.2, "a"] - tm.assert_series_equal(r, e) - - def test_ix_intervalindex(self): - # https://github.com/pandas-dev/pandas/issues/27865 - df = DataFrame( - np.random.randn(5, 2), - index=pd.IntervalIndex.from_breaks([-np.inf, 0, 1, 2, 3, np.inf]), - ) - result = df.ix[0:2, 0] - expected = df.iloc[0:2, 0] - tm.assert_series_equal(result, expected) diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index e5e899bfb7f0d..6f20ec649b200 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -1,7 +1,6 @@ """ test label based indexing with loc """ from io import StringIO import re -from warnings import catch_warnings, filterwarnings import numpy as np import pytest @@ -96,18 +95,12 @@ def test_loc_setitem_slice(self): def test_loc_getitem_int(self): # int label - self.check_result("loc", 2, "ix", 2, typs=["ints", "uints"], axes=0) - self.check_result("loc", 3, "ix", 3, typs=["ints", "uints"], axes=1) - self.check_result("loc", 2, "ix", 2, typs=["label"], fails=KeyError) + self.check_result("loc", 2, "loc", 2, typs=["label"], fails=KeyError) def test_loc_getitem_label(self): # label - self.check_result("loc", "c", "ix", "c", typs=["labels"], axes=0) - self.check_result("loc", "null", "ix", "null", typs=["mixed"], axes=0) - self.check_result("loc", 8, "ix", 8, typs=["mixed"], axes=0) - self.check_result("loc", Timestamp("20130102"), "ix", 1, typs=["ts"], axes=0) - self.check_result("loc", "c", "ix", "c", typs=["empty"], fails=KeyError) + self.check_result("loc", "c", "loc", "c", typs=["empty"], fails=KeyError) def test_loc_getitem_label_out_of_range(self): @@ -115,49 +108,28 @@ def test_loc_getitem_label_out_of_range(self): self.check_result( "loc", "f", - "ix", + "loc", "f", typs=["ints", "uints", "labels", "mixed", "ts"], fails=KeyError, ) self.check_result("loc", "f", "ix", "f", typs=["floats"], fails=KeyError) + self.check_result("loc", "f", "loc", "f", typs=["floats"], fails=KeyError) self.check_result( - "loc", 20, "ix", 20, typs=["ints", "uints", "mixed"], fails=KeyError, + "loc", 20, "loc", 20, typs=["ints", "uints", "mixed"], fails=KeyError, ) - self.check_result("loc", 20, "ix", 20, typs=["labels"], fails=TypeError) - self.check_result("loc", 20, "ix", 20, typs=["ts"], axes=0, fails=TypeError) - self.check_result("loc", 20, "ix", 20, typs=["floats"], axes=0, fails=KeyError) + self.check_result("loc", 20, "loc", 20, typs=["labels"], fails=TypeError) + self.check_result("loc", 20, "loc", 20, typs=["ts"], axes=0, fails=TypeError) + self.check_result("loc", 20, "loc", 20, typs=["floats"], axes=0, fails=KeyError) def test_loc_getitem_label_list(self): - + # TODO: test something here? # list of labels - self.check_result( - "loc", [0, 2, 4], "ix", [0, 2, 4], typs=["ints", "uints"], axes=0, - ) - self.check_result( - "loc", [3, 6, 9], "ix", [3, 6, 9], typs=["ints", "uints"], axes=1, - ) - self.check_result( - "loc", ["a", "b", "d"], "ix", ["a", "b", "d"], typs=["labels"], axes=0, - ) - self.check_result( - "loc", ["A", "B", "C"], "ix", ["A", "B", "C"], typs=["labels"], axes=1, - ) - self.check_result( - "loc", [2, 8, "null"], "ix", [2, 8, "null"], typs=["mixed"], axes=0, - ) - self.check_result( - "loc", - [Timestamp("20130102"), Timestamp("20130103")], - "ix", - [Timestamp("20130102"), Timestamp("20130103")], - typs=["ts"], - axes=0, - ) + pass def test_loc_getitem_label_list_with_missing(self): self.check_result( - "loc", [0, 1, 2], "indexer", [0, 1, 2], typs=["empty"], fails=KeyError, + "loc", [0, 1, 2], "loc", [0, 1, 2], typs=["empty"], fails=KeyError, ) self.check_result( "loc", @@ -206,7 +178,7 @@ def test_loc_getitem_label_list_fails(self): self.check_result( "loc", [20, 30, 40], - "ix", + "loc", [20, 30, 40], typs=["ints", "uints"], axes=1, @@ -214,35 +186,15 @@ def test_loc_getitem_label_list_fails(self): ) def test_loc_getitem_label_array_like(self): + # TODO: test something? # array like - self.check_result( - "loc", - Series(index=[0, 2, 4], dtype=object).index, - "ix", - [0, 2, 4], - typs=["ints", "uints"], - axes=0, - ) - self.check_result( - "loc", - Series(index=[3, 6, 9], dtype=object).index, - "ix", - [3, 6, 9], - typs=["ints", "uints"], - axes=1, - ) + pass def test_loc_getitem_bool(self): # boolean indexers b = [True, False, True, False] - self.check_result( - "loc", - b, - "ix", - b, - typs=["ints", "uints", "labels", "mixed", "ts", "floats"], - ) - self.check_result("loc", b, "ix", b, typs=["empty"], fails=IndexError) + + self.check_result("loc", b, "loc", b, typs=["empty"], fails=IndexError) @pytest.mark.parametrize("index", [[True, False], [True, False, True, False]]) def test_loc_getitem_bool_diff_len(self, index): @@ -255,14 +207,8 @@ def test_loc_getitem_bool_diff_len(self, index): _ = s.loc[index] def test_loc_getitem_int_slice(self): - - # ok - self.check_result( - "loc", slice(2, 4), "ix", [2, 4], typs=["ints", "uints"], axes=0, - ) - self.check_result( - "loc", slice(3, 6), "ix", [3, 6], typs=["ints", "uints"], axes=1, - ) + # TODO: test something here? + pass def test_loc_to_fail(self): @@ -356,55 +302,34 @@ def test_loc_getitem_list_with_fail(self): def test_loc_getitem_label_slice(self): # label slices (with ints) + + # real label slices + + # GH 14316 + self.check_result( "loc", slice(1, 3), - "ix", + "loc", slice(1, 3), typs=["labels", "mixed", "empty", "ts", "floats"], fails=TypeError, ) - # real label slices - self.check_result( - "loc", slice("a", "c"), "ix", slice("a", "c"), typs=["labels"], axes=0, - ) - self.check_result( - "loc", slice("A", "C"), "ix", slice("A", "C"), typs=["labels"], axes=1, - ) - self.check_result( "loc", slice("20130102", "20130104"), - "ix", - slice("20130102", "20130104"), - typs=["ts"], - axes=0, - ) - self.check_result( "loc", slice("20130102", "20130104"), - "ix", - slice("20130102", "20130104"), typs=["ts"], axes=1, fails=TypeError, ) - # GH 14316 - self.check_result( - "loc", - slice("20130104", "20130102"), - "indexer", - [0, 1, 2], - typs=["ts_rev"], - axes=0, - ) - self.check_result( "loc", slice(2, 8), - "ix", + "loc", slice(2, 8), typs=["mixed"], axes=0, @@ -413,7 +338,7 @@ def test_loc_getitem_label_slice(self): self.check_result( "loc", slice(2, 8), - "ix", + "loc", slice(2, 8), typs=["mixed"], axes=1, @@ -423,7 +348,7 @@ def test_loc_getitem_label_slice(self): self.check_result( "loc", slice(2, 4, 2), - "ix", + "loc", slice(2, 4, 2), typs=["mixed"], axes=0, @@ -898,11 +823,6 @@ def test_loc_name(self): result = df.iloc[[0, 1]].index.name assert result == "index_name" - with catch_warnings(record=True): - filterwarnings("ignore", "\\n.ix", FutureWarning) - result = df.ix[[0, 1]].index.name - assert result == "index_name" - result = df.loc[[0, 1]].index.name assert result == "index_name" diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index 3adc206335e6f..15c65be37e0d9 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -1,11 +1,9 @@ """ test setting *parts* of objects both positionally and label based -TOD: these should be split among the indexer tests +TODO: these should be split among the indexer tests """ -from warnings import catch_warnings - import numpy as np import pytest @@ -15,7 +13,6 @@ class TestPartialSetting: - @pytest.mark.filterwarnings("ignore:\\n.ix:FutureWarning") def test_partial_setting(self): # GH2578, allow ix and friends to partially set @@ -87,32 +84,28 @@ def test_partial_setting(self): # single dtype frame, overwrite expected = DataFrame(dict({"A": [0, 2, 4], "B": [0, 2, 4]})) df = df_orig.copy() - with catch_warnings(record=True): - df.ix[:, "B"] = df.ix[:, "A"] + df.loc[:, "B"] = df.loc[:, "A"] tm.assert_frame_equal(df, expected) # mixed dtype frame, overwrite expected = DataFrame(dict({"A": [0, 2, 4], "B": Series([0, 2, 4])})) df = df_orig.copy() df["B"] = df["B"].astype(np.float64) - with catch_warnings(record=True): - df.ix[:, "B"] = df.ix[:, "A"] + df.loc[:, "B"] = df.loc[:, "A"] tm.assert_frame_equal(df, expected) # single dtype frame, partial setting expected = df_orig.copy() expected["C"] = df["A"] df = df_orig.copy() - with catch_warnings(record=True): - df.ix[:, "C"] = df.ix[:, "A"] + df.loc[:, "C"] = df.loc[:, "A"] tm.assert_frame_equal(df, expected) # mixed frame, partial setting expected = df_orig.copy() expected["C"] = df["A"] df = df_orig.copy() - with catch_warnings(record=True): - df.ix[:, "C"] = df.ix[:, "A"] + df.loc[:, "C"] = df.loc[:, "A"] tm.assert_frame_equal(df, expected) # GH 8473 @@ -328,7 +321,6 @@ def test_series_partial_set_with_name(self): result = ser.iloc[[1, 1, 0, 0]] tm.assert_series_equal(result, expected, check_index_type=True) - @pytest.mark.filterwarnings("ignore:\\n.ix") def test_partial_set_invalid(self): # GH 4940 @@ -339,26 +331,15 @@ def test_partial_set_invalid(self): # don't allow not string inserts with pytest.raises(TypeError): - with catch_warnings(record=True): - df.loc[100.0, :] = df.ix[0] - - with pytest.raises(TypeError): - with catch_warnings(record=True): - df.loc[100, :] = df.ix[0] + df.loc[100.0, :] = df.iloc[0] with pytest.raises(TypeError): - with catch_warnings(record=True): - df.ix[100.0, :] = df.ix[0] - - with pytest.raises(ValueError): - with catch_warnings(record=True): - df.ix[100, :] = df.ix[0] + df.loc[100, :] = df.iloc[0] # allow object conversion here df = orig.copy() - with catch_warnings(record=True): - df.loc["a", :] = df.ix[0] - exp = orig.append(Series(df.ix[0], name="a")) + df.loc["a", :] = df.iloc[0] + exp = orig.append(Series(df.iloc[0], name="a")) tm.assert_frame_equal(df, exp) tm.assert_index_equal(df.index, Index(orig.index.tolist() + ["a"])) assert df.index.dtype == "object" diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py index b41b90cd9afd1..ddaea5b597d6d 100644 --- a/pandas/tests/indexing/test_scalar.py +++ b/pandas/tests/indexing/test_scalar.py @@ -16,7 +16,7 @@ def _check(f, func, values=False): indicies = self.generate_indices(f, values) for i in indicies: result = getattr(f, func)[i] - expected = self.get_value(f, i, values) + expected = self.get_value(func, f, i, values) tm.assert_almost_equal(result, expected) for kind in self._kinds: @@ -44,7 +44,7 @@ def _check(f, func, values=False): indicies = self.generate_indices(f, values) for i in indicies: getattr(f, func)[i] = 1 - expected = self.get_value(f, i, values) + expected = self.get_value(func, f, i, values) tm.assert_almost_equal(expected, 1) for kind in self._kinds: diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 204cdee2d9e1f..ae16d0fa651d2 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -2,7 +2,6 @@ from io import StringIO import itertools from itertools import product -from warnings import catch_warnings, simplefilter import numpy as np from numpy.random import randn @@ -209,11 +208,6 @@ def test_reindex(self): reindexed = self.frame.loc[[("foo", "one"), ("bar", "one")]] tm.assert_frame_equal(reindexed, expected) - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - reindexed = self.frame.ix[[("foo", "one"), ("bar", "one")]] - tm.assert_frame_equal(reindexed, expected) - def test_reindex_preserve_levels(self): new_index = self.ymd.index[::10] chunk = self.ymd.reindex(new_index) @@ -222,11 +216,6 @@ def test_reindex_preserve_levels(self): chunk = self.ymd.loc[new_index] assert chunk.index is new_index - with catch_warnings(record=True): - simplefilter("ignore", FutureWarning) - chunk = self.ymd.ix[new_index] - assert chunk.index is new_index - ymdT = self.ymd.T chunk = ymdT.reindex(columns=new_index) assert chunk.columns is new_index
- [x] Needs release note - [ ] Needs geopandas compat - [x] Need to remove ix asvs
https://api.github.com/repos/pandas-dev/pandas/pulls/27620
2019-07-27T01:45:51Z
2019-12-12T12:15:52Z
2019-12-12T12:15:52Z
2019-12-12T12:16:17Z
Continue simplifying indexing code
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index cdbe0e9d22eb4..9fd956c40c1f0 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2836,11 +2836,13 @@ def __getitem__(self, key): # Do we have a slicer (on rows)? indexer = convert_to_index_sliceable(self, key) if indexer is not None: + # either we have a slice or we have a string that can be converted + # to a slice for partial-string date indexing return self._slice(indexer, axis=0) # Do we have a (boolean) DataFrame? if isinstance(key, DataFrame): - return self._getitem_frame(key) + return self.where(key) # Do we have a (boolean) 1d indexer? if com.is_bool_indexer(key): @@ -2938,11 +2940,6 @@ def _getitem_multilevel(self, key): else: return self._get_item_cache(key) - def _getitem_frame(self, key): - if key.values.size and not is_bool_dtype(key.values): - raise ValueError("Must pass DataFrame with boolean values only") - return self.where(key) - def _get_value(self, index, col, takeable: bool = False): """ Quickly retrieve single value at passed column and index. @@ -2986,6 +2983,8 @@ def __setitem__(self, key, value): # see if we can slice the rows indexer = convert_to_index_sliceable(self, key) if indexer is not None: + # either we have a slice or we have a string that can be converted + # to a slice for partial-string date indexing return self._setitem_slice(indexer, value) if isinstance(key, DataFrame) or getattr(key, "ndim", None) == 2: diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index a1a8619fab892..df89dbe6db6dc 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -117,6 +117,7 @@ def __iter__(self): raise NotImplementedError("ix is not iterable") def __getitem__(self, key): + # Used in ix and downstream in geopandas _CoordinateIndexer if type(key) is tuple: # Note: we check the type exactly instead of with isinstance # because NamedTuple is checked separately. @@ -181,7 +182,7 @@ def _get_setitem_indexer(self, key): pass if isinstance(key, range): - return self._convert_range(key, is_setter=True) + return list(key) axis = self.axis or 0 try: @@ -258,10 +259,6 @@ def _convert_tuple(self, key): keyidx.append(idx) return tuple(keyidx) - def _convert_range(self, key: range, is_setter: bool = False): - """ convert a range argument """ - return list(key) - def _convert_scalar_indexer(self, key, axis: int): # if we are accessing via lowered dim, use the last dim ax = self.obj._get_axis(min(axis, self.ndim - 1)) diff --git a/pandas/core/series.py b/pandas/core/series.py index c7fcab56e1fe5..f840b6ce649b8 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1131,8 +1131,7 @@ def __getitem__(self, key): def _get_with(self, key): # other: fancy integer or otherwise if isinstance(key, slice): - indexer = self.index._convert_slice_indexer(key, kind="getitem") - return self._get_values(indexer) + return self._slice(key) elif isinstance(key, ABCDataFrame): raise TypeError( "Indexing a Series with DataFrame is not " @@ -1148,7 +1147,6 @@ def _get_with(self, key): return self._get_values(key) raise - # pragma: no cover if not isinstance(key, (list, np.ndarray, Series, Index)): key = list(key) @@ -1165,19 +1163,18 @@ def _get_with(self, key): elif key_type == "boolean": return self._get_values(key) - try: - # handle the dup indexing case (GH 4246) - if isinstance(key, (list, tuple)): - return self.loc[key] - - return self.reindex(key) - except Exception: - # [slice(0, 5, None)] will break if you convert to ndarray, - # e.g. as requested by np.median - # hack - if isinstance(key[0], slice): + if isinstance(key, (list, tuple)): + # TODO: de-dup with tuple case handled above? + # handle the dup indexing case GH#4246 + if len(key) == 1 and isinstance(key[0], slice): + # [slice(0, 5, None)] will break if you convert to ndarray, + # e.g. as requested by np.median + # FIXME: hack return self._get_values(key) - raise + + return self.loc[key] + + return self.reindex(key) def _get_values_tuple(self, key): # mpl hackaround @@ -1220,33 +1217,28 @@ def _get_value(self, label, takeable: bool = False): def __setitem__(self, key, value): key = com.apply_if_callable(key, self) + cacher_needs_updating = self._check_is_chained_assignment_possible() - def setitem(key, value): - try: - self._set_with_engine(key, value) - return - except com.SettingWithCopyError: - raise - except (KeyError, ValueError): - values = self._values - if is_integer(key) and not self.index.inferred_type == "integer": - - values[key] = value - return - elif key is Ellipsis: - self[:] = value - return - + try: + self._set_with_engine(key, value) + except com.SettingWithCopyError: + raise + except (KeyError, ValueError): + values = self._values + if is_integer(key) and not self.index.inferred_type == "integer": + values[key] = value + elif key is Ellipsis: + self[:] = value + else: self.loc[key] = value - return - except TypeError as e: - if isinstance(key, tuple) and not isinstance(self.index, MultiIndex): - raise ValueError("Can only tuple-index with a MultiIndex") + except TypeError as e: + if isinstance(key, tuple) and not isinstance(self.index, MultiIndex): + raise ValueError("Can only tuple-index with a MultiIndex") - # python 3 type errors should be raised - if _is_unorderable_exception(e): - raise IndexError(key) + # python 3 type errors should be raised + if _is_unorderable_exception(e): + raise IndexError(key) if com.is_bool_indexer(key): key = check_bool_indexer(self.index, key) @@ -1258,9 +1250,6 @@ def setitem(key, value): self._set_with(key, value) - # do the setitem - cacher_needs_updating = self._check_is_chained_assignment_possible() - setitem(key, value) if cacher_needs_updating: self._maybe_update_cacher() @@ -1282,6 +1271,14 @@ def _set_with(self, key, value): if isinstance(key, slice): indexer = self.index._convert_slice_indexer(key, kind="getitem") return self._set_values(indexer, value) + + elif is_scalar(key) and not is_integer(key) and key not in self.index: + # GH#12862 adding an new key to the Series + # Note: have to exclude integers because that is ambiguously + # position-based + self.loc[key] = value + return + else: if isinstance(key, tuple): try: @@ -1289,13 +1286,6 @@ def _set_with(self, key, value): except Exception: pass - if is_scalar(key) and not is_integer(key) and key not in self.index: - # GH#12862 adding an new key to the Series - # Note: have to exclude integers because that is ambiguously - # position-based - self.loc[key] = value - return - if is_scalar(key): key = [key] elif not isinstance(key, (list, Series, np.ndarray)): @@ -1306,6 +1296,7 @@ def _set_with(self, key, value): if isinstance(key, Index): key_type = key.inferred_type + key = key._values else: key_type = lib.infer_dtype(key, skipna=False) @@ -1320,10 +1311,7 @@ def _set_with(self, key, value): self._set_labels(key, value) def _set_labels(self, key, value): - if isinstance(key, Index): - key = key.values - else: - key = com.asarray_tuplesafe(key) + key = com.asarray_tuplesafe(key) indexer = self.index.get_indexer(key) mask = indexer == -1 if mask.any(): diff --git a/pandas/core/sparse/series.py b/pandas/core/sparse/series.py index fc51c06b149fd..d81cab77f09f5 100644 --- a/pandas/core/sparse/series.py +++ b/pandas/core/sparse/series.py @@ -324,7 +324,7 @@ def _ixs(self, i: int, axis: int = 0): Parameters ---------- i : int - axis: int + axis : int default 0, ignored Returns diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 814a99701b703..ae14563e5952a 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -269,7 +269,7 @@ def test_getitem_boolean( subframe_obj = datetime_frame[indexer_obj] assert_frame_equal(subframe_obj, subframe) - with pytest.raises(ValueError, match="boolean values only"): + with pytest.raises(ValueError, match="Boolean array expected"): datetime_frame[datetime_frame] # test that Series work
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27619
2019-07-27T01:39:24Z
2019-07-27T14:09:37Z
2019-07-27T14:09:37Z
2019-07-27T15:11:12Z
Remove Encoding of values in char** For Labels
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 4decc99087a9e..8e25857e5ad69 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -159,6 +159,7 @@ I/O ^^^ - :meth:`read_csv` now accepts binary mode file buffers when using the Python csv engine (:issue:`23779`) +- Bug in :meth:`DataFrame.to_json` where using a Tuple as a column or index value and using ``orient="columns"`` or ``orient="index"`` would produce invalid JSON (:issue:`20500`) - Plotting diff --git a/pandas/_libs/src/ujson/lib/ultrajson.h b/pandas/_libs/src/ujson/lib/ultrajson.h index 0470fef450dde..ee6e7081bf00e 100644 --- a/pandas/_libs/src/ujson/lib/ultrajson.h +++ b/pandas/_libs/src/ujson/lib/ultrajson.h @@ -307,11 +307,4 @@ EXPORTFUNCTION JSOBJ JSON_DecodeObject(JSONObjectDecoder *dec, const char *buffer, size_t cbBuffer); EXPORTFUNCTION void encode(JSOBJ, JSONObjectEncoder *, const char *, size_t); -#define Buffer_Reserve(__enc, __len) \ - if ((size_t)((__enc)->end - (__enc)->offset) < (size_t)(__len)) { \ - Buffer_Realloc((__enc), (__len)); \ - } - -void Buffer_Realloc(JSONObjectEncoder *enc, size_t cbNeeded); - #endif // PANDAS__LIBS_SRC_UJSON_LIB_ULTRAJSON_H_ diff --git a/pandas/_libs/src/ujson/lib/ultrajsonenc.c b/pandas/_libs/src/ujson/lib/ultrajsonenc.c index 2d6c823a45515..d5b379bee585b 100644 --- a/pandas/_libs/src/ujson/lib/ultrajsonenc.c +++ b/pandas/_libs/src/ujson/lib/ultrajsonenc.c @@ -714,6 +714,12 @@ int Buffer_EscapeStringValidated(JSOBJ obj, JSONObjectEncoder *enc, } } +#define Buffer_Reserve(__enc, __len) \ + if ( (size_t) ((__enc)->end - (__enc)->offset) < (size_t) (__len)) \ + { \ + Buffer_Realloc((__enc), (__len));\ + } \ + #define Buffer_AppendCharUnchecked(__enc, __chr) *((__enc)->offset++) = __chr; FASTCALL_ATTR INLINE_PREFIX void FASTCALL_MSVC strreverse(char *begin, diff --git a/pandas/_libs/src/ujson/python/objToJSON.c b/pandas/_libs/src/ujson/python/objToJSON.c index 926440218b5d9..de336fb3aa1dc 100644 --- a/pandas/_libs/src/ujson/python/objToJSON.c +++ b/pandas/_libs/src/ujson/python/objToJSON.c @@ -48,13 +48,13 @@ Numeric decoder derived from from TCL library #include <../../../tslibs/src/datetime/np_datetime_strings.h> #include "datetime.h" -#define NPY_JSON_BUFSIZE 32768 - static PyTypeObject *type_decimal; static PyTypeObject *cls_dataframe; static PyTypeObject *cls_series; static PyTypeObject *cls_index; static PyTypeObject *cls_nat; +PyObject *cls_timestamp; +PyObject *cls_timedelta; npy_int64 get_nat(void) { return NPY_MIN_INT64; } @@ -166,6 +166,8 @@ void *initObjToJSON(void) cls_index = (PyTypeObject *)PyObject_GetAttrString(mod_pandas, "Index"); cls_series = (PyTypeObject *)PyObject_GetAttrString(mod_pandas, "Series"); + cls_timestamp = PyObject_GetAttrString(mod_pandas, "Timestamp"); + cls_timedelta = PyObject_GetAttrString(mod_pandas, "Timedelta"); Py_DECREF(mod_pandas); } @@ -787,30 +789,23 @@ JSOBJ NpyArr_iterGetValue(JSOBJ obj, JSONTypeContext *tc) { return GET_TC(tc)->itemValue; } -static void NpyArr_getLabel(JSOBJ obj, JSONTypeContext *tc, size_t *outLen, - npy_intp idx, char **labels) { - JSONObjectEncoder *enc = (JSONObjectEncoder *)tc->encoder; - PRINTMARK(); - *outLen = strlen(labels[idx]); - Buffer_Reserve(enc, *outLen); - memcpy(enc->offset, labels[idx], sizeof(char) * (*outLen)); - enc->offset += *outLen; - *outLen = 0; -} - char *NpyArr_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen) { NpyArrContext *npyarr = GET_TC(tc)->npyarr; npy_intp idx; PRINTMARK(); + char *cStr; if (GET_TC(tc)->iterNext == NpyArr_iterNextItem) { idx = npyarr->index[npyarr->stridedim] - 1; - NpyArr_getLabel(obj, tc, outLen, idx, npyarr->columnLabels); + cStr = npyarr->columnLabels[idx]; } else { idx = npyarr->index[npyarr->stridedim - npyarr->inc] - 1; - NpyArr_getLabel(obj, tc, outLen, idx, npyarr->rowLabels); + cStr = npyarr->rowLabels[idx]; } - return NULL; + + *outLen = strlen(cStr); + + return cStr; } //============================================================================= @@ -852,19 +847,22 @@ char *PdBlock_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen) { PdBlockContext *blkCtxt = GET_TC(tc)->pdblock; NpyArrContext *npyarr = blkCtxt->npyCtxts[0]; npy_intp idx; + char *cStr; PRINTMARK(); if (GET_TC(tc)->iterNext == PdBlock_iterNextItem) { idx = blkCtxt->colIdx - 1; - NpyArr_getLabel(obj, tc, outLen, idx, npyarr->columnLabels); + cStr = npyarr->columnLabels[idx]; } else { idx = GET_TC(tc)->iterNext != PdBlock_iterNext ? npyarr->index[npyarr->stridedim - npyarr->inc] - 1 : npyarr->index[npyarr->stridedim]; - NpyArr_getLabel(obj, tc, outLen, idx, npyarr->rowLabels); + cStr = npyarr->rowLabels[idx]; } - return NULL; + + *outLen = strlen(cStr); + return cStr; } char *PdBlock_iterGetName_Transpose(JSOBJ obj, JSONTypeContext *tc, @@ -872,16 +870,19 @@ char *PdBlock_iterGetName_Transpose(JSOBJ obj, JSONTypeContext *tc, PdBlockContext *blkCtxt = GET_TC(tc)->pdblock; NpyArrContext *npyarr = blkCtxt->npyCtxts[blkCtxt->colIdx]; npy_intp idx; + char *cStr; PRINTMARK(); if (GET_TC(tc)->iterNext == NpyArr_iterNextItem) { idx = npyarr->index[npyarr->stridedim] - 1; - NpyArr_getLabel(obj, tc, outLen, idx, npyarr->columnLabels); + cStr = npyarr->columnLabels[idx]; } else { idx = blkCtxt->colIdx; - NpyArr_getLabel(obj, tc, outLen, idx, npyarr->rowLabels); + cStr = npyarr->rowLabels[idx]; } - return NULL; + + *outLen = strlen(cStr); + return cStr; } int PdBlock_iterNext(JSOBJ obj, JSONTypeContext *tc) { @@ -1578,16 +1579,30 @@ void NpyArr_freeLabels(char **labels, npy_intp len) { } } -char **NpyArr_encodeLabels(PyArrayObject *labels, JSONObjectEncoder *enc, +/* + * Function: NpyArr_encodeLabels + * ----------------------------- + * + * Builds an array of "encoded" labels. + * + * labels: PyArrayObject pointer for labels to be "encoded" + * num : number of labels + * + * "encode" is quoted above because we aren't really doing encoding + * For historical reasons this function would actually encode the entire + * array into a separate buffer with a separate call to JSON_Encode + * and would leave it to complex pointer manipulation from there to + * unpack values as needed. To make things simpler and more idiomatic + * this has instead just stringified any input save for datetime values, + * which may need to be represented in various formats. + */ +char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc, npy_intp num) { // NOTE this function steals a reference to labels. - PyObjectEncoder *pyenc = (PyObjectEncoder *)enc; PyObject *item = NULL; - npy_intp i, stride, len, need_quotes; + npy_intp i, stride, len; char **ret; - char *dataptr, *cLabel, *origend, *origst, *origoffset; - char labelBuffer[NPY_JSON_BUFSIZE]; - PyArray_GetItemFunc *getitem; + char *dataptr, *cLabel; int type_num; PRINTMARK(); @@ -1614,68 +1629,136 @@ char **NpyArr_encodeLabels(PyArrayObject *labels, JSONObjectEncoder *enc, ret[i] = NULL; } - origst = enc->start; - origend = enc->end; - origoffset = enc->offset; - stride = PyArray_STRIDE(labels, 0); dataptr = PyArray_DATA(labels); - getitem = (PyArray_GetItemFunc *)PyArray_DESCR(labels)->f->getitem; type_num = PyArray_TYPE(labels); for (i = 0; i < num; i++) { - if (PyTypeNum_ISDATETIME(type_num) || PyTypeNum_ISNUMBER(type_num)) - { - item = (PyObject *)labels; - pyenc->npyType = type_num; - pyenc->npyValue = dataptr; - } else { - item = getitem(dataptr, labels); - if (!item) { - NpyArr_freeLabels(ret, num); - ret = 0; - break; - } - } - - cLabel = JSON_EncodeObject(item, enc, labelBuffer, NPY_JSON_BUFSIZE); - - if (item != (PyObject *)labels) { - Py_DECREF(item); - } - - if (PyErr_Occurred() || enc->errorMsg) { + item = PyArray_GETITEM(labels, dataptr); + if (!item) { + NpyArr_freeLabels(ret, num); + ret = 0; + break; + } + + // TODO: for any matches on type_num (date and timedeltas) should use a + // vectorized solution to convert to epoch or iso formats + if (enc->datetimeIso && (type_num == NPY_TIMEDELTA || PyDelta_Check(item))) { + PyObject *td = PyObject_CallFunction(cls_timedelta, "(O)", item); + if (td == NULL) { + Py_DECREF(item); + NpyArr_freeLabels(ret, num); + ret = 0; + break; + } + + PyObject *iso = PyObject_CallMethod(td, "isoformat", NULL); + Py_DECREF(td); + if (iso == NULL) { + Py_DECREF(item); + NpyArr_freeLabels(ret, num); + ret = 0; + break; + } + + cLabel = (char *)PyUnicode_AsUTF8(iso); + Py_DECREF(iso); + len = strlen(cLabel); + } + else if (PyTypeNum_ISDATETIME(type_num) || + PyDateTime_Check(item) || PyDate_Check(item)) { + PyObject *ts = PyObject_CallFunction(cls_timestamp, "(O)", item); + if (ts == NULL) { + Py_DECREF(item); + NpyArr_freeLabels(ret, num); + ret = 0; + break; + } + + if (enc->datetimeIso) { + PyObject *iso = PyObject_CallMethod(ts, "isoformat", NULL); + Py_DECREF(ts); + if (iso == NULL) { + Py_DECREF(item); + NpyArr_freeLabels(ret, num); + ret = 0; + break; + } + + cLabel = (char *)PyUnicode_AsUTF8(iso); + Py_DECREF(iso); + len = strlen(cLabel); + } else { + npy_int64 value; + // TODO: refactor to not duplicate what goes on in beginTypeContext + if (PyObject_HasAttrString(ts, "value")) { + PRINTMARK(); + value = get_long_attr(ts, "value"); + } else { + PRINTMARK(); + value = + total_seconds(ts) * 1000000000LL; // nanoseconds per second + } + Py_DECREF(ts); + + switch (enc->datetimeUnit) { + case NPY_FR_ns: + break; + case NPY_FR_us: + value /= 1000LL; + break; + case NPY_FR_ms: + value /= 1000000LL; + break; + case NPY_FR_s: + value /= 1000000000LL; + break; + default: + Py_DECREF(item); + NpyArr_freeLabels(ret, num); + ret = 0; + break; + } + + char buf[21] = {0}; // 21 chars for 2**63 as string + cLabel = buf; + sprintf(buf, "%" NPY_INT64_FMT, value); + len = strlen(cLabel); + } + } else { // Fallack to string representation + PyObject *str = PyObject_Str(item); + if (str == NULL) { + Py_DECREF(item); + NpyArr_freeLabels(ret, num); + ret = 0; + break; + } + + cLabel = (char *)PyUnicode_AsUTF8(str); + Py_DECREF(str); + len = strlen(cLabel); + } + + Py_DECREF(item); + // Add 1 to include NULL terminator + ret[i] = PyObject_Malloc(len + 1); + memcpy(ret[i], cLabel, len + 1); + + if (PyErr_Occurred()) { NpyArr_freeLabels(ret, num); ret = 0; break; } - need_quotes = ((*cLabel) != '"'); - len = enc->offset - cLabel + 1 + 2 * need_quotes; - ret[i] = PyObject_Malloc(sizeof(char) * len); - if (!ret[i]) { PyErr_NoMemory(); ret = 0; break; } - if (need_quotes) { - ret[i][0] = '"'; - memcpy(ret[i] + 1, cLabel, sizeof(char) * (len - 4)); - ret[i][len - 3] = '"'; - } else { - memcpy(ret[i], cLabel, sizeof(char) * (len - 2)); - } - ret[i][len - 2] = ':'; - ret[i][len - 1] = '\0'; dataptr += stride; } - enc->start = origst; - enc->end = origend; - enc->offset = origoffset; - Py_DECREF(labels); return ret; } @@ -1972,7 +2055,7 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } pc->columnLabelsLen = PyArray_DIM(pc->newObj, 0); pc->columnLabels = NpyArr_encodeLabels((PyArrayObject *)values, - (JSONObjectEncoder *)enc, + enc, pc->columnLabelsLen); if (!pc->columnLabels) { goto INVALID; @@ -2075,7 +2158,7 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } pc->columnLabelsLen = PyObject_Size(tmpObj); pc->columnLabels = NpyArr_encodeLabels((PyArrayObject *)values, - (JSONObjectEncoder *)enc, + enc, pc->columnLabelsLen); Py_DECREF(tmpObj); if (!pc->columnLabels) { @@ -2098,7 +2181,7 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { pc->rowLabelsLen = PyObject_Size(tmpObj); pc->rowLabels = NpyArr_encodeLabels((PyArrayObject *)values, - (JSONObjectEncoder *)enc, pc->rowLabelsLen); + enc, pc->rowLabelsLen); Py_DECREF(tmpObj); tmpObj = (enc->outputFormat == INDEX ? PyObject_GetAttrString(obj, "columns") @@ -2117,7 +2200,7 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } pc->columnLabelsLen = PyObject_Size(tmpObj); pc->columnLabels = NpyArr_encodeLabels((PyArrayObject *)values, - (JSONObjectEncoder *)enc, + enc, pc->columnLabelsLen); Py_DECREF(tmpObj); if (!pc->columnLabels) { @@ -2429,7 +2512,6 @@ PyObject *objToJSON(PyObject *self, PyObject *args, PyObject *kwargs) { PRINTMARK(); ret = JSON_EncodeObject(oinput, encoder, buffer, sizeof(buffer)); PRINTMARK(); - if (PyErr_Occurred()) { PRINTMARK(); return NULL; diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 9c687f036aa68..9842a706f43d7 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -1012,60 +1012,70 @@ def test_convert_dates_infer(self): result = read_json(dumps(data))[["id", infer_word]] assert_frame_equal(result, expected) - def test_date_format_frame(self): + @pytest.mark.parametrize( + "date,date_unit", + [ + ("20130101 20:43:42.123", None), + ("20130101 20:43:42", "s"), + ("20130101 20:43:42.123", "ms"), + ("20130101 20:43:42.123456", "us"), + ("20130101 20:43:42.123456789", "ns"), + ], + ) + def test_date_format_frame(self, date, date_unit): df = self.tsframe.copy() - def test_w_date(date, date_unit=None): - df["date"] = Timestamp(date) - df.iloc[1, df.columns.get_loc("date")] = pd.NaT - df.iloc[5, df.columns.get_loc("date")] = pd.NaT - if date_unit: - json = df.to_json(date_format="iso", date_unit=date_unit) - else: - json = df.to_json(date_format="iso") - result = read_json(json) - expected = df.copy() - expected.index = expected.index.tz_localize("UTC") - expected["date"] = expected["date"].dt.tz_localize("UTC") - assert_frame_equal(result, expected) - - test_w_date("20130101 20:43:42.123") - test_w_date("20130101 20:43:42", date_unit="s") - test_w_date("20130101 20:43:42.123", date_unit="ms") - test_w_date("20130101 20:43:42.123456", date_unit="us") - test_w_date("20130101 20:43:42.123456789", date_unit="ns") + df["date"] = Timestamp(date) + df.iloc[1, df.columns.get_loc("date")] = pd.NaT + df.iloc[5, df.columns.get_loc("date")] = pd.NaT + if date_unit: + json = df.to_json(date_format="iso", date_unit=date_unit) + else: + json = df.to_json(date_format="iso") + result = read_json(json) + expected = df.copy() + # expected.index = expected.index.tz_localize("UTC") + expected["date"] = expected["date"].dt.tz_localize("UTC") + assert_frame_equal(result, expected) + def test_date_format_frame_raises(self): + df = self.tsframe.copy() msg = "Invalid value 'foo' for option 'date_unit'" with pytest.raises(ValueError, match=msg): df.to_json(date_format="iso", date_unit="foo") - def test_date_format_series(self): - def test_w_date(date, date_unit=None): - ts = Series(Timestamp(date), index=self.ts.index) - ts.iloc[1] = pd.NaT - ts.iloc[5] = pd.NaT - if date_unit: - json = ts.to_json(date_format="iso", date_unit=date_unit) - else: - json = ts.to_json(date_format="iso") - result = read_json(json, typ="series") - expected = ts.copy() - expected.index = expected.index.tz_localize("UTC") - expected = expected.dt.tz_localize("UTC") - assert_series_equal(result, expected) - - test_w_date("20130101 20:43:42.123") - test_w_date("20130101 20:43:42", date_unit="s") - test_w_date("20130101 20:43:42.123", date_unit="ms") - test_w_date("20130101 20:43:42.123456", date_unit="us") - test_w_date("20130101 20:43:42.123456789", date_unit="ns") + @pytest.mark.parametrize( + "date,date_unit", + [ + ("20130101 20:43:42.123", None), + ("20130101 20:43:42", "s"), + ("20130101 20:43:42.123", "ms"), + ("20130101 20:43:42.123456", "us"), + ("20130101 20:43:42.123456789", "ns"), + ], + ) + def test_date_format_series(self, date, date_unit): + ts = Series(Timestamp(date), index=self.ts.index) + ts.iloc[1] = pd.NaT + ts.iloc[5] = pd.NaT + if date_unit: + json = ts.to_json(date_format="iso", date_unit=date_unit) + else: + json = ts.to_json(date_format="iso") + result = read_json(json, typ="series") + expected = ts.copy() + # expected.index = expected.index.tz_localize("UTC") + expected = expected.dt.tz_localize("UTC") + assert_series_equal(result, expected) + def test_date_format_series_raises(self): ts = Series(Timestamp("20130101 20:43:42.123"), index=self.ts.index) msg = "Invalid value 'foo' for option 'date_unit'" with pytest.raises(ValueError, match=msg): ts.to_json(date_format="iso", date_unit="foo") - def test_date_unit(self): + @pytest.mark.parametrize("unit", ["s", "ms", "us", "ns"]) + def test_date_unit(self, unit): df = self.tsframe.copy() df["date"] = Timestamp("20130101 20:43:42") dl = df.columns.get_loc("date") @@ -1073,16 +1083,15 @@ def test_date_unit(self): df.iloc[2, dl] = Timestamp("21460101 20:43:42") df.iloc[4, dl] = pd.NaT - for unit in ("s", "ms", "us", "ns"): - json = df.to_json(date_format="epoch", date_unit=unit) + json = df.to_json(date_format="epoch", date_unit=unit) - # force date unit - result = read_json(json, date_unit=unit) - assert_frame_equal(result, df) + # force date unit + result = read_json(json, date_unit=unit) + assert_frame_equal(result, df) - # detect date unit - result = read_json(json, date_unit=None) - assert_frame_equal(result, df) + # detect date unit + result = read_json(json, date_unit=None) + assert_frame_equal(result, df) def test_weird_nested_json(self): # this used to core dump the parser @@ -1611,3 +1620,30 @@ def test_read_timezone_information(self): ) expected = Series([88], index=DatetimeIndex(["2019-01-01 11:00:00"], tz="UTC")) assert_series_equal(result, expected) + + @pytest.mark.parametrize( + "date_format,key", [("epoch", 86400000), ("iso", "P1DT0H0M0S")] + ) + def test_timedelta_as_label(self, date_format, key): + df = pd.DataFrame([[1]], columns=[pd.Timedelta("1D")]) + expected = '{{"{key}":{{"0":1}}}}'.format(key=key) + result = df.to_json(date_format=date_format) + + assert result == expected + + @pytest.mark.parametrize( + "orient,expected", + [ + ("index", "{\"('a', 'b')\":{\"('c', 'd')\":1}}"), + ("columns", "{\"('c', 'd')\":{\"('a', 'b')\":1}}"), + # TODO: the below have separate encoding procedures + # They produce JSON but not in a consistent manner + pytest.param("split", "", marks=pytest.mark.skip), + pytest.param("table", "", marks=pytest.mark.skip), + ], + ) + def test_tuple_labels(self, orient, expected): + # GH 20500 + df = pd.DataFrame([[1]], index=[("a", "b")], columns=[("c", "d")]) + result = df.to_json(orient=orient) + assert result == expected
- [X] closes #20500 In reviewing this module there is a shared function for object keys and values which encodes objects into a separate buffer and subsequently indexes off of that. Instead of encoding values in a buffer I've updated that function to be a char ** pointing to string representations of the labels (or index / columns, rather). This is arguably a pre-cursor to: 1. #19486 to disentangle date time functions from JSON 2. #12004 to add indent support (tried this previously but vendoring ujson updates but didn't work because of this limitation) 3. #27164 because the various formats may need column / index labels at different points in time, so encoding up front makes that very difficult to reuse The only downside here I haven't been able to figure out is how to deal with date formatting. Right now all labels are written as epochs. I'm sure there is a way to handle but I wasn't clear on what the best way to convert arbitrary input (i.e. object or datetime dtypes) into ISO formats by element where applicable. cc @jbrockmendel in case you have insight on that
https://api.github.com/repos/pandas-dev/pandas/pulls/27618
2019-07-26T23:35:30Z
2019-08-23T22:38:19Z
2019-08-23T22:38:18Z
2019-08-23T22:38:22Z
Move json_normalize to pd namespace
diff --git a/doc/redirects.csv b/doc/redirects.csv index 587a5e9f65b38..0a71f037d23c3 100644 --- a/doc/redirects.csv +++ b/doc/redirects.csv @@ -777,7 +777,7 @@ generated/pandas.io.formats.style.Styler.to_excel,../reference/api/pandas.io.for generated/pandas.io.formats.style.Styler.use,../reference/api/pandas.io.formats.style.Styler.use generated/pandas.io.formats.style.Styler.where,../reference/api/pandas.io.formats.style.Styler.where generated/pandas.io.json.build_table_schema,../reference/api/pandas.io.json.build_table_schema -generated/pandas.io.json.json_normalize,../reference/api/pandas.io.json.json_normalize +generated/pandas.io.json.json_normalize,../reference/api/pandas.json_normalize generated/pandas.io.stata.StataReader.data_label,../reference/api/pandas.io.stata.StataReader.data_label generated/pandas.io.stata.StataReader.value_labels,../reference/api/pandas.io.stata.StataReader.value_labels generated/pandas.io.stata.StataReader.variable_labels,../reference/api/pandas.io.stata.StataReader.variable_labels diff --git a/doc/source/reference/io.rst b/doc/source/reference/io.rst index 50168dec928ab..0037d4a4410c3 100644 --- a/doc/source/reference/io.rst +++ b/doc/source/reference/io.rst @@ -50,13 +50,13 @@ JSON :toctree: api/ read_json + json_normalize .. currentmodule:: pandas.io.json .. autosummary:: :toctree: api/ - json_normalize build_table_schema .. currentmodule:: pandas diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index 52e16c15fc481..ae0f02312e1df 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -2136,27 +2136,26 @@ into a flat table. .. ipython:: python - from pandas.io.json import json_normalize data = [{'id': 1, 'name': {'first': 'Coleen', 'last': 'Volk'}}, {'name': {'given': 'Mose', 'family': 'Regner'}}, {'id': 2, 'name': 'Faye Raker'}] - json_normalize(data) + pd.json_normalize(data) .. ipython:: python data = [{'state': 'Florida', 'shortname': 'FL', 'info': {'governor': 'Rick Scott'}, - 'counties': [{'name': 'Dade', 'population': 12345}, - {'name': 'Broward', 'population': 40000}, - {'name': 'Palm Beach', 'population': 60000}]}, + 'county': [{'name': 'Dade', 'population': 12345}, + {'name': 'Broward', 'population': 40000}, + {'name': 'Palm Beach', 'population': 60000}]}, {'state': 'Ohio', 'shortname': 'OH', 'info': {'governor': 'John Kasich'}, - 'counties': [{'name': 'Summit', 'population': 1234}, - {'name': 'Cuyahoga', 'population': 1337}]}] + 'county': [{'name': 'Summit', 'population': 1234}, + {'name': 'Cuyahoga', 'population': 1337}]}] - json_normalize(data, 'counties', ['state', 'shortname', ['info', 'governor']]) + pd.json_normalize(data, 'county', ['state', 'shortname', ['info', 'governor']]) The max_level parameter provides more control over which level to end normalization. With max_level=1 the following snippet normalizes until 1st nesting level of the provided dict. @@ -2169,7 +2168,7 @@ With max_level=1 the following snippet normalizes until 1st nesting level of the 'Name': 'Name001'}}, 'Image': {'a': 'b'} }] - json_normalize(data, max_level=1) + pd.json_normalize(data, max_level=1) .. _io.jsonl: diff --git a/doc/source/whatsnew/v0.25.0.rst b/doc/source/whatsnew/v0.25.0.rst index be137eaabd40a..b6b91983b8267 100644 --- a/doc/source/whatsnew/v0.25.0.rst +++ b/doc/source/whatsnew/v0.25.0.rst @@ -170,7 +170,7 @@ which level to end normalization (:issue:`23843`): The repr now looks like this: -.. ipython:: python +.. code-block:: ipython from pandas.io.json import json_normalize data = [{ diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst old mode 100755 new mode 100644 index 7554a2fc0b1c2..6ad6b5129ef5a --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -498,6 +498,9 @@ Deprecations - The parameter ``numeric_only`` of :meth:`Categorical.min` and :meth:`Categorical.max` is deprecated and replaced with ``skipna`` (:issue:`25303`) - The parameter ``label`` in :func:`lreshape` has been deprecated and will be removed in a future version (:issue:`29742`) - ``pandas.core.index`` has been deprecated and will be removed in a future version, the public classes are available in the top-level namespace (:issue:`19711`) +- :func:`pandas.json_normalize` is now exposed in the top-level namespace. + Usage of ``json_normalize`` as ``pandas.io.json.json_normalize`` is now deprecated and + it is recommended to use ``json_normalize`` as :func:`pandas.json_normalize` instead (:issue:`27586`). - .. _whatsnew_1000.prior_deprecations: diff --git a/pandas/__init__.py b/pandas/__init__.py index ec367c62de9db..30b7e5bafe1df 100644 --- a/pandas/__init__.py +++ b/pandas/__init__.py @@ -175,6 +175,8 @@ read_spss, ) +from pandas.io.json import _json_normalize as json_normalize + from pandas.util._tester import test import pandas.testing import pandas.arrays diff --git a/pandas/io/json/__init__.py b/pandas/io/json/__init__.py index 2382d993df96b..48febb086c302 100644 --- a/pandas/io/json/__init__.py +++ b/pandas/io/json/__init__.py @@ -1,5 +1,5 @@ from pandas.io.json._json import dumps, loads, read_json, to_json -from pandas.io.json._normalize import json_normalize +from pandas.io.json._normalize import _json_normalize, json_normalize from pandas.io.json._table_schema import build_table_schema __all__ = [ @@ -7,6 +7,7 @@ "loads", "read_json", "to_json", + "_json_normalize", "json_normalize", "build_table_schema", ] diff --git a/pandas/io/json/_normalize.py b/pandas/io/json/_normalize.py index df513d4d37d71..3c9c906939e8f 100644 --- a/pandas/io/json/_normalize.py +++ b/pandas/io/json/_normalize.py @@ -8,6 +8,7 @@ import numpy as np from pandas._libs.writers import convert_json_to_lines +from pandas.util._decorators import deprecate from pandas import DataFrame @@ -108,7 +109,7 @@ def nested_to_record( return new_ds -def json_normalize( +def _json_normalize( data: Union[Dict, List[Dict]], record_path: Optional[Union[str, List]] = None, meta: Optional[Union[str, List]] = None, @@ -332,3 +333,8 @@ def _recursive_extract(data, path, seen_meta, level=0): ) result[k] = np.array(v, dtype=object).repeat(lengths) return result + + +json_normalize = deprecate( + "pandas.io.json.json_normalize", _json_normalize, "1.0.0", "pandas.json_normalize" +) diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index b832440aca99c..900ba878e4c0a 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -170,6 +170,9 @@ class TestPDApi(Base): "read_spss", ] + # top-level json funcs + funcs_json = ["json_normalize"] + # top-level to_* funcs funcs_to = ["to_datetime", "to_numeric", "to_pickle", "to_timedelta"] @@ -209,6 +212,7 @@ def test_api(self): + self.funcs + self.funcs_option + self.funcs_read + + self.funcs_json + self.funcs_to + self.deprecated_funcs_in_future + self.deprecated_funcs diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index c71c52bce87b8..038dd2df4d632 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -3,10 +3,9 @@ import numpy as np import pytest -from pandas import DataFrame, Index +from pandas import DataFrame, Index, json_normalize import pandas.util.testing as tm -from pandas.io.json import json_normalize from pandas.io.json._normalize import nested_to_record @@ -698,3 +697,10 @@ def test_with_large_max_level(self): ] output = nested_to_record(input_data, max_level=max_level) assert output == expected + + def test_deprecated_import(self): + with tm.assert_produces_warning(FutureWarning): + from pandas.io.json import json_normalize + + recs = [{"a": 1, "b": 2, "c": 3}, {"a": 4, "b": 5, "c": 6}] + json_normalize(recs)
- Added a whatsnew entry - Imported pandas.io.json.json_normalize in __init__.py - [x] closes #27586 - [x] whatsnew entry cc: @WillAyd
https://api.github.com/repos/pandas-dev/pandas/pulls/27615
2019-07-26T17:12:09Z
2019-12-18T19:53:18Z
2019-12-18T19:53:17Z
2019-12-18T19:55:50Z
CLN: Fix comment in interval.py
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 7f1aad3ba3261..2a0d2c8770063 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -1206,7 +1206,7 @@ def maybe_convert_platform_interval(values): """ if isinstance(values, (list, tuple)) and len(values) == 0: # GH 19016 - # empty lists/tuples get object dtype by default, but this is not + # empty lists/tuples get object dtype by default, but this is # prohibited for IntervalArray, so coerce to integer instead return np.array([], dtype=np.int64) elif is_categorical_dtype(values):
https://api.github.com/repos/pandas-dev/pandas/pulls/27612
2019-07-26T15:12:28Z
2019-07-26T20:58:56Z
2019-07-26T20:58:56Z
2019-07-26T21:02:41Z
Remove NpyDateTimeToEpoch
diff --git a/pandas/_libs/include/pandas/datetime/date_conversions.h b/pandas/_libs/include/pandas/datetime/date_conversions.h index 42a16f33cc2ea..9a4a02ea89b4d 100644 --- a/pandas/_libs/include/pandas/datetime/date_conversions.h +++ b/pandas/_libs/include/pandas/datetime/date_conversions.h @@ -21,8 +21,4 @@ int scaleNanosecToUnit(npy_int64 *value, NPY_DATETIMEUNIT unit); char *int64ToIso(int64_t value, NPY_DATETIMEUNIT valueUnit, NPY_DATETIMEUNIT base, size_t *len); -// TODO(username): this function doesn't do a lot; should augment or -// replace with scaleNanosecToUnit -npy_datetime NpyDateTimeToEpoch(npy_datetime dt, NPY_DATETIMEUNIT base); - char *int64ToIsoDuration(int64_t value, size_t *len); diff --git a/pandas/_libs/include/pandas/datetime/pd_datetime.h b/pandas/_libs/include/pandas/datetime/pd_datetime.h index 714d264924750..7674fbbe743fe 100644 --- a/pandas/_libs/include/pandas/datetime/pd_datetime.h +++ b/pandas/_libs/include/pandas/datetime/pd_datetime.h @@ -35,7 +35,6 @@ typedef struct { const npy_datetimestruct *); int (*scaleNanosecToUnit)(npy_int64 *, NPY_DATETIMEUNIT); char *(*int64ToIso)(int64_t, NPY_DATETIMEUNIT, NPY_DATETIMEUNIT, size_t *); - npy_datetime (*NpyDateTimeToEpoch)(npy_datetime, NPY_DATETIMEUNIT); char *(*PyDateTimeToIso)(PyObject *, NPY_DATETIMEUNIT, size_t *); npy_datetime (*PyDateTimeToEpoch)(PyObject *, NPY_DATETIMEUNIT); char *(*int64ToIsoDuration)(int64_t, size_t *); diff --git a/pandas/_libs/src/datetime/date_conversions.c b/pandas/_libs/src/datetime/date_conversions.c index 4b172349de8d3..7eaf8aad12f43 100644 --- a/pandas/_libs/src/datetime/date_conversions.c +++ b/pandas/_libs/src/datetime/date_conversions.c @@ -69,11 +69,6 @@ char *int64ToIso(int64_t value, NPY_DATETIMEUNIT valueUnit, return result; } -npy_datetime NpyDateTimeToEpoch(npy_datetime dt, NPY_DATETIMEUNIT base) { - scaleNanosecToUnit(&dt, base); - return dt; -} - /* Converts the int64_t representation of a duration to ISO; mutates len */ char *int64ToIsoDuration(int64_t value, size_t *len) { pandas_timedeltastruct tds; diff --git a/pandas/_libs/src/datetime/pd_datetime.c b/pandas/_libs/src/datetime/pd_datetime.c index b201023114f8a..030d734aeab21 100644 --- a/pandas/_libs/src/datetime/pd_datetime.c +++ b/pandas/_libs/src/datetime/pd_datetime.c @@ -171,14 +171,21 @@ static npy_datetime PyDateTimeToEpoch(PyObject *dt, NPY_DATETIMEUNIT base) { if (!PyErr_Occurred()) { PyErr_SetString(PyExc_ValueError, "Could not convert PyDateTime to numpy datetime"); + + return -1; } - // TODO(username): is setting errMsg required? - // ((JSONObjectEncoder *)tc->encoder)->errorMsg = ""; - // return NULL; } npy_datetime npy_dt = npy_datetimestruct_to_datetime(NPY_FR_ns, &dts); - return NpyDateTimeToEpoch(npy_dt, base); + if (scaleNanosecToUnit(&npy_dt, base) == -1) { + PyErr_Format(PyExc_ValueError, + "Call to scaleNanosecToUnit with value %" NPY_DATETIME_FMT + " and base %d failed", + npy_dt, base); + + return -1; + } + return npy_dt; } static int pandas_datetime_exec(PyObject *module) { @@ -191,7 +198,6 @@ static int pandas_datetime_exec(PyObject *module) { capi->npy_datetimestruct_to_datetime = npy_datetimestruct_to_datetime; capi->scaleNanosecToUnit = scaleNanosecToUnit; capi->int64ToIso = int64ToIso; - capi->NpyDateTimeToEpoch = NpyDateTimeToEpoch; capi->PyDateTimeToIso = PyDateTimeToIso; capi->PyDateTimeToEpoch = PyDateTimeToEpoch; capi->int64ToIsoDuration = int64ToIsoDuration; diff --git a/pandas/_libs/src/vendored/ujson/python/objToJSON.c b/pandas/_libs/src/vendored/ujson/python/objToJSON.c index 6271791fe201e..9f1c1d3f857d1 100644 --- a/pandas/_libs/src/vendored/ujson/python/objToJSON.c +++ b/pandas/_libs/src/vendored/ujson/python/objToJSON.c @@ -1286,8 +1286,12 @@ static char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc, } else { int size_of_cLabel = 21; // 21 chars for int 64 cLabel = PyObject_Malloc(size_of_cLabel); - snprintf(cLabel, size_of_cLabel, "%" NPY_DATETIME_FMT, - NpyDateTimeToEpoch(i8date, base)); + if (scaleNanosecToUnit(&i8date, base) == -1) { + NpyArr_freeLabels(ret, num); + ret = 0; + break; + } + snprintf(cLabel, size_of_cLabel, "%" NPY_DATETIME_FMT, i8date); len = strlen(cLabel); } } @@ -1373,7 +1377,7 @@ static void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { tc->prv = pc; if (PyTypeNum_ISDATETIME(enc->npyType)) { - const int64_t longVal = *(npy_int64 *)enc->npyValue; + int64_t longVal = *(npy_int64 *)enc->npyValue; if (longVal == get_nat()) { tc->type = JT_NULL; } else { @@ -1389,7 +1393,10 @@ static void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { tc->type = JT_UTF8; } else { NPY_DATETIMEUNIT base = ((PyObjectEncoder *)tc->encoder)->datetimeUnit; - pc->longValue = NpyDateTimeToEpoch(longVal, base); + if (scaleNanosecToUnit(&longVal, base) == -1) { + goto INVALID; + } + pc->longValue = longVal; tc->type = JT_LONG; } }
Duplicative of scaleNanosecToUnit but swallows errors
https://api.github.com/repos/pandas-dev/pandas/pulls/56276
2023-12-01T03:38:23Z
2023-12-01T18:34:38Z
2023-12-01T18:34:38Z
2023-12-01T18:34:45Z
Remove inline_helper.h header file
diff --git a/pandas/_libs/include/pandas/inline_helper.h b/pandas/_libs/include/pandas/inline_helper.h deleted file mode 100644 index 1e03da1327470..0000000000000 --- a/pandas/_libs/include/pandas/inline_helper.h +++ /dev/null @@ -1,24 +0,0 @@ -/* -Copyright (c) 2016, PyData Development Team -All rights reserved. - -Distributed under the terms of the BSD Simplified License. - -The full license is in the LICENSE file, distributed with this software. -*/ - -#pragma once - -#ifndef PANDAS_INLINE -#if defined(__clang__) -#define PANDAS_INLINE static __inline__ __attribute__((__unused__)) -#elif defined(__GNUC__) -#define PANDAS_INLINE static __inline__ -#elif defined(_MSC_VER) -#define PANDAS_INLINE static __inline -#elif defined(__STDC_VERSION__) && __STDC_VERSION__ >= 199901L -#define PANDAS_INLINE static inline -#else -#define PANDAS_INLINE -#endif // __GNUC__ -#endif // PANDAS_INLINE diff --git a/pandas/_libs/include/pandas/parser/tokenizer.h b/pandas/_libs/include/pandas/parser/tokenizer.h index 6a46ad637a401..f7e36a2f05a70 100644 --- a/pandas/_libs/include/pandas/parser/tokenizer.h +++ b/pandas/_libs/include/pandas/parser/tokenizer.h @@ -18,7 +18,6 @@ See LICENSE for the license #define ERROR_OVERFLOW 2 #define ERROR_INVALID_CHARS 3 -#include "pandas/inline_helper.h" #include "pandas/portable.h" #include <stdint.h> diff --git a/pandas/_libs/include/pandas/skiplist.h b/pandas/_libs/include/pandas/skiplist.h index d002dba193279..57e304b3a66c0 100644 --- a/pandas/_libs/include/pandas/skiplist.h +++ b/pandas/_libs/include/pandas/skiplist.h @@ -15,13 +15,12 @@ Python recipe (https://rhettinger.wordpress.com/2010/02/06/lost-knowledge/) #pragma once -#include "pandas/inline_helper.h" #include <math.h> #include <stdio.h> #include <stdlib.h> #include <string.h> -PANDAS_INLINE float __skiplist_nanf(void) { +static inline float __skiplist_nanf(void) { const union { int __i; float __f; @@ -30,7 +29,7 @@ PANDAS_INLINE float __skiplist_nanf(void) { } #define PANDAS_NAN ((double)__skiplist_nanf()) -PANDAS_INLINE double Log2(double val) { return log(val) / log(2.); } +static inline double Log2(double val) { return log(val) / log(2.); } typedef struct node_t node_t; @@ -51,13 +50,13 @@ typedef struct { int maxlevels; } skiplist_t; -PANDAS_INLINE double urand(void) { +static inline double urand(void) { return ((double)rand() + 1) / ((double)RAND_MAX + 2); } -PANDAS_INLINE int int_min(int a, int b) { return a < b ? a : b; } +static inline int int_min(int a, int b) { return a < b ? a : b; } -PANDAS_INLINE node_t *node_init(double value, int levels) { +static inline node_t *node_init(double value, int levels) { node_t *result; result = (node_t *)malloc(sizeof(node_t)); if (result) { @@ -78,9 +77,9 @@ PANDAS_INLINE node_t *node_init(double value, int levels) { } // do this ourselves -PANDAS_INLINE void node_incref(node_t *node) { ++(node->ref_count); } +static inline void node_incref(node_t *node) { ++(node->ref_count); } -PANDAS_INLINE void node_decref(node_t *node) { --(node->ref_count); } +static inline void node_decref(node_t *node) { --(node->ref_count); } static void node_destroy(node_t *node) { int i; @@ -100,7 +99,7 @@ static void node_destroy(node_t *node) { } } -PANDAS_INLINE void skiplist_destroy(skiplist_t *skp) { +static inline void skiplist_destroy(skiplist_t *skp) { if (skp) { node_destroy(skp->head); free(skp->tmp_steps); @@ -109,7 +108,7 @@ PANDAS_INLINE void skiplist_destroy(skiplist_t *skp) { } } -PANDAS_INLINE skiplist_t *skiplist_init(int expected_size) { +static inline skiplist_t *skiplist_init(int expected_size) { skiplist_t *result; node_t *NIL, *head; int maxlevels, i; @@ -147,7 +146,7 @@ PANDAS_INLINE skiplist_t *skiplist_init(int expected_size) { } // 1 if left < right, 0 if left == right, -1 if left > right -PANDAS_INLINE int _node_cmp(node_t *node, double value) { +static inline int _node_cmp(node_t *node, double value) { if (node->is_nil || node->value > value) { return -1; } else if (node->value < value) { @@ -157,7 +156,7 @@ PANDAS_INLINE int _node_cmp(node_t *node, double value) { } } -PANDAS_INLINE double skiplist_get(skiplist_t *skp, int i, int *ret) { +static inline double skiplist_get(skiplist_t *skp, int i, int *ret) { node_t *node; int level; @@ -181,7 +180,7 @@ PANDAS_INLINE double skiplist_get(skiplist_t *skp, int i, int *ret) { // Returns the lowest rank of all elements with value `value`, as opposed to the // highest rank returned by `skiplist_insert`. -PANDAS_INLINE int skiplist_min_rank(skiplist_t *skp, double value) { +static inline int skiplist_min_rank(skiplist_t *skp, double value) { node_t *node; int level, rank = 0; @@ -199,7 +198,7 @@ PANDAS_INLINE int skiplist_min_rank(skiplist_t *skp, double value) { // Returns the rank of the inserted element. When there are duplicates, // `rank` is the highest of the group, i.e. the 'max' method of // https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.rank.html -PANDAS_INLINE int skiplist_insert(skiplist_t *skp, double value) { +static inline int skiplist_insert(skiplist_t *skp, double value) { node_t *node, *prevnode, *newnode, *next_at_level; int *steps_at_level; int size, steps, level, rank = 0; @@ -253,7 +252,7 @@ PANDAS_INLINE int skiplist_insert(skiplist_t *skp, double value) { return rank + 1; } -PANDAS_INLINE int skiplist_remove(skiplist_t *skp, double value) { +static inline int skiplist_remove(skiplist_t *skp, double value) { int level, size; node_t *node, *prevnode, *tmpnode, *next_at_level; node_t **chain; diff --git a/pandas/_libs/include/pandas/vendored/klib/khash.h b/pandas/_libs/include/pandas/vendored/klib/khash.h index 31d12a3b30001..f072106e09596 100644 --- a/pandas/_libs/include/pandas/vendored/klib/khash.h +++ b/pandas/_libs/include/pandas/vendored/klib/khash.h @@ -85,7 +85,6 @@ int main() { #define AC_VERSION_KHASH_H "0.2.6" -#include "pandas/inline_helper.h" #include <limits.h> #include <stdlib.h> #include <string.h> @@ -153,7 +152,7 @@ typedef khuint_t khiter_t; // specializations of // https://github.com/aappleby/smhasher/blob/master/src/MurmurHash2.cpp -khuint32_t PANDAS_INLINE murmur2_32to32(khuint32_t k) { +static inline khuint32_t murmur2_32to32(khuint32_t k) { const khuint32_t SEED = 0xc70f6907UL; // 'm' and 'r' are mixing constants generated offline. // They're not really 'magic', they just happen to work well. @@ -186,7 +185,7 @@ khuint32_t PANDAS_INLINE murmur2_32to32(khuint32_t k) { // - no performance difference could be measured compared to a possible // x64-version -khuint32_t PANDAS_INLINE murmur2_32_32to32(khuint32_t k1, khuint32_t k2) { +static inline khuint32_t murmur2_32_32to32(khuint32_t k1, khuint32_t k2) { const khuint32_t SEED = 0xc70f6907UL; // 'm' and 'r' are mixing constants generated offline. // They're not really 'magic', they just happen to work well. @@ -220,7 +219,7 @@ khuint32_t PANDAS_INLINE murmur2_32_32to32(khuint32_t k1, khuint32_t k2) { return h; } -khuint32_t PANDAS_INLINE murmur2_64to32(khuint64_t k) { +static inline khuint32_t murmur2_64to32(khuint64_t k) { khuint32_t k1 = (khuint32_t)k; khuint32_t k2 = (khuint32_t)(k >> 32); @@ -445,7 +444,7 @@ static const double __ac_HASH_UPPER = 0.77; #define KHASH_INIT(name, khkey_t, khval_t, kh_is_map, __hash_func, \ __hash_equal) \ - KHASH_INIT2(name, PANDAS_INLINE, khkey_t, khval_t, kh_is_map, __hash_func, \ + KHASH_INIT2(name, static inline, khkey_t, khval_t, kh_is_map, __hash_func, \ __hash_equal) /* --- BEGIN OF HASH FUNCTIONS --- */ @@ -465,7 +464,7 @@ static const double __ac_HASH_UPPER = 0.77; @param key The integer [khuint64_t] @return The hash value [khuint_t] */ -PANDAS_INLINE khuint_t kh_int64_hash_func(khuint64_t key) { +static inline khuint_t kh_int64_hash_func(khuint64_t key) { return (khuint_t)((key) >> 33 ^ (key) ^ (key) << 11); } /*! @function @@ -478,7 +477,7 @@ PANDAS_INLINE khuint_t kh_int64_hash_func(khuint64_t key) { @param s Pointer to a null terminated string @return The hash value */ -PANDAS_INLINE khuint_t __ac_X31_hash_string(const char *s) { +static inline khuint_t __ac_X31_hash_string(const char *s) { khuint_t h = *s; if (h) for (++s; *s; ++s) @@ -496,7 +495,7 @@ PANDAS_INLINE khuint_t __ac_X31_hash_string(const char *s) { */ #define kh_str_hash_equal(a, b) (strcmp(a, b) == 0) -PANDAS_INLINE khuint_t __ac_Wang_hash(khuint_t key) { +static inline khuint_t __ac_Wang_hash(khuint_t key) { key += ~(key << 15); key ^= (key >> 10); key += (key << 3); diff --git a/pandas/_libs/include/pandas/vendored/klib/khash_python.h b/pandas/_libs/include/pandas/vendored/klib/khash_python.h index dc16a4ada1716..5a933b45d9e21 100644 --- a/pandas/_libs/include/pandas/vendored/klib/khash_python.h +++ b/pandas/_libs/include/pandas/vendored/klib/khash_python.h @@ -83,13 +83,13 @@ void traced_free(void *ptr) { // implementation of dicts, which shines for smaller sizes but is more // predisposed to superlinear running times (see GH 36729 for comparison) -khuint64_t PANDAS_INLINE asuint64(double key) { +static inline khuint64_t asuint64(double key) { khuint64_t val; memcpy(&val, &key, sizeof(double)); return val; } -khuint32_t PANDAS_INLINE asuint32(float key) { +static inline khuint32_t asuint32(float key) { khuint32_t val; memcpy(&val, &key, sizeof(float)); return val; @@ -98,7 +98,7 @@ khuint32_t PANDAS_INLINE asuint32(float key) { #define ZERO_HASH 0 #define NAN_HASH 0 -khuint32_t PANDAS_INLINE kh_float64_hash_func(double val) { +static inline khuint32_t kh_float64_hash_func(double val) { // 0.0 and -0.0 should have the same hash: if (val == 0.0) { return ZERO_HASH; @@ -111,7 +111,7 @@ khuint32_t PANDAS_INLINE kh_float64_hash_func(double val) { return murmur2_64to32(as_int); } -khuint32_t PANDAS_INLINE kh_float32_hash_func(float val) { +static inline khuint32_t kh_float32_hash_func(float val) { // 0.0 and -0.0 should have the same hash: if (val == 0.0f) { return ZERO_HASH; @@ -138,10 +138,10 @@ KHASH_MAP_INIT_FLOAT64(float64, size_t) KHASH_MAP_INIT_FLOAT32(float32, size_t) -khint32_t PANDAS_INLINE kh_complex128_hash_func(khcomplex128_t val) { +static inline khint32_t kh_complex128_hash_func(khcomplex128_t val) { return kh_float64_hash_func(val.real) ^ kh_float64_hash_func(val.imag); } -khint32_t PANDAS_INLINE kh_complex64_hash_func(khcomplex64_t val) { +static inline khint32_t kh_complex64_hash_func(khcomplex64_t val) { return kh_float32_hash_func(val.real) ^ kh_float32_hash_func(val.imag); } @@ -164,7 +164,7 @@ KHASH_MAP_INIT_COMPLEX128(complex128, size_t) #define kh_exist_complex128(h, k) (kh_exist(h, k)) // NaN-floats should be in the same equivalency class, see GH 22119 -int PANDAS_INLINE floatobject_cmp(PyFloatObject *a, PyFloatObject *b) { +static inline int floatobject_cmp(PyFloatObject *a, PyFloatObject *b) { return (Py_IS_NAN(PyFloat_AS_DOUBLE(a)) && Py_IS_NAN(PyFloat_AS_DOUBLE(b))) || (PyFloat_AS_DOUBLE(a) == PyFloat_AS_DOUBLE(b)); } @@ -172,7 +172,7 @@ int PANDAS_INLINE floatobject_cmp(PyFloatObject *a, PyFloatObject *b) { // NaNs should be in the same equivalency class, see GH 41836 // PyObject_RichCompareBool for complexobjects has a different behavior // needs to be replaced -int PANDAS_INLINE complexobject_cmp(PyComplexObject *a, PyComplexObject *b) { +static inline int complexobject_cmp(PyComplexObject *a, PyComplexObject *b) { return (Py_IS_NAN(a->cval.real) && Py_IS_NAN(b->cval.real) && Py_IS_NAN(a->cval.imag) && Py_IS_NAN(b->cval.imag)) || (Py_IS_NAN(a->cval.real) && Py_IS_NAN(b->cval.real) && @@ -182,12 +182,12 @@ int PANDAS_INLINE complexobject_cmp(PyComplexObject *a, PyComplexObject *b) { (a->cval.real == b->cval.real && a->cval.imag == b->cval.imag); } -int PANDAS_INLINE pyobject_cmp(PyObject *a, PyObject *b); +static inline int pyobject_cmp(PyObject *a, PyObject *b); // replacing PyObject_RichCompareBool (NaN!=NaN) with pyobject_cmp (NaN==NaN), // which treats NaNs as equivalent // see GH 41836 -int PANDAS_INLINE tupleobject_cmp(PyTupleObject *a, PyTupleObject *b) { +static inline int tupleobject_cmp(PyTupleObject *a, PyTupleObject *b) { Py_ssize_t i; if (Py_SIZE(a) != Py_SIZE(b)) { @@ -202,7 +202,7 @@ int PANDAS_INLINE tupleobject_cmp(PyTupleObject *a, PyTupleObject *b) { return 1; } -int PANDAS_INLINE pyobject_cmp(PyObject *a, PyObject *b) { +static inline int pyobject_cmp(PyObject *a, PyObject *b) { if (a == b) { return 1; } @@ -230,7 +230,7 @@ int PANDAS_INLINE pyobject_cmp(PyObject *a, PyObject *b) { return result; } -Py_hash_t PANDAS_INLINE _Pandas_HashDouble(double val) { +static inline Py_hash_t _Pandas_HashDouble(double val) { // Since Python3.10, nan is no longer has hash 0 if (Py_IS_NAN(val)) { return 0; @@ -242,14 +242,14 @@ Py_hash_t PANDAS_INLINE _Pandas_HashDouble(double val) { #endif } -Py_hash_t PANDAS_INLINE floatobject_hash(PyFloatObject *key) { +static inline Py_hash_t floatobject_hash(PyFloatObject *key) { return _Pandas_HashDouble(PyFloat_AS_DOUBLE(key)); } #define _PandasHASH_IMAG 1000003UL // replaces _Py_HashDouble with _Pandas_HashDouble -Py_hash_t PANDAS_INLINE complexobject_hash(PyComplexObject *key) { +static inline Py_hash_t complexobject_hash(PyComplexObject *key) { Py_uhash_t realhash = (Py_uhash_t)_Pandas_HashDouble(key->cval.real); Py_uhash_t imaghash = (Py_uhash_t)_Pandas_HashDouble(key->cval.imag); if (realhash == (Py_uhash_t)-1 || imaghash == (Py_uhash_t)-1) { @@ -262,7 +262,7 @@ Py_hash_t PANDAS_INLINE complexobject_hash(PyComplexObject *key) { return (Py_hash_t)combined; } -khuint32_t PANDAS_INLINE kh_python_hash_func(PyObject *key); +static inline khuint32_t kh_python_hash_func(PyObject *key); // we could use any hashing algorithm, this is the original CPython's for tuples @@ -280,7 +280,7 @@ khuint32_t PANDAS_INLINE kh_python_hash_func(PyObject *key); ((x << 13) | (x >> 19)) /* Rotate left 13 bits */ #endif -Py_hash_t PANDAS_INLINE tupleobject_hash(PyTupleObject *key) { +static inline Py_hash_t tupleobject_hash(PyTupleObject *key) { Py_ssize_t i, len = Py_SIZE(key); PyObject **item = key->ob_item; @@ -304,7 +304,7 @@ Py_hash_t PANDAS_INLINE tupleobject_hash(PyTupleObject *key) { return acc; } -khuint32_t PANDAS_INLINE kh_python_hash_func(PyObject *key) { +static inline khuint32_t kh_python_hash_func(PyObject *key) { Py_hash_t hash; // For PyObject_Hash holds: // hash(0.0) == 0 == hash(-0.0) @@ -373,14 +373,14 @@ typedef struct { typedef kh_str_starts_t *p_kh_str_starts_t; -p_kh_str_starts_t PANDAS_INLINE kh_init_str_starts(void) { +static inline p_kh_str_starts_t kh_init_str_starts(void) { kh_str_starts_t *result = (kh_str_starts_t *)KHASH_CALLOC(1, sizeof(kh_str_starts_t)); result->table = kh_init_str(); return result; } -khuint_t PANDAS_INLINE kh_put_str_starts_item(kh_str_starts_t *table, char *key, +static inline khuint_t kh_put_str_starts_item(kh_str_starts_t *table, char *key, int *ret) { khuint_t result = kh_put_str(table->table, key, ret); if (*ret != 0) { @@ -389,7 +389,7 @@ khuint_t PANDAS_INLINE kh_put_str_starts_item(kh_str_starts_t *table, char *key, return result; } -khuint_t PANDAS_INLINE kh_get_str_starts_item(const kh_str_starts_t *table, +static inline khuint_t kh_get_str_starts_item(const kh_str_starts_t *table, const char *key) { unsigned char ch = *key; if (table->starts[ch]) { @@ -399,18 +399,18 @@ khuint_t PANDAS_INLINE kh_get_str_starts_item(const kh_str_starts_t *table, return 0; } -void PANDAS_INLINE kh_destroy_str_starts(kh_str_starts_t *table) { +static inline void kh_destroy_str_starts(kh_str_starts_t *table) { kh_destroy_str(table->table); KHASH_FREE(table); } -void PANDAS_INLINE kh_resize_str_starts(kh_str_starts_t *table, khuint_t val) { +static inline void kh_resize_str_starts(kh_str_starts_t *table, khuint_t val) { kh_resize_str(table->table, val); } // utility function: given the number of elements // returns number of necessary buckets -khuint_t PANDAS_INLINE kh_needed_n_buckets(khuint_t n_elements) { +static inline khuint_t kh_needed_n_buckets(khuint_t n_elements) { khuint_t candidate = n_elements; kroundup32(candidate); khuint_t upper_bound = (khuint_t)(candidate * __ac_HASH_UPPER + 0.5); diff --git a/pandas/_libs/src/parser/tokenizer.c b/pandas/_libs/src/parser/tokenizer.c index c9466c485ae94..f3d976841808c 100644 --- a/pandas/_libs/src/parser/tokenizer.c +++ b/pandas/_libs/src/parser/tokenizer.c @@ -343,7 +343,7 @@ static int push_char(parser_t *self, char c) { return 0; } -int PANDAS_INLINE end_field(parser_t *self) { +static inline int end_field(parser_t *self) { // XXX cruft if (self->words_len >= self->words_cap) { TRACE(("end_field: ERROR!!! self->words_len(%zu) >= "
`inline` is a part of C99, so we don't need to define a helper for it anymore (we now require a C11 compiler)
https://api.github.com/repos/pandas-dev/pandas/pulls/56275
2023-12-01T02:56:43Z
2023-12-01T18:35:36Z
2023-12-01T18:35:36Z
2023-12-01T18:35:43Z
Clean up tokenizer / parser files
diff --git a/pandas/_libs/include/pandas/parser/io.h b/pandas/_libs/include/pandas/parser/io.h index cbe6bc04b7663..c707c23b567d2 100644 --- a/pandas/_libs/include/pandas/parser/io.h +++ b/pandas/_libs/include/pandas/parser/io.h @@ -25,7 +25,7 @@ typedef struct _rd_source { void *new_rd_source(PyObject *obj); -int del_rd_source(void *src); +void del_rd_source(void *src); -void *buffer_rd_bytes(void *source, size_t nbytes, size_t *bytes_read, +char *buffer_rd_bytes(void *source, size_t nbytes, size_t *bytes_read, int *status, const char *encoding_errors); diff --git a/pandas/_libs/include/pandas/parser/pd_parser.h b/pandas/_libs/include/pandas/parser/pd_parser.h index 61f15dcef8d27..58a09ae1bba39 100644 --- a/pandas/_libs/include/pandas/parser/pd_parser.h +++ b/pandas/_libs/include/pandas/parser/pd_parser.h @@ -20,8 +20,8 @@ typedef struct { int (*to_double)(char *, double *, char, char, int *); int (*floatify)(PyObject *, double *, int *); void *(*new_rd_source)(PyObject *); - int (*del_rd_source)(void *); - void *(*buffer_rd_bytes)(void *, size_t, size_t *, int *, const char *); + void (*del_rd_source)(void *); + char *(*buffer_rd_bytes)(void *, size_t, size_t *, int *, const char *); void (*uint_state_init)(uint_state *); int (*uint64_conflict)(uint_state *); void (*coliter_setup)(coliter_t *, parser_t *, int64_t, int64_t); @@ -30,7 +30,7 @@ typedef struct { void (*parser_free)(parser_t *); void (*parser_del)(parser_t *); int (*parser_add_skiprow)(parser_t *, int64_t); - int (*parser_set_skipfirstnrows)(parser_t *, int64_t); + void (*parser_set_skipfirstnrows)(parser_t *, int64_t); void (*parser_set_default_options)(parser_t *); int (*parser_consume_rows)(parser_t *, size_t); int (*parser_trim_buffers)(parser_t *); diff --git a/pandas/_libs/include/pandas/parser/tokenizer.h b/pandas/_libs/include/pandas/parser/tokenizer.h index 6a46ad637a401..ade783e3716de 100644 --- a/pandas/_libs/include/pandas/parser/tokenizer.h +++ b/pandas/_libs/include/pandas/parser/tokenizer.h @@ -84,9 +84,9 @@ typedef enum { typedef enum { ERROR, WARN, SKIP } BadLineHandleMethod; -typedef void *(*io_callback)(void *src, size_t nbytes, size_t *bytes_read, +typedef char *(*io_callback)(void *src, size_t nbytes, size_t *bytes_read, int *status, const char *encoding_errors); -typedef int (*io_cleanup)(void *src); +typedef void (*io_cleanup)(void *src); typedef struct parser_t { void *source; @@ -187,7 +187,7 @@ int parser_trim_buffers(parser_t *self); int parser_add_skiprow(parser_t *self, int64_t row); -int parser_set_skipfirstnrows(parser_t *self, int64_t nrows); +void parser_set_skipfirstnrows(parser_t *self, int64_t nrows); void parser_free(parser_t *self); diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index ab28b34be58f2..204b242d9eb73 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -152,9 +152,9 @@ cdef extern from "pandas/parser/tokenizer.h": WARN, SKIP - ctypedef void* (*io_callback)(void *src, size_t nbytes, size_t *bytes_read, + ctypedef char* (*io_callback)(void *src, size_t nbytes, size_t *bytes_read, int *status, const char *encoding_errors) - ctypedef int (*io_cleanup)(void *src) + ctypedef void (*io_cleanup)(void *src) ctypedef struct parser_t: void *source @@ -247,9 +247,9 @@ cdef extern from "pandas/parser/tokenizer.h": cdef extern from "pandas/parser/pd_parser.h": void *new_rd_source(object obj) except NULL - int del_rd_source(void *src) + void del_rd_source(void *src) - void* buffer_rd_bytes(void *source, size_t nbytes, + char* buffer_rd_bytes(void *source, size_t nbytes, size_t *bytes_read, int *status, const char *encoding_errors) void uint_state_init(uint_state *self) @@ -266,7 +266,7 @@ cdef extern from "pandas/parser/pd_parser.h": void parser_del(parser_t *self) nogil int parser_add_skiprow(parser_t *self, int64_t row) - int parser_set_skipfirstnrows(parser_t *self, int64_t nrows) + void parser_set_skipfirstnrows(parser_t *self, int64_t nrows) void parser_set_default_options(parser_t *self) @@ -318,13 +318,13 @@ cdef double round_trip_wrapper(const char *p, char **q, char decimal, return round_trip(p, q, decimal, sci, tsep, skip_trailing, error, maybe_int) -cdef void* buffer_rd_bytes_wrapper(void *source, size_t nbytes, +cdef char* buffer_rd_bytes_wrapper(void *source, size_t nbytes, size_t *bytes_read, int *status, const char *encoding_errors) noexcept: return buffer_rd_bytes(source, nbytes, bytes_read, status, encoding_errors) -cdef int del_rd_source_wrapper(void *src) noexcept: - return del_rd_source(src) +cdef void del_rd_source_wrapper(void *src) noexcept: + del_rd_source(src) cdef class TextReader: diff --git a/pandas/_libs/src/parser/io.c b/pandas/_libs/src/parser/io.c index 29c2c8d095907..851901481d222 100644 --- a/pandas/_libs/src/parser/io.c +++ b/pandas/_libs/src/parser/io.c @@ -35,12 +35,10 @@ void *new_rd_source(PyObject *obj) { */ -int del_rd_source(void *rds) { +void del_rd_source(void *rds) { Py_XDECREF(RDS(rds)->obj); Py_XDECREF(RDS(rds)->buffer); free(rds); - - return 0; } /* @@ -49,26 +47,20 @@ int del_rd_source(void *rds) { */ -void *buffer_rd_bytes(void *source, size_t nbytes, size_t *bytes_read, +char *buffer_rd_bytes(void *source, size_t nbytes, size_t *bytes_read, int *status, const char *encoding_errors) { - PyGILState_STATE state; - PyObject *result, *func, *args, *tmp; - - void *retval; - - size_t length; rd_source *src = RDS(source); - state = PyGILState_Ensure(); + PyGILState_STATE state = PyGILState_Ensure(); /* delete old object */ Py_XDECREF(src->buffer); src->buffer = NULL; - args = Py_BuildValue("(i)", nbytes); + PyObject *args = Py_BuildValue("(i)", nbytes); - func = PyObject_GetAttrString(src->obj, "read"); + PyObject *func = PyObject_GetAttrString(src->obj, "read"); /* Note: PyObject_CallObject requires the GIL */ - result = PyObject_CallObject(func, args); + PyObject *result = PyObject_CallObject(func, args); Py_XDECREF(args); Py_XDECREF(func); @@ -78,7 +70,7 @@ void *buffer_rd_bytes(void *source, size_t nbytes, size_t *bytes_read, *status = CALLING_READ_FAILED; return NULL; } else if (!PyBytes_Check(result)) { - tmp = PyUnicode_AsEncodedString(result, "utf-8", encoding_errors); + PyObject *tmp = PyUnicode_AsEncodedString(result, "utf-8", encoding_errors); Py_DECREF(result); if (tmp == NULL) { PyGILState_Release(state); @@ -87,7 +79,7 @@ void *buffer_rd_bytes(void *source, size_t nbytes, size_t *bytes_read, result = tmp; } - length = PySequence_Length(result); + const size_t length = PySequence_Length(result); if (length == 0) *status = REACHED_EOF; @@ -96,7 +88,7 @@ void *buffer_rd_bytes(void *source, size_t nbytes, size_t *bytes_read, /* hang on to the Python object */ src->buffer = result; - retval = (void *)PyBytes_AsString(result); + char *retval = PyBytes_AsString(result); PyGILState_Release(state); diff --git a/pandas/_libs/src/parser/pd_parser.c b/pandas/_libs/src/parser/pd_parser.c index 41689704ccffc..88b6603c3c6f9 100644 --- a/pandas/_libs/src/parser/pd_parser.c +++ b/pandas/_libs/src/parser/pd_parser.c @@ -24,7 +24,6 @@ static int to_double(char *item, double *p_value, char sci, char decimal, } static int floatify(PyObject *str, double *result, int *maybe_int) { - int status; char *data; PyObject *tmp = NULL; const char sci = 'E'; @@ -43,7 +42,7 @@ static int floatify(PyObject *str, double *result, int *maybe_int) { return -1; } - status = to_double(data, result, sci, dec, maybe_int); + const int status = to_double(data, result, sci, dec, maybe_int); if (!status) { /* handle inf/-inf infinity/-infinity */ diff --git a/pandas/_libs/src/parser/tokenizer.c b/pandas/_libs/src/parser/tokenizer.c index c9466c485ae94..efe448b034806 100644 --- a/pandas/_libs/src/parser/tokenizer.c +++ b/pandas/_libs/src/parser/tokenizer.c @@ -22,6 +22,7 @@ GitHub. See Python Software Foundation License and BSD licenses for these. #include <ctype.h> #include <float.h> #include <math.h> +#include <stdbool.h> #include "pandas/portable.h" @@ -107,18 +108,7 @@ void parser_set_default_options(parser_t *self) { parser_t *parser_new(void) { return (parser_t *)calloc(1, sizeof(parser_t)); } -int parser_clear_data_buffers(parser_t *self) { - free_if_not_null((void *)&self->stream); - free_if_not_null((void *)&self->words); - free_if_not_null((void *)&self->word_starts); - free_if_not_null((void *)&self->line_start); - free_if_not_null((void *)&self->line_fields); - return 0; -} - -int parser_cleanup(parser_t *self) { - int status = 0; - +static void parser_cleanup(parser_t *self) { // XXX where to put this free_if_not_null((void *)&self->error_msg); free_if_not_null((void *)&self->warn_msg); @@ -128,23 +118,13 @@ int parser_cleanup(parser_t *self) { self->skipset = NULL; } - if (parser_clear_data_buffers(self) < 0) { - status = -1; - } - if (self->cb_cleanup != NULL) { - if (self->cb_cleanup(self->source) < 0) { - status = -1; - } + self->cb_cleanup(self->source); self->cb_cleanup = NULL; } - - return status; } int parser_init(parser_t *self) { - int64_t sz; - /* Initialize data buffers */ @@ -167,8 +147,9 @@ int parser_init(parser_t *self) { self->stream_len = 0; // word pointers and metadata - sz = STREAM_INIT_SIZE / 10; - sz = sz ? sz : 1; + _Static_assert(STREAM_INIT_SIZE / 10 > 0, + "STREAM_INIT_SIZE must be defined and >= 10"); + const int64_t sz = STREAM_INIT_SIZE / 10; self->words = malloc(sz * sizeof(char *)); self->word_starts = malloc(sz * sizeof(int64_t)); self->max_words_cap = sz; @@ -220,17 +201,14 @@ void parser_free(parser_t *self) { void parser_del(parser_t *self) { free(self); } static int make_stream_space(parser_t *self, size_t nbytes) { - uint64_t i, cap, length; - int status; - void *orig_ptr, *newptr; - // Can we fit potentially nbytes tokens (+ null terminators) in the stream? /* TOKEN STREAM */ - orig_ptr = (void *)self->stream; + int status; + char *orig_ptr = (void *)self->stream; TRACE(("\n\nmake_stream_space: nbytes = %zu. grow_buffer(self->stream...)\n", nbytes)) self->stream = @@ -248,7 +226,7 @@ static int make_stream_space(parser_t *self, size_t nbytes) { if (self->stream != orig_ptr) { self->pword_start = self->stream + self->word_start; - for (i = 0; i < self->words_len; ++i) { + for (uint64_t i = 0; i < self->words_len; ++i) { self->words[i] = self->stream + self->word_starts[i]; } } @@ -257,7 +235,7 @@ static int make_stream_space(parser_t *self, size_t nbytes) { WORD VECTORS */ - cap = self->words_cap; + const uint64_t words_cap = self->words_cap; /** * If we are reading in chunks, we need to be aware of the maximum number @@ -267,11 +245,9 @@ static int make_stream_space(parser_t *self, size_t nbytes) { * Otherwise, we risk a buffer overflow if we mistakenly under-allocate * just because a recent chunk did not have as many words. */ - if (self->words_len + nbytes < self->max_words_cap) { - length = self->max_words_cap - nbytes - 1; - } else { - length = self->words_len; - } + const uint64_t length = self->words_len + nbytes < self->max_words_cap + ? self->max_words_cap - nbytes - 1 + : self->words_len; self->words = (char **)grow_buffer((void *)self->words, length, &self->words_cap, @@ -284,23 +260,23 @@ static int make_stream_space(parser_t *self, size_t nbytes) { } // realloc took place - if (cap != self->words_cap) { + if (words_cap != self->words_cap) { TRACE(("make_stream_space: cap != self->words_cap, nbytes = %d, " "self->words_cap=%d\n", nbytes, self->words_cap)) - newptr = - realloc((void *)self->word_starts, sizeof(int64_t) * self->words_cap); + int64_t *newptr = (int64_t *)realloc(self->word_starts, + sizeof(int64_t) * self->words_cap); if (newptr == NULL) { return PARSER_OUT_OF_MEMORY; } else { - self->word_starts = (int64_t *)newptr; + self->word_starts = newptr; } } /* LINE VECTORS */ - cap = self->lines_cap; + const uint64_t lines_cap = self->lines_cap; self->line_start = (int64_t *)grow_buffer((void *)self->line_start, self->lines + 1, &self->lines_cap, nbytes, sizeof(int64_t), &status); @@ -312,14 +288,14 @@ static int make_stream_space(parser_t *self, size_t nbytes) { } // realloc took place - if (cap != self->lines_cap) { + if (lines_cap != self->lines_cap) { TRACE(("make_stream_space: cap != self->lines_cap, nbytes = %d\n", nbytes)) - newptr = - realloc((void *)self->line_fields, sizeof(int64_t) * self->lines_cap); + int64_t *newptr = (int64_t *)realloc(self->line_fields, + sizeof(int64_t) * self->lines_cap); if (newptr == NULL) { return PARSER_OUT_OF_MEMORY; } else { - self->line_fields = (int64_t *)newptr; + self->line_fields = newptr; } } @@ -333,7 +309,7 @@ static int push_char(parser_t *self, char c) { TRACE(("push_char: ERROR!!! self->stream_len(%d) >= " "self->stream_cap(%d)\n", self->stream_len, self->stream_cap)) - int64_t bufsize = 100; + const size_t bufsize = 100; self->error_msg = malloc(bufsize); snprintf(self->error_msg, bufsize, "Buffer overflow caught - possible malformed input file.\n"); @@ -349,7 +325,7 @@ int PANDAS_INLINE end_field(parser_t *self) { TRACE(("end_field: ERROR!!! self->words_len(%zu) >= " "self->words_cap(%zu)\n", self->words_len, self->words_cap)) - int64_t bufsize = 100; + const size_t bufsize = 100; self->error_msg = malloc(bufsize); snprintf(self->error_msg, bufsize, "Buffer overflow caught - possible malformed input file.\n"); @@ -381,30 +357,24 @@ int PANDAS_INLINE end_field(parser_t *self) { } static void append_warning(parser_t *self, const char *msg) { - int64_t ex_length; - int64_t length = strlen(msg); - void *newptr; + const int64_t length = strlen(msg); if (self->warn_msg == NULL) { self->warn_msg = malloc(length + 1); snprintf(self->warn_msg, length + 1, "%s", msg); } else { - ex_length = strlen(self->warn_msg); - newptr = realloc(self->warn_msg, ex_length + length + 1); + const int64_t ex_length = strlen(self->warn_msg); + char *newptr = (char *)realloc(self->warn_msg, ex_length + length + 1); if (newptr != NULL) { - self->warn_msg = (char *)newptr; + self->warn_msg = newptr; snprintf(self->warn_msg + ex_length, length + 1, "%s", msg); } } } static int end_line(parser_t *self) { - char *msg; - int64_t fields; int64_t ex_fields = self->expected_fields; - int64_t bufsize = 100; // for error or warning messages - - fields = self->line_fields[self->lines]; + int64_t fields = self->line_fields[self->lines]; TRACE(("end_line: Line end, nfields: %d\n", fields)); @@ -447,6 +417,7 @@ static int end_line(parser_t *self) { // file_lines is now the actual file line number (starting at 1) if (self->on_bad_lines == ERROR) { + const size_t bufsize = 100; self->error_msg = malloc(bufsize); snprintf(self->error_msg, bufsize, "Expected %" PRId64 " fields in line %" PRIu64 ", saw %" PRId64 @@ -460,7 +431,8 @@ static int end_line(parser_t *self) { // simply skip bad lines if (self->on_bad_lines == WARN) { // pass up error message - msg = malloc(bufsize); + const size_t bufsize = 100; + char *msg = (char *)malloc(bufsize); snprintf(msg, bufsize, "Skipping line %" PRIu64 ": expected %" PRId64 " fields, saw %" PRId64 "\n", @@ -474,7 +446,7 @@ static int end_line(parser_t *self) { if ((self->lines >= self->header_end + 1) && fields < ex_fields) { // might overrun the buffer when closing fields if (make_stream_space(self, ex_fields - fields) < 0) { - int64_t bufsize = 100; + const size_t bufsize = 100; self->error_msg = malloc(bufsize); snprintf(self->error_msg, bufsize, "out of memory"); return -1; @@ -494,7 +466,7 @@ static int end_line(parser_t *self) { if (self->lines >= self->lines_cap) { TRACE(("end_line: ERROR!!! self->lines(%zu) >= self->lines_cap(%zu)\n", self->lines, self->lines_cap)) - int64_t bufsize = 100; + const size_t bufsize = 100; self->error_msg = malloc(bufsize); snprintf(self->error_msg, bufsize, "Buffer overflow caught - " @@ -532,13 +504,11 @@ int parser_add_skiprow(parser_t *self, int64_t row) { return 0; } -int parser_set_skipfirstnrows(parser_t *self, int64_t nrows) { +void parser_set_skipfirstnrows(parser_t *self, int64_t nrows) { // self->file_lines is zero based so subtract 1 from nrows if (nrows > 0) { self->skip_first_N_rows = nrows - 1; } - - return 0; } static int parser_buffer_bytes(parser_t *self, size_t nbytes, @@ -556,7 +526,7 @@ static int parser_buffer_bytes(parser_t *self, size_t nbytes, self->datalen = bytes_read; if (status != REACHED_EOF && self->data == NULL) { - int64_t bufsize = 200; + const size_t bufsize = 200; self->error_msg = malloc(bufsize); if (status == CALLING_READ_FAILED) { @@ -586,7 +556,7 @@ static int parser_buffer_bytes(parser_t *self, size_t nbytes, if (slen >= self->stream_cap) { \ TRACE(("PUSH_CHAR: ERROR!!! slen(%d) >= stream_cap(%d)\n", slen, \ self->stream_cap)) \ - int64_t bufsize = 100; \ + const size_t bufsize = 100; \ self->error_msg = malloc(bufsize); \ snprintf(self->error_msg, bufsize, \ "Buffer overflow caught - possible malformed input file.\n"); \ @@ -664,22 +634,14 @@ static int parser_buffer_bytes(parser_t *self, size_t nbytes, self->datapos += 3; \ } -int skip_this_line(parser_t *self, int64_t rownum) { - int should_skip; - PyObject *result; - PyGILState_STATE state; - +static int skip_this_line(parser_t *self, int64_t rownum) { if (self->skipfunc != NULL) { - state = PyGILState_Ensure(); - result = PyObject_CallFunction(self->skipfunc, "i", rownum); + PyGILState_STATE state = PyGILState_Ensure(); + PyObject *result = PyObject_CallFunction(self->skipfunc, "i", rownum); // Error occurred. It will be processed // and caught at the Cython level. - if (result == NULL) { - should_skip = -1; - } else { - should_skip = PyObject_IsTrue(result); - } + const int should_skip = result == NULL ? -1 : PyObject_IsTrue(result); Py_XDECREF(result); PyGILState_Release(state); @@ -693,12 +655,8 @@ int skip_this_line(parser_t *self, int64_t rownum) { } } -int tokenize_bytes(parser_t *self, size_t line_limit, uint64_t start_lines) { - int64_t i; - uint64_t slen; - int should_skip; - char c; - char *stream; +static int tokenize_bytes(parser_t *self, size_t line_limit, + uint64_t start_lines) { char *buf = self->data + self->datapos; const char lineterminator = @@ -716,14 +674,14 @@ int tokenize_bytes(parser_t *self, size_t line_limit, uint64_t start_lines) { (self->escapechar != '\0') ? self->escapechar : 1000; if (make_stream_space(self, self->datalen - self->datapos) < 0) { - int64_t bufsize = 100; + const size_t bufsize = 100; self->error_msg = malloc(bufsize); snprintf(self->error_msg, bufsize, "out of memory"); return -1; } - stream = self->stream + self->stream_len; - slen = self->stream_len; + char *stream = self->stream + self->stream_len; + uint64_t slen = self->stream_len; TRACE(("%s\n", buf)); @@ -731,6 +689,8 @@ int tokenize_bytes(parser_t *self, size_t line_limit, uint64_t start_lines) { CHECK_FOR_BOM(); } + char c; + int64_t i; for (i = self->datapos; i < self->datalen; ++i) { // next character in file c = *buf++; @@ -840,9 +800,9 @@ int tokenize_bytes(parser_t *self, size_t line_limit, uint64_t start_lines) { break; } - case START_RECORD: + case START_RECORD: { // start of record - should_skip = skip_this_line(self, self->file_lines); + const int should_skip = skip_this_line(self, self->file_lines); if (should_skip == -1) { goto parsingerror; @@ -894,7 +854,7 @@ int tokenize_bytes(parser_t *self, size_t line_limit, uint64_t start_lines) { // normal character - fall through // to handle as START_FIELD self->state = START_FIELD; - + } case START_FIELD: // expecting field if (IS_TERMINATOR(c)) { @@ -1111,7 +1071,7 @@ int tokenize_bytes(parser_t *self, size_t line_limit, uint64_t start_lines) { } static int parser_handle_eof(parser_t *self) { - int64_t bufsize = 100; + const size_t bufsize = 100; TRACE(("handling eof, datalen: %d, pstate: %d\n", self->datalen, self->state)) @@ -1155,9 +1115,6 @@ static int parser_handle_eof(parser_t *self) { } int parser_consume_rows(parser_t *self, size_t nrows) { - int64_t offset, word_deletions; - uint64_t char_count, i; - if (nrows > self->lines) { nrows = self->lines; } @@ -1167,15 +1124,15 @@ int parser_consume_rows(parser_t *self, size_t nrows) { return 0; /* cannot guarantee that nrows + 1 has been observed */ - word_deletions = self->line_start[nrows - 1] + self->line_fields[nrows - 1]; - if (word_deletions >= 1) { - char_count = (self->word_starts[word_deletions - 1] + - strlen(self->words[word_deletions - 1]) + 1); - } else { - /* if word_deletions == 0 (i.e. this case) then char_count must - * be 0 too, as no data needs to be skipped */ - char_count = 0; - } + const int64_t word_deletions = + self->line_start[nrows - 1] + self->line_fields[nrows - 1]; + + /* if word_deletions == 0 (i.e. this case) then char_count must + * be 0 too, as no data needs to be skipped */ + const int64_t char_count = word_deletions >= 1 + ? (self->word_starts[word_deletions - 1] + + strlen(self->words[word_deletions - 1]) + 1) + : 0; TRACE(("parser_consume_rows: Deleting %d words, %d chars\n", word_deletions, char_count)); @@ -1191,7 +1148,8 @@ int parser_consume_rows(parser_t *self, size_t nrows) { /* move token metadata */ // Note: We should always have words_len < word_deletions, so this // subtraction will remain appropriately-typed. - for (i = 0; i < self->words_len - word_deletions; ++i) { + int64_t offset; + for (uint64_t i = 0; i < self->words_len - word_deletions; ++i) { offset = i + word_deletions; self->words[i] = self->words[offset] - char_count; @@ -1206,7 +1164,7 @@ int parser_consume_rows(parser_t *self, size_t nrows) { /* move line metadata */ // Note: We should always have self->lines - nrows + 1 >= 0, so this // subtraction will remain appropriately-typed. - for (i = 0; i < self->lines - nrows + 1; ++i) { + for (uint64_t i = 0; i < self->lines - nrows + 1; ++i) { offset = i + nrows; self->line_start[i] = self->line_start[offset] - word_deletions; self->line_fields[i] = self->line_fields[offset]; @@ -1227,10 +1185,6 @@ int parser_trim_buffers(parser_t *self) { /* Free memory */ - size_t new_cap; - void *newptr; - - uint64_t i; /** * Before we free up space and trim, we should @@ -1246,7 +1200,7 @@ int parser_trim_buffers(parser_t *self) { } /* trim words, word_starts */ - new_cap = _next_pow2(self->words_len) + 1; + size_t new_cap = _next_pow2(self->words_len) + 1; if (new_cap < self->words_cap) { TRACE(("parser_trim_buffers: new_cap < self->words_cap\n")); self->words = realloc(self->words, new_cap * sizeof(char *)); @@ -1268,7 +1222,7 @@ int parser_trim_buffers(parser_t *self) { if (new_cap < self->stream_cap) { TRACE(("parser_trim_buffers: new_cap < self->stream_cap, calling " "realloc\n")); - newptr = realloc(self->stream, new_cap); + void *newptr = realloc(self->stream, new_cap); if (newptr == NULL) { return PARSER_OUT_OF_MEMORY; } else { @@ -1280,7 +1234,7 @@ int parser_trim_buffers(parser_t *self) { if (self->stream != newptr) { self->pword_start = (char *)newptr + self->word_start; - for (i = 0; i < self->words_len; ++i) { + for (uint64_t i = 0; i < self->words_len; ++i) { self->words[i] = (char *)newptr + self->word_starts[i]; } } @@ -1294,7 +1248,7 @@ int parser_trim_buffers(parser_t *self) { new_cap = _next_pow2(self->lines) + 1; if (new_cap < self->lines_cap) { TRACE(("parser_trim_buffers: new_cap < self->lines_cap\n")); - newptr = realloc(self->line_start, new_cap * sizeof(int64_t)); + void *newptr = realloc(self->line_start, new_cap * sizeof(int64_t)); if (newptr == NULL) { return PARSER_OUT_OF_MEMORY; } else { @@ -1317,10 +1271,10 @@ int parser_trim_buffers(parser_t *self) { all : tokenize all the data vs. certain number of rows */ -int _tokenize_helper(parser_t *self, size_t nrows, int all, - const char *encoding_errors) { +static int _tokenize_helper(parser_t *self, size_t nrows, int all, + const char *encoding_errors) { int status = 0; - uint64_t start_lines = self->lines; + const uint64_t start_lines = self->lines; if (self->state == FINISHED) { return 0; @@ -1367,13 +1321,11 @@ int _tokenize_helper(parser_t *self, size_t nrows, int all, } int tokenize_nrows(parser_t *self, size_t nrows, const char *encoding_errors) { - int status = _tokenize_helper(self, nrows, 0, encoding_errors); - return status; + return _tokenize_helper(self, nrows, 0, encoding_errors); } int tokenize_all_rows(parser_t *self, const char *encoding_errors) { - int status = _tokenize_helper(self, -1, 1, encoding_errors); - return status; + return _tokenize_helper(self, -1, 1, encoding_errors); } /* @@ -1449,22 +1401,9 @@ int to_boolean(const char *item, uint8_t *val) { // * Add tsep argument for thousands separator // -// pessimistic but quick assessment, -// assuming that each decimal digit requires 4 bits to store -const int max_int_decimal_digits = (sizeof(unsigned int) * 8) / 4; - double xstrtod(const char *str, char **endptr, char decimal, char sci, char tsep, int skip_trailing, int *error, int *maybe_int) { - double number; - unsigned int i_number = 0; - int exponent; - int negative; - char *p = (char *)str; - double p10; - int n; - int num_digits; - int num_decimals; - + const char *p = str; if (maybe_int != NULL) *maybe_int = 1; // Skip leading whitespace. @@ -1472,7 +1411,7 @@ double xstrtod(const char *str, char **endptr, char decimal, char sci, p++; // Handle optional sign. - negative = 0; + int negative = 0; switch (*p) { case '-': negative = 1; // Fall through to increment position. @@ -1480,11 +1419,17 @@ double xstrtod(const char *str, char **endptr, char decimal, char sci, p++; } - exponent = 0; - num_digits = 0; - num_decimals = 0; + int exponent = 0; + int num_digits = 0; + int num_decimals = 0; + + // pessimistic but quick assessment, + // assuming that each decimal digit requires 4 bits to store + // TODO: C23 has UINT64_WIDTH macro that can be used at compile time + const int max_int_decimal_digits = (sizeof(unsigned int) * 8) / 4; // Process string of digits. + unsigned int i_number = 0; while (isdigit_ascii(*p) && num_digits <= max_int_decimal_digits) { i_number = i_number * 10 + (*p - '0'); p++; @@ -1492,7 +1437,7 @@ double xstrtod(const char *str, char **endptr, char decimal, char sci, p += (tsep != '\0' && *p == tsep); } - number = i_number; + double number = i_number; if (num_digits > max_int_decimal_digits) { // process what's left as double @@ -1546,7 +1491,7 @@ double xstrtod(const char *str, char **endptr, char decimal, char sci, // Process string of digits. num_digits = 0; - n = 0; + int n = 0; while (isdigit_ascii(*p)) { n = n * 10 + (*p - '0'); num_digits++; @@ -1569,8 +1514,8 @@ double xstrtod(const char *str, char **endptr, char decimal, char sci, } // Scale the result. - p10 = 10.; - n = exponent; + double p10 = 10.; + int n = exponent; if (n < 0) n = -n; while (n) { @@ -1595,21 +1540,15 @@ double xstrtod(const char *str, char **endptr, char decimal, char sci, } if (endptr) - *endptr = p; + *endptr = (char *)p; return number; } double precise_xstrtod(const char *str, char **endptr, char decimal, char sci, char tsep, int skip_trailing, int *error, int *maybe_int) { - double number; - int exponent; - int negative; - char *p = (char *)str; - int num_digits; - int num_decimals; - int max_digits = 17; - int n; + const char *p = str; + const int max_digits = 17; if (maybe_int != NULL) *maybe_int = 1; @@ -1652,7 +1591,7 @@ double precise_xstrtod(const char *str, char **endptr, char decimal, char sci, p++; // Handle optional sign. - negative = 0; + int negative = 0; switch (*p) { case '-': negative = 1; // Fall through to increment position. @@ -1660,10 +1599,10 @@ double precise_xstrtod(const char *str, char **endptr, char decimal, char sci, p++; } - number = 0.; - exponent = 0; - num_digits = 0; - num_decimals = 0; + double number = 0.; + int exponent = 0; + int num_digits = 0; + int num_decimals = 0; // Process string of digits. while (isdigit_ascii(*p)) { @@ -1723,7 +1662,7 @@ double precise_xstrtod(const char *str, char **endptr, char decimal, char sci, // Process string of digits. num_digits = 0; - n = 0; + int n = 0; while (num_digits < max_digits && isdigit_ascii(*p)) { n = n * 10 + (*p - '0'); num_digits++; @@ -1767,7 +1706,7 @@ double precise_xstrtod(const char *str, char **endptr, char decimal, char sci, } if (endptr) - *endptr = p; + *endptr = (char *)p; return number; } @@ -1777,10 +1716,10 @@ double precise_xstrtod(const char *str, char **endptr, char decimal, char sci, with a call to `free`. */ -char *_str_copy_decimal_str_c(const char *s, char **endpos, char decimal, - char tsep) { +static char *_str_copy_decimal_str_c(const char *s, char **endpos, char decimal, + char tsep) { const char *p = s; - size_t length = strlen(s); + const size_t length = strlen(s); char *s_copy = malloc(length + 1); char *dst = s_copy; // Skip leading whitespace. @@ -1830,10 +1769,9 @@ double round_trip(const char *p, char **q, char decimal, char sci, char tsep, char *pc = _str_copy_decimal_str_c(p, &endptr, decimal, tsep); // This is called from a nogil block in parsers.pyx // so need to explicitly get GIL before Python calls - PyGILState_STATE gstate; - gstate = PyGILState_Ensure(); + PyGILState_STATE gstate = PyGILState_Ensure(); char *endpc; - double r = PyOS_string_to_double(pc, &endpc, 0); + const double r = PyOS_string_to_double(pc, &endpc, 0); // PyOS_string_to_double needs to consume the whole string if (endpc == pc + strlen(pc)) { if (q != NULL) { @@ -1882,20 +1820,15 @@ int uint64_conflict(uint_state *self) { int64_t str_to_int64(const char *p_item, int64_t int_min, int64_t int_max, int *error, char tsep) { const char *p = p_item; - int isneg = 0; - int64_t number = 0; - int d; - // Skip leading spaces. while (isspace_ascii(*p)) { ++p; } // Handle sign. - if (*p == '-') { - isneg = 1; - ++p; - } else if (*p == '+') { + const bool isneg = *p == '-' ? true : false; + // Handle sign. + if (isneg || (*p == '+')) { p++; } @@ -1906,6 +1839,7 @@ int64_t str_to_int64(const char *p_item, int64_t int_min, int64_t int_max, return 0; } + int64_t number = 0; if (isneg) { // If number is greater than pre_min, at least one more digit // can be processed without overflowing. @@ -1913,7 +1847,7 @@ int64_t str_to_int64(const char *p_item, int64_t int_min, int64_t int_max, int64_t pre_min = int_min / 10; // Process the digits. - d = *p; + char d = *p; if (tsep != '\0') { while (1) { if (d == tsep) { @@ -1950,7 +1884,7 @@ int64_t str_to_int64(const char *p_item, int64_t int_min, int64_t int_max, int dig_pre_max = int_max % 10; // Process the digits. - d = *p; + char d = *p; if (tsep != '\0') { while (1) { if (d == tsep) { @@ -2002,11 +1936,6 @@ int64_t str_to_int64(const char *p_item, int64_t int_min, int64_t int_max, uint64_t str_to_uint64(uint_state *state, const char *p_item, int64_t int_max, uint64_t uint_max, int *error, char tsep) { const char *p = p_item; - uint64_t pre_max = uint_max / 10; - int dig_pre_max = uint_max % 10; - uint64_t number = 0; - int d; - // Skip leading spaces. while (isspace_ascii(*p)) { ++p; @@ -2032,7 +1961,10 @@ uint64_t str_to_uint64(uint_state *state, const char *p_item, int64_t int_max, // can be processed without overflowing. // // Process the digits. - d = *p; + uint64_t number = 0; + const uint64_t pre_max = uint_max / 10; + const uint64_t dig_pre_max = uint_max % 10; + char d = *p; if (tsep != '\0') { while (1) { if (d == tsep) {
Same pattern as before - remove C89 constructs, add const / static where possible This has an added tweak to remove unnecessary int return values from destructors
https://api.github.com/repos/pandas-dev/pandas/pulls/56274
2023-12-01T01:37:36Z
2023-12-01T18:36:42Z
2023-12-01T18:36:42Z
2023-12-01T23:25:09Z
TST/CLN: Remove makeTime methods
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index ead00cd778d7b..676757d8e095f 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -6,7 +6,6 @@ import operator import os import re -import string from sys import byteorder from typing import ( TYPE_CHECKING, @@ -109,7 +108,6 @@ from pandas.core.arrays import ArrowExtensionArray _N = 30 -_K = 4 UNSIGNED_INT_NUMPY_DTYPES: list[NpDtype] = ["uint8", "uint16", "uint32", "uint64"] UNSIGNED_INT_EA_DTYPES: list[Dtype] = ["UInt8", "UInt16", "UInt32", "UInt64"] @@ -341,10 +339,6 @@ def to_array(obj): # Others -def getCols(k) -> str: - return string.ascii_uppercase[:k] - - def makeTimeSeries(nper=None, freq: Frequency = "B", name=None) -> Series: if nper is None: nper = _N @@ -355,16 +349,6 @@ def makeTimeSeries(nper=None, freq: Frequency = "B", name=None) -> Series: ) -def getTimeSeriesData(nper=None, freq: Frequency = "B") -> dict[str, Series]: - return {c: makeTimeSeries(nper, freq) for c in getCols(_K)} - - -# make frame -def makeTimeDataFrame(nper=None, freq: Frequency = "B") -> DataFrame: - data = getTimeSeriesData(nper, freq) - return DataFrame(data) - - def makeCustomIndex( nentries, nlevels, @@ -887,7 +871,6 @@ def shares_memory(left, right) -> bool: "external_error_raised", "FLOAT_EA_DTYPES", "FLOAT_NUMPY_DTYPES", - "getCols", "get_cython_table_params", "get_dtype", "getitem", @@ -895,13 +878,11 @@ def shares_memory(left, right) -> bool: "get_finest_unit", "get_obj", "get_op_from_name", - "getTimeSeriesData", "iat", "iloc", "loc", "makeCustomDataframe", "makeCustomIndex", - "makeTimeDataFrame", "makeTimeSeries", "maybe_produces_warning", "NARROW_NP_DTYPES", diff --git a/pandas/conftest.py b/pandas/conftest.py index 9ed6f8f43ae03..6401d4b5981e0 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -550,7 +550,11 @@ def multiindex_year_month_day_dataframe_random_data(): DataFrame with 3 level MultiIndex (year, month, day) covering first 100 business days from 2000-01-01 with random data """ - tdf = tm.makeTimeDataFrame(100) + tdf = DataFrame( + np.random.default_rng(2).standard_normal((100, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=100, freq="B"), + ) ymd = tdf.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]).sum() # use int64 Index, to make sure things work ymd.index = ymd.index.set_levels([lev.astype("i8") for lev in ymd.index.levels]) diff --git a/pandas/tests/frame/conftest.py b/pandas/tests/frame/conftest.py index 99ea565e5b60c..e07024b2e2a09 100644 --- a/pandas/tests/frame/conftest.py +++ b/pandas/tests/frame/conftest.py @@ -7,7 +7,6 @@ NaT, date_range, ) -import pandas._testing as tm @pytest.fixture @@ -16,27 +15,12 @@ def datetime_frame() -> DataFrame: Fixture for DataFrame of floats with DatetimeIndex Columns are ['A', 'B', 'C', 'D'] - - A B C D - 2000-01-03 -1.122153 0.468535 0.122226 1.693711 - 2000-01-04 0.189378 0.486100 0.007864 -1.216052 - 2000-01-05 0.041401 -0.835752 -0.035279 -0.414357 - 2000-01-06 0.430050 0.894352 0.090719 0.036939 - 2000-01-07 -0.620982 -0.668211 -0.706153 1.466335 - 2000-01-10 -0.752633 0.328434 -0.815325 0.699674 - 2000-01-11 -2.236969 0.615737 -0.829076 -1.196106 - ... ... ... ... ... - 2000-02-03 1.642618 -0.579288 0.046005 1.385249 - 2000-02-04 -0.544873 -1.160962 -0.284071 -1.418351 - 2000-02-07 -2.656149 -0.601387 1.410148 0.444150 - 2000-02-08 -1.201881 -1.289040 0.772992 -1.445300 - 2000-02-09 1.377373 0.398619 1.008453 -0.928207 - 2000-02-10 0.473194 -0.636677 0.984058 0.511519 - 2000-02-11 -0.965556 0.408313 -1.312844 -0.381948 - - [30 rows x 4 columns] """ - return DataFrame(tm.getTimeSeriesData()) + return DataFrame( + np.random.default_rng(2).standard_normal((100, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=100, freq="B"), + ) @pytest.fixture diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 135a86cad1395..dfb4a3092789a 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -584,7 +584,7 @@ def test_fancy_getitem_slice_mixed( tm.assert_frame_equal(float_frame, original) def test_getitem_setitem_non_ix_labels(self): - df = tm.makeTimeDataFrame() + df = DataFrame(range(20), index=date_range("2020-01-01", periods=20)) start, end = df.index[[5, 10]] diff --git a/pandas/tests/frame/methods/test_cov_corr.py b/pandas/tests/frame/methods/test_cov_corr.py index 359e9122b0c0b..108816697ef3e 100644 --- a/pandas/tests/frame/methods/test_cov_corr.py +++ b/pandas/tests/frame/methods/test_cov_corr.py @@ -6,7 +6,9 @@ import pandas as pd from pandas import ( DataFrame, + Index, Series, + date_range, isna, ) import pandas._testing as tm @@ -325,8 +327,12 @@ def test_corrwith(self, datetime_frame, dtype): tm.assert_almost_equal(correls[row], df1.loc[row].corr(df2.loc[row])) def test_corrwith_with_objects(self): - df1 = tm.makeTimeDataFrame() - df2 = tm.makeTimeDataFrame() + df1 = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + df2 = df1.copy() cols = ["A", "B", "C", "D"] df1["obj"] = "foo" diff --git a/pandas/tests/frame/methods/test_first_and_last.py b/pandas/tests/frame/methods/test_first_and_last.py index 23355a5549a88..212e56442ee07 100644 --- a/pandas/tests/frame/methods/test_first_and_last.py +++ b/pandas/tests/frame/methods/test_first_and_last.py @@ -1,12 +1,15 @@ """ Note: includes tests for `last` """ +import numpy as np import pytest import pandas as pd from pandas import ( DataFrame, + Index, bdate_range, + date_range, ) import pandas._testing as tm @@ -16,13 +19,21 @@ class TestFirst: def test_first_subset(self, frame_or_series): - ts = tm.makeTimeDataFrame(freq="12h") + ts = DataFrame( + np.random.default_rng(2).standard_normal((100, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=100, freq="12h"), + ) ts = tm.get_obj(ts, frame_or_series) with tm.assert_produces_warning(FutureWarning, match=deprecated_msg): result = ts.first("10d") assert len(result) == 20 - ts = tm.makeTimeDataFrame(freq="D") + ts = DataFrame( + np.random.default_rng(2).standard_normal((100, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=100, freq="D"), + ) ts = tm.get_obj(ts, frame_or_series) with tm.assert_produces_warning(FutureWarning, match=deprecated_msg): result = ts.first("10d") @@ -64,13 +75,21 @@ def test_first_last_raises(self, frame_or_series): obj.last("1D") def test_last_subset(self, frame_or_series): - ts = tm.makeTimeDataFrame(freq="12h") + ts = DataFrame( + np.random.default_rng(2).standard_normal((100, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=100, freq="12h"), + ) ts = tm.get_obj(ts, frame_or_series) with tm.assert_produces_warning(FutureWarning, match=last_deprecated_msg): result = ts.last("10d") assert len(result) == 20 - ts = tm.makeTimeDataFrame(nper=30, freq="D") + ts = DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=30, freq="D"), + ) ts = tm.get_obj(ts, frame_or_series) with tm.assert_produces_warning(FutureWarning, match=last_deprecated_msg): result = ts.last("10d") diff --git a/pandas/tests/frame/methods/test_truncate.py b/pandas/tests/frame/methods/test_truncate.py index 4c4b04076c8d5..12077952c2e03 100644 --- a/pandas/tests/frame/methods/test_truncate.py +++ b/pandas/tests/frame/methods/test_truncate.py @@ -60,7 +60,7 @@ def test_truncate(self, datetime_frame, frame_or_series): truncated = ts.truncate(before=ts.index[-1] + ts.index.freq) assert len(truncated) == 0 - msg = "Truncate: 2000-01-06 00:00:00 must be after 2000-02-04 00:00:00" + msg = "Truncate: 2000-01-06 00:00:00 must be after 2000-05-16 00:00:00" with pytest.raises(ValueError, match=msg): ts.truncate( before=ts.index[-1] - ts.index.freq, after=ts.index[0] + ts.index.freq diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 7fd795dc84cca..a4825c80ee815 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -1523,8 +1523,12 @@ def test_combineFunc(self, float_frame, mixed_float_frame): [operator.eq, operator.ne, operator.lt, operator.gt, operator.ge, operator.le], ) def test_comparisons(self, simple_frame, float_frame, func): - df1 = tm.makeTimeDataFrame() - df2 = tm.makeTimeDataFrame() + df1 = DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=30, freq="B"), + ) + df2 = df1.copy() row = simple_frame.xs("a") ndim_5 = np.ones(df1.shape + (1, 1, 1)) diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index 1f08b9d5c35b8..6564e381af0ea 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -10,7 +10,9 @@ from pandas import ( DataFrame, + Index, Series, + date_range, ) import pandas._testing as tm @@ -328,12 +330,16 @@ def test_squeeze_series_noop(self, ser): def test_squeeze_frame_noop(self): # noop - df = tm.makeTimeDataFrame() + df = DataFrame(np.eye(2)) tm.assert_frame_equal(df.squeeze(), df) def test_squeeze_frame_reindex(self): # squeezing - df = tm.makeTimeDataFrame().reindex(columns=["A"]) + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ).reindex(columns=["A"]) tm.assert_series_equal(df.squeeze(), df["A"]) def test_squeeze_0_len_dim(self): @@ -345,7 +351,11 @@ def test_squeeze_0_len_dim(self): def test_squeeze_axis(self): # axis argument - df = tm.makeTimeDataFrame(nper=1).iloc[:, :1] + df = DataFrame( + np.random.default_rng(2).standard_normal((1, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=1, freq="B"), + ).iloc[:, :1] assert df.shape == (1, 1) tm.assert_series_equal(df.squeeze(axis=0), df.iloc[0]) tm.assert_series_equal(df.squeeze(axis="index"), df.iloc[0]) @@ -360,14 +370,22 @@ def test_squeeze_axis(self): df.squeeze(axis="x") def test_squeeze_axis_len_3(self): - df = tm.makeTimeDataFrame(3) + df = DataFrame( + np.random.default_rng(2).standard_normal((3, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=3, freq="B"), + ) tm.assert_frame_equal(df.squeeze(axis=0), df) def test_numpy_squeeze(self): s = Series(range(2), dtype=np.float64) tm.assert_series_equal(np.squeeze(s), s) - df = tm.makeTimeDataFrame().reindex(columns=["A"]) + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ).reindex(columns=["A"]) tm.assert_series_equal(np.squeeze(df), df["A"]) @pytest.mark.parametrize( @@ -382,11 +400,19 @@ def test_transpose_series(self, ser): tm.assert_series_equal(ser.transpose(), ser) def test_transpose_frame(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) tm.assert_frame_equal(df.transpose().transpose(), df) def test_numpy_transpose(self, frame_or_series): - obj = tm.makeTimeDataFrame() + obj = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) obj = tm.get_obj(obj, frame_or_series) if frame_or_series is Series: @@ -419,7 +445,11 @@ def test_take_series(self, ser): def test_take_frame(self): indices = [1, 5, -2, 6, 3, -1] - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) out = df.take(indices) expected = DataFrame( data=df.values.take(indices, axis=0), @@ -431,7 +461,7 @@ def test_take_frame(self): def test_take_invalid_kwargs(self, frame_or_series): indices = [-3, 2, 0, 1] - obj = tm.makeTimeDataFrame() + obj = DataFrame(range(5)) obj = tm.get_obj(obj, frame_or_series) msg = r"take\(\) got an unexpected keyword argument 'foo'" diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 3ba1510cc6b1d..c3bcd30796e63 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -161,7 +161,11 @@ def test_agg_apply_corner(ts, tsframe): def test_agg_grouping_is_list_tuple(ts): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=pd.date_range("2000-01-01", periods=30, freq="B"), + ) grouped = df.groupby(lambda x: x.year) grouper = grouped.grouper.groupings[0].grouping_vector diff --git a/pandas/tests/groupby/conftest.py b/pandas/tests/groupby/conftest.py index b8fb3b7fff676..6d4a874f9d3ec 100644 --- a/pandas/tests/groupby/conftest.py +++ b/pandas/tests/groupby/conftest.py @@ -1,7 +1,11 @@ import numpy as np import pytest -from pandas import DataFrame +from pandas import ( + DataFrame, + Index, + date_range, +) import pandas._testing as tm from pandas.core.groupby.base import ( reduction_kernels, @@ -48,7 +52,11 @@ def ts(): @pytest.fixture def tsframe(): - return DataFrame(tm.getTimeSeriesData()) + return DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=30, freq="B"), + ) @pytest.fixture diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 5b17484de9c93..254a12d9bdebb 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -319,7 +319,11 @@ def test_pass_args_kwargs_duplicate_columns(tsframe, as_index): def test_len(): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]) assert len(grouped) == len(df) @@ -327,6 +331,8 @@ def test_len(): expected = len({(x.year, x.month) for x in df.index}) assert len(grouped) == expected + +def test_len_nan_group(): # issue 11016 df = DataFrame({"a": [np.nan] * 3, "b": [1, 2, 3]}) assert len(df.groupby("a")) == 0 @@ -940,7 +946,11 @@ def test_groupby_as_index_corner(df, ts): def test_groupby_multiple_key(): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]) agged = grouped.sum() tm.assert_almost_equal(df.values, agged.values) @@ -1655,7 +1665,11 @@ def test_dont_clobber_name_column(): def test_skip_group_keys(): - tsf = tm.makeTimeDataFrame() + tsf = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) grouped = tsf.groupby(lambda x: x.month, group_keys=False) result = grouped.apply(lambda x: x.sort_values(by="A")[:3]) diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index a6f160d92fb66..35699fe9647d7 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -10,6 +10,7 @@ from pandas import ( Categorical, DataFrame, + Index, MultiIndex, Series, Timestamp, @@ -67,7 +68,11 @@ def demean(arr): tm.assert_frame_equal(result, expected) # GH 8430 - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((50, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=50, freq="B"), + ) g = df.groupby(pd.Grouper(freq="ME")) g.transform(lambda x: x - 1) @@ -115,7 +120,7 @@ def test_transform_fast2(): ) result = df.groupby("grouping").transform("first") - dates = pd.Index( + dates = Index( [ Timestamp("2014-1-1"), Timestamp("2014-1-2"), diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py index eae7e46c7ec35..d270741a0e0bc 100644 --- a/pandas/tests/indexes/multi/test_indexing.py +++ b/pandas/tests/indexes/multi/test_indexing.py @@ -13,6 +13,7 @@ import pandas as pd from pandas import ( Categorical, + DataFrame, Index, MultiIndex, date_range, @@ -37,7 +38,11 @@ def test_slice_locs_partial(self, idx): assert result == (2, 4) def test_slice_locs(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((50, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=50, freq="B"), + ) stacked = df.stack(future_stack=True) idx = stacked.index @@ -57,7 +62,11 @@ def test_slice_locs(self): tm.assert_almost_equal(sliced.values, expected.values) def test_slice_locs_with_type_mismatch(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) stacked = df.stack(future_stack=True) idx = stacked.index with pytest.raises(TypeError, match="^Level type mismatch"): @@ -861,7 +870,7 @@ def test_timestamp_multiindex_indexer(): [3], ] ) - df = pd.DataFrame({"foo": np.arange(len(idx))}, idx) + df = DataFrame({"foo": np.arange(len(idx))}, idx) result = df.loc[pd.IndexSlice["2019-1-2":, "x", :], "foo"] qidx = MultiIndex.from_product( [ diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index 2f9018112c03b..ca551024b4c1f 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -536,7 +536,11 @@ def test_series_partial_set_with_name(self): @pytest.mark.parametrize("key", [100, 100.0]) def test_setitem_with_expansion_numeric_into_datetimeindex(self, key): # GH#4940 inserting non-strings - orig = tm.makeTimeDataFrame() + orig = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) df = orig.copy() df.loc[key, :] = df.iloc[0] @@ -550,7 +554,11 @@ def test_partial_set_invalid(self): # GH 4940 # allow only setting of 'valid' values - orig = tm.makeTimeDataFrame() + orig = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) # allow object conversion here df = orig.copy() diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 4dfae753edf72..74286a3ddd8ed 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -20,6 +20,7 @@ DataFrame, Index, MultiIndex, + date_range, option_context, ) import pandas._testing as tm @@ -271,7 +272,7 @@ def test_excel_multindex_roundtrip( def test_read_excel_parse_dates(self, ext): # see gh-11544, gh-12051 df = DataFrame( - {"col": [1, 2, 3], "date_strings": pd.date_range("2012-01-01", periods=3)} + {"col": [1, 2, 3], "date_strings": date_range("2012-01-01", periods=3)} ) df2 = df.copy() df2["date_strings"] = df2["date_strings"].dt.strftime("%m/%d/%Y") @@ -460,7 +461,11 @@ def test_mixed(self, frame, path): tm.assert_frame_equal(mixed_frame, recons) def test_ts_frame(self, path): - df = tm.makeTimeDataFrame()[:5] + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=5, freq="B"), + ) # freq doesn't round-trip index = pd.DatetimeIndex(np.asarray(df.index), freq=None) @@ -533,7 +538,11 @@ def test_inf_roundtrip(self, path): def test_sheets(self, frame, path): # freq doesn't round-trip - tsframe = tm.makeTimeDataFrame()[:5] + tsframe = DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=5, freq="B"), + ) index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None) tsframe.index = index @@ -653,7 +662,11 @@ def test_excel_roundtrip_datetime(self, merge_cells, path): # datetime.date, not sure what to test here exactly # freq does not round-trip - tsframe = tm.makeTimeDataFrame()[:5] + tsframe = DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=5, freq="B"), + ) index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None) tsframe.index = index @@ -772,7 +785,11 @@ def test_to_excel_timedelta(self, path): def test_to_excel_periodindex(self, path): # xp has a PeriodIndex - df = tm.makeTimeDataFrame()[:5] + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=5, freq="B"), + ) xp = df.resample("ME").mean().to_period("M") xp.to_excel(path, sheet_name="sht1") @@ -837,7 +854,11 @@ def test_to_excel_multiindex_cols(self, merge_cells, frame, path): def test_to_excel_multiindex_dates(self, merge_cells, path): # try multiindex with dates - tsframe = tm.makeTimeDataFrame()[:5] + tsframe = DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=5, freq="B"), + ) new_index = [tsframe.index, np.arange(len(tsframe.index), dtype=np.int64)] tsframe.index = MultiIndex.from_arrays(new_index) diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 79be90cd00469..428c73c282426 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -23,8 +23,10 @@ NA, DataFrame, DatetimeIndex, + Index, Series, Timestamp, + date_range, read_json, ) import pandas._testing as tm @@ -115,7 +117,11 @@ def datetime_series(self): def datetime_frame(self): # Same as usual datetime_frame, but with index freq set to None, # since that doesn't round-trip, see GH#33711 - df = DataFrame(tm.getTimeSeriesData()) + df = DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=30, freq="B"), + ) df.index = df.index._with_freq(None) return df @@ -266,7 +272,7 @@ def test_roundtrip_empty(self, orient, convert_axes): data = StringIO(empty_frame.to_json(orient=orient)) result = read_json(data, orient=orient, convert_axes=convert_axes) if orient == "split": - idx = pd.Index([], dtype=(float if convert_axes else object)) + idx = Index([], dtype=(float if convert_axes else object)) expected = DataFrame(index=idx, columns=idx) elif orient in ["index", "columns"]: expected = DataFrame() @@ -294,7 +300,7 @@ def test_roundtrip_timestamp(self, orient, convert_axes, datetime_frame): @pytest.mark.parametrize("convert_axes", [True, False]) def test_roundtrip_mixed(self, orient, convert_axes): - index = pd.Index(["a", "b", "c", "d", "e"]) + index = Index(["a", "b", "c", "d", "e"]) values = { "A": [0.0, 1.0, 2.0, 3.0, 4.0], "B": [0.0, 1.0, 0.0, 1.0, 0.0], @@ -495,7 +501,7 @@ def test_frame_mixedtype_orient(self): # GH10289 tm.assert_frame_equal(left, right) def test_v12_compat(self, datapath): - dti = pd.date_range("2000-01-03", "2000-01-07") + dti = date_range("2000-01-03", "2000-01-07") # freq doesn't roundtrip dti = DatetimeIndex(np.asarray(dti), freq=None) df = DataFrame( @@ -525,7 +531,7 @@ def test_v12_compat(self, datapath): tm.assert_frame_equal(df_iso, df_unser_iso, check_column_type=False) def test_blocks_compat_GH9037(self, using_infer_string): - index = pd.date_range("20000101", periods=10, freq="h") + index = date_range("20000101", periods=10, freq="h") # freq doesn't round-trip index = DatetimeIndex(list(index), freq=None) @@ -1034,7 +1040,7 @@ def test_doc_example(self): dfj2["date"] = Timestamp("20130101") dfj2["ints"] = range(5) dfj2["bools"] = True - dfj2.index = pd.date_range("20130101", periods=5) + dfj2.index = date_range("20130101", periods=5) json = StringIO(dfj2.to_json()) result = read_json(json, dtype={"ints": np.int64, "bools": np.bool_}) @@ -1078,7 +1084,7 @@ def test_timedelta(self): result = read_json(StringIO(ser.to_json()), typ="series").apply(converter) tm.assert_series_equal(result, ser) - ser = Series([timedelta(23), timedelta(seconds=5)], index=pd.Index([0, 1])) + ser = Series([timedelta(23), timedelta(seconds=5)], index=Index([0, 1])) assert ser.dtype == "timedelta64[ns]" result = read_json(StringIO(ser.to_json()), typ="series").apply(converter) tm.assert_series_equal(result, ser) @@ -1094,7 +1100,7 @@ def test_timedelta2(self): { "a": [timedelta(days=23), timedelta(seconds=5)], "b": [1, 2], - "c": pd.date_range(start="20130101", periods=2), + "c": date_range(start="20130101", periods=2), } ) data = StringIO(frame.to_json(date_unit="ns")) @@ -1209,10 +1215,10 @@ def test_categorical(self): def test_datetime_tz(self): # GH4377 df.to_json segfaults with non-ndarray blocks - tz_range = pd.date_range("20130101", periods=3, tz="US/Eastern") + tz_range = date_range("20130101", periods=3, tz="US/Eastern") tz_naive = tz_range.tz_convert("utc").tz_localize(None) - df = DataFrame({"A": tz_range, "B": pd.date_range("20130101", periods=3)}) + df = DataFrame({"A": tz_range, "B": date_range("20130101", periods=3)}) df_naive = df.copy() df_naive["A"] = tz_naive @@ -1265,9 +1271,9 @@ def test_tz_is_naive(self): @pytest.mark.parametrize( "tz_range", [ - pd.date_range("2013-01-01 05:00:00Z", periods=2), - pd.date_range("2013-01-01 00:00:00", periods=2, tz="US/Eastern"), - pd.date_range("2013-01-01 00:00:00-0500", periods=2), + date_range("2013-01-01 05:00:00Z", periods=2), + date_range("2013-01-01 00:00:00", periods=2, tz="US/Eastern"), + date_range("2013-01-01 00:00:00-0500", periods=2), ], ) def test_tz_range_is_utc(self, tz_range): @@ -1290,7 +1296,7 @@ def test_tz_range_is_utc(self, tz_range): assert ujson_dumps(df.astype({"DT": object}), iso_dates=True) def test_tz_range_is_naive(self): - dti = pd.date_range("2013-01-01 05:00:00", periods=2) + dti = date_range("2013-01-01 05:00:00", periods=2) exp = '["2013-01-01T05:00:00.000","2013-01-02T05:00:00.000"]' dfexp = '{"DT":{"0":"2013-01-01T05:00:00.000","1":"2013-01-02T05:00:00.000"}}' @@ -1926,7 +1932,7 @@ def test_to_json_multiindex_escape(self): # GH 15273 df = DataFrame( True, - index=pd.date_range("2017-01-20", "2017-01-23"), + index=date_range("2017-01-20", "2017-01-23"), columns=["foo", "bar"], ).stack(future_stack=True) result = df.to_json() @@ -2128,8 +2134,8 @@ def test_json_roundtrip_string_inference(orient): expected = DataFrame( [["a", "b"], ["c", "d"]], dtype="string[pyarrow_numpy]", - index=pd.Index(["row 1", "row 2"], dtype="string[pyarrow_numpy]"), - columns=pd.Index(["col 1", "col 2"], dtype="string[pyarrow_numpy]"), + index=Index(["row 1", "row 2"], dtype="string[pyarrow_numpy]"), + columns=Index(["col 1", "col 2"], dtype="string[pyarrow_numpy]"), ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py index 9eb9ffa53dd22..6cb4a4ad47440 100644 --- a/pandas/tests/io/pytables/test_append.py +++ b/pandas/tests/io/pytables/test_append.py @@ -33,7 +33,11 @@ def test_append(setup_path): with ensure_clean_store(setup_path) as store: # this is allowed by almost always don't want to do it # tables.NaturalNameWarning): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((20, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=20, freq="B"), + ) _maybe_remove(store, "df1") store.append("df1", df[:10]) store.append("df1", df[10:]) @@ -279,7 +283,11 @@ def test_append_all_nans(setup_path): def test_append_frame_column_oriented(setup_path): with ensure_clean_store(setup_path) as store: # column oriented - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) df.index = df.index._with_freq(None) # freq doesn't round-trip _maybe_remove(store, "df1") @@ -427,7 +435,11 @@ def check_col(key, name, size): # with nans _maybe_remove(store, "df") - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) df["string"] = "foo" df.loc[df.index[1:4], "string"] = np.nan df["string2"] = "bar" @@ -487,7 +499,11 @@ def test_append_with_empty_string(setup_path): def test_append_with_data_columns(setup_path): with ensure_clean_store(setup_path) as store: - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) df.iloc[0, df.columns.get_loc("B")] = 1.0 _maybe_remove(store, "df") store.append("df", df[:2], data_columns=["B"]) @@ -854,8 +870,12 @@ def test_append_with_timedelta(setup_path): def test_append_to_multiple(setup_path): - df1 = tm.makeTimeDataFrame() - df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) + df1 = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + df2 = df1.copy().rename(columns="{}_2".format) df2["foo"] = "bar" df = concat([df1, df2], axis=1) @@ -887,8 +907,16 @@ def test_append_to_multiple(setup_path): def test_append_to_multiple_dropna(setup_path): - df1 = tm.makeTimeDataFrame() - df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) + df1 = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + df2 = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ).rename(columns="{}_2".format) df1.iloc[1, df1.columns.get_indexer(["A", "B"])] = np.nan df = concat([df1, df2], axis=1) @@ -904,8 +932,12 @@ def test_append_to_multiple_dropna(setup_path): def test_append_to_multiple_dropna_false(setup_path): - df1 = tm.makeTimeDataFrame() - df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) + df1 = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + df2 = df1.copy().rename(columns="{}_2".format) df1.iloc[1, df1.columns.get_indexer(["A", "B"])] = np.nan df = concat([df1, df2], axis=1) diff --git a/pandas/tests/io/pytables/test_errors.py b/pandas/tests/io/pytables/test_errors.py index d956e4f5775eb..2021101098892 100644 --- a/pandas/tests/io/pytables/test_errors.py +++ b/pandas/tests/io/pytables/test_errors.py @@ -98,7 +98,11 @@ def test_unimplemented_dtypes_table_columns(setup_path): def test_invalid_terms(tmp_path, setup_path): with ensure_clean_store(setup_path) as store: - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) df["string"] = "foo" df.loc[df.index[0:4], "string"] = "bar" diff --git a/pandas/tests/io/pytables/test_file_handling.py b/pandas/tests/io/pytables/test_file_handling.py index 2920f0b07b31e..40397c49f12d2 100644 --- a/pandas/tests/io/pytables/test_file_handling.py +++ b/pandas/tests/io/pytables/test_file_handling.py @@ -20,6 +20,7 @@ Index, Series, _testing as tm, + date_range, read_hdf, ) from pandas.tests.io.pytables.common import ( @@ -36,7 +37,11 @@ @pytest.mark.parametrize("mode", ["r", "r+", "a", "w"]) def test_mode(setup_path, tmp_path, mode): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) msg = r"[\S]* does not exist" path = tmp_path / setup_path @@ -85,7 +90,11 @@ def test_mode(setup_path, tmp_path, mode): def test_default_mode(tmp_path, setup_path): # read_hdf uses default mode - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) path = tmp_path / setup_path df.to_hdf(path, key="df", mode="w") result = read_hdf(path, "df") diff --git a/pandas/tests/io/pytables/test_put.py b/pandas/tests/io/pytables/test_put.py index 8a6e3c9006439..df47bd78c86b8 100644 --- a/pandas/tests/io/pytables/test_put.py +++ b/pandas/tests/io/pytables/test_put.py @@ -97,7 +97,11 @@ def test_api_default_format(tmp_path, setup_path): def test_put(setup_path): with ensure_clean_store(setup_path) as store: ts = tm.makeTimeSeries() - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((20, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=20, freq="B"), + ) store["a"] = ts store["b"] = df[:10] store["foo/bar/bah"] = df[:10] @@ -153,7 +157,11 @@ def test_put_string_index(setup_path): def test_put_compression(setup_path): with ensure_clean_store(setup_path) as store: - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) store.put("c", df, format="table", complib="zlib") tm.assert_frame_equal(store["c"], df) @@ -166,7 +174,11 @@ def test_put_compression(setup_path): @td.skip_if_windows def test_put_compression_blosc(setup_path): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) with ensure_clean_store(setup_path) as store: # can't compress if format='fixed' @@ -179,7 +191,11 @@ def test_put_compression_blosc(setup_path): def test_put_mixed_type(setup_path): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) df["obj1"] = "foo" df["obj2"] = "bar" df["bool1"] = df["A"] > 0 diff --git a/pandas/tests/io/pytables/test_read.py b/pandas/tests/io/pytables/test_read.py index 2030b1eca3203..e4a3ea1fc9db8 100644 --- a/pandas/tests/io/pytables/test_read.py +++ b/pandas/tests/io/pytables/test_read.py @@ -15,6 +15,7 @@ Index, Series, _testing as tm, + date_range, read_hdf, ) from pandas.tests.io.pytables.common import ( @@ -72,7 +73,11 @@ def test_read_missing_key_opened_store(tmp_path, setup_path): def test_read_column(setup_path): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) with ensure_clean_store(setup_path) as store: _maybe_remove(store, "df") diff --git a/pandas/tests/io/pytables/test_round_trip.py b/pandas/tests/io/pytables/test_round_trip.py index 693f10172a99e..2c61da3809010 100644 --- a/pandas/tests/io/pytables/test_round_trip.py +++ b/pandas/tests/io/pytables/test_round_trip.py @@ -15,6 +15,7 @@ Series, _testing as tm, bdate_range, + date_range, read_hdf, ) from pandas.tests.io.pytables.common import ( @@ -372,7 +373,11 @@ def test_frame(compression, setup_path): df, tm.assert_frame_equal, path=setup_path, compression=compression ) - tdf = tm.makeTimeDataFrame() + tdf = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) _check_roundtrip( tdf, tm.assert_frame_equal, path=setup_path, compression=compression ) diff --git a/pandas/tests/io/pytables/test_select.py b/pandas/tests/io/pytables/test_select.py index 3eaa1e86dbf6d..0e303d1c890c5 100644 --- a/pandas/tests/io/pytables/test_select.py +++ b/pandas/tests/io/pytables/test_select.py @@ -130,7 +130,11 @@ def test_select_with_dups(setup_path): def test_select(setup_path): with ensure_clean_store(setup_path) as store: # select with columns= - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) _maybe_remove(store, "df") store.append("df", df) result = store.select("df", columns=["A", "B"]) @@ -331,7 +335,11 @@ def test_select_with_many_inputs(setup_path): def test_select_iterator(tmp_path, setup_path): # single table with ensure_clean_store(setup_path) as store: - df = tm.makeTimeDataFrame(500) + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) _maybe_remove(store, "df") store.append("df", df) @@ -341,33 +349,41 @@ def test_select_iterator(tmp_path, setup_path): result = concat(results) tm.assert_frame_equal(expected, result) - results = list(store.select("df", chunksize=100)) + results = list(store.select("df", chunksize=2)) assert len(results) == 5 result = concat(results) tm.assert_frame_equal(expected, result) - results = list(store.select("df", chunksize=150)) + results = list(store.select("df", chunksize=2)) result = concat(results) tm.assert_frame_equal(result, expected) path = tmp_path / setup_path - df = tm.makeTimeDataFrame(500) + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) df.to_hdf(path, key="df_non_table") msg = "can only use an iterator or chunksize on a table" with pytest.raises(TypeError, match=msg): - read_hdf(path, "df_non_table", chunksize=100) + read_hdf(path, "df_non_table", chunksize=2) with pytest.raises(TypeError, match=msg): read_hdf(path, "df_non_table", iterator=True) path = tmp_path / setup_path - df = tm.makeTimeDataFrame(500) + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) df.to_hdf(path, key="df", format="table") - results = list(read_hdf(path, "df", chunksize=100)) + results = list(read_hdf(path, "df", chunksize=2)) result = concat(results) assert len(results) == 5 @@ -377,9 +393,13 @@ def test_select_iterator(tmp_path, setup_path): # multiple with ensure_clean_store(setup_path) as store: - df1 = tm.makeTimeDataFrame(500) + df1 = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) store.append("df1", df1, data_columns=True) - df2 = tm.makeTimeDataFrame(500).rename(columns="{}_2".format) + df2 = df1.copy().rename(columns="{}_2".format) df2["foo"] = "bar" store.append("df2", df2) @@ -388,7 +408,7 @@ def test_select_iterator(tmp_path, setup_path): # full selection expected = store.select_as_multiple(["df1", "df2"], selector="df1") results = list( - store.select_as_multiple(["df1", "df2"], selector="df1", chunksize=150) + store.select_as_multiple(["df1", "df2"], selector="df1", chunksize=2) ) result = concat(results) tm.assert_frame_equal(expected, result) @@ -401,7 +421,11 @@ def test_select_iterator_complete_8014(setup_path): # no iterator with ensure_clean_store(setup_path) as store: - expected = tm.makeTimeDataFrame(100064, "s") + expected = DataFrame( + np.random.default_rng(2).standard_normal((100064, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=100064, freq="s"), + ) _maybe_remove(store, "df") store.append("df", expected) @@ -432,7 +456,11 @@ def test_select_iterator_complete_8014(setup_path): # with iterator, full range with ensure_clean_store(setup_path) as store: - expected = tm.makeTimeDataFrame(100064, "s") + expected = DataFrame( + np.random.default_rng(2).standard_normal((100064, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=100064, freq="s"), + ) _maybe_remove(store, "df") store.append("df", expected) @@ -470,7 +498,11 @@ def test_select_iterator_non_complete_8014(setup_path): # with iterator, non complete range with ensure_clean_store(setup_path) as store: - expected = tm.makeTimeDataFrame(100064, "s") + expected = DataFrame( + np.random.default_rng(2).standard_normal((100064, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=100064, freq="s"), + ) _maybe_remove(store, "df") store.append("df", expected) @@ -500,7 +532,11 @@ def test_select_iterator_non_complete_8014(setup_path): # with iterator, empty where with ensure_clean_store(setup_path) as store: - expected = tm.makeTimeDataFrame(100064, "s") + expected = DataFrame( + np.random.default_rng(2).standard_normal((100064, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=100064, freq="s"), + ) _maybe_remove(store, "df") store.append("df", expected) @@ -520,7 +556,11 @@ def test_select_iterator_many_empty_frames(setup_path): # with iterator, range limited to the first chunk with ensure_clean_store(setup_path) as store: - expected = tm.makeTimeDataFrame(100000, "s") + expected = DataFrame( + np.random.default_rng(2).standard_normal((100064, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=100064, freq="s"), + ) _maybe_remove(store, "df") store.append("df", expected) @@ -568,7 +608,11 @@ def test_select_iterator_many_empty_frames(setup_path): def test_frame_select(setup_path): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) with ensure_clean_store(setup_path) as store: store.put("frame", df, format="table") @@ -589,7 +633,11 @@ def test_frame_select(setup_path): tm.assert_frame_equal(result, expected) # invalid terms - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) store.append("df_time", df) msg = "day is out of range for month: 0" with pytest.raises(ValueError, match=msg): @@ -604,7 +652,11 @@ def test_frame_select(setup_path): def test_frame_select_complex(setup_path): # select via complex criteria - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) df["string"] = "foo" df.loc[df.index[0:4], "string"] = "bar" @@ -717,7 +769,11 @@ def test_frame_select_complex2(tmp_path): def test_invalid_filtering(setup_path): # can't use more than one filter (atm) - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) with ensure_clean_store(setup_path) as store: store.put("df", df, format="table") @@ -735,7 +791,11 @@ def test_invalid_filtering(setup_path): def test_string_select(setup_path): # GH 2973 with ensure_clean_store(setup_path) as store: - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) # test string ==/!= df["x"] = "none" @@ -775,8 +835,12 @@ def test_string_select(setup_path): def test_select_as_multiple(setup_path): - df1 = tm.makeTimeDataFrame() - df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) + df1 = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + df2 = df1.copy().rename(columns="{}_2".format) df2["foo"] = "bar" with ensure_clean_store(setup_path) as store: @@ -836,7 +900,8 @@ def test_select_as_multiple(setup_path): tm.assert_frame_equal(result, expected) # test exception for diff rows - store.append("df3", tm.makeTimeDataFrame(nper=50)) + df3 = df1.copy().head(2) + store.append("df3", df3) msg = "all tables must have exactly the same nrows!" with pytest.raises(ValueError, match=msg): store.select_as_multiple( diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 98257f1765d53..057f1b1fd19c3 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -201,7 +201,11 @@ def test_versioning(setup_path): columns=Index(list("ABCD"), dtype=object), index=Index([f"i-{i}" for i in range(30)], dtype=object), ) - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((20, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=20, freq="B"), + ) _maybe_remove(store, "df1") store.append("df1", df[:10]) store.append("df1", df[10:]) @@ -295,7 +299,11 @@ def test_getattr(setup_path): result = getattr(store, "a") tm.assert_series_equal(result, s) - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) store["df"] = df result = store.df tm.assert_frame_equal(result, df) @@ -395,7 +403,11 @@ def col(t, column): return getattr(store.get_storer(t).table.cols, column) # data columns - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) df["string"] = "foo" df["string2"] = "bar" store.append("f", df, data_columns=["string", "string2"]) @@ -426,7 +438,11 @@ def col(t, column): return getattr(store.get_storer(t).table.cols, column) # data columns - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) df["string"] = "foo" df["string2"] = "bar" store.append("f", df, data_columns=["string"]) @@ -640,7 +656,11 @@ def test_store_series_name(setup_path): def test_overwrite_node(setup_path): with ensure_clean_store(setup_path) as store: - store["a"] = tm.makeTimeDataFrame() + store["a"] = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) ts = tm.makeTimeSeries() store["a"] = ts @@ -648,7 +668,11 @@ def test_overwrite_node(setup_path): def test_coordinates(setup_path): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) with ensure_clean_store(setup_path) as store: _maybe_remove(store, "df") @@ -679,8 +703,12 @@ def test_coordinates(setup_path): # multiple tables _maybe_remove(store, "df1") _maybe_remove(store, "df2") - df1 = tm.makeTimeDataFrame() - df2 = tm.makeTimeDataFrame().rename(columns="{}_2".format) + df1 = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + df2 = df1.copy().rename(columns="{}_2".format) store.append("df1", df1, data_columns=["A", "B"]) store.append("df2", df2) diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index d7c69ff17749c..e20c49c072515 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -4119,8 +4119,12 @@ def tquery(query, con=None): def test_xsqlite_basic(sqlite_buildin): - frame = tm.makeTimeDataFrame() - assert sql.to_sql(frame, name="test_table", con=sqlite_buildin, index=False) == 30 + frame = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) + assert sql.to_sql(frame, name="test_table", con=sqlite_buildin, index=False) == 10 result = sql.read_sql("select * from test_table", sqlite_buildin) # HACK! Change this once indexes are handled properly. @@ -4133,7 +4137,7 @@ def test_xsqlite_basic(sqlite_buildin): frame2 = frame.copy() new_idx = Index(np.arange(len(frame2)), dtype=np.int64) + 10 frame2["Idx"] = new_idx.copy() - assert sql.to_sql(frame2, name="test_table2", con=sqlite_buildin, index=False) == 30 + assert sql.to_sql(frame2, name="test_table2", con=sqlite_buildin, index=False) == 10 result = sql.read_sql("select * from test_table2", sqlite_buildin, index_col="Idx") expected = frame.copy() expected.index = new_idx @@ -4142,7 +4146,11 @@ def test_xsqlite_basic(sqlite_buildin): def test_xsqlite_write_row_by_row(sqlite_buildin): - frame = tm.makeTimeDataFrame() + frame = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) frame.iloc[0, 0] = np.nan create_sql = sql.get_schema(frame, "test") cur = sqlite_buildin.cursor() @@ -4161,7 +4169,11 @@ def test_xsqlite_write_row_by_row(sqlite_buildin): def test_xsqlite_execute(sqlite_buildin): - frame = tm.makeTimeDataFrame() + frame = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) create_sql = sql.get_schema(frame, "test") cur = sqlite_buildin.cursor() cur.execute(create_sql) @@ -4178,7 +4190,11 @@ def test_xsqlite_execute(sqlite_buildin): def test_xsqlite_schema(sqlite_buildin): - frame = tm.makeTimeDataFrame() + frame = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) create_sql = sql.get_schema(frame, "test") lines = create_sql.splitlines() for line in lines: diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index 2a864abc5ea4a..45dc612148f40 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -19,6 +19,7 @@ import pandas as pd from pandas import ( DataFrame, + Index, MultiIndex, PeriodIndex, Series, @@ -53,19 +54,31 @@ class TestDataFramePlots: @pytest.mark.slow def test_plot(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) _check_plot_works(df.plot, grid=False) @pytest.mark.slow def test_plot_subplots(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) # _check_plot_works adds an ax so use default_axes=True to avoid warning axes = _check_plot_works(df.plot, default_axes=True, subplots=True) _check_axes_shape(axes, axes_num=4, layout=(4, 1)) @pytest.mark.slow def test_plot_subplots_negative_layout(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) axes = _check_plot_works( df.plot, default_axes=True, @@ -76,7 +89,11 @@ def test_plot_subplots_negative_layout(self): @pytest.mark.slow def test_plot_subplots_use_index(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) axes = _check_plot_works( df.plot, default_axes=True, @@ -286,7 +303,11 @@ def test_donot_overwrite_index_name(self): def test_plot_xy(self): # columns.inferred_type == 'string' - df = tm.makeTimeDataFrame(5) + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=5, freq="B"), + ) _check_data(df.plot(x=0, y=1), df.set_index("A")["B"].plot()) _check_data(df.plot(x=0), df.set_index("A").plot()) _check_data(df.plot(y=0), df.B.plot()) @@ -295,7 +316,11 @@ def test_plot_xy(self): _check_data(df.plot(y="B"), df.B.plot()) def test_plot_xy_int_cols(self): - df = tm.makeTimeDataFrame(5) + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=5, freq="B"), + ) # columns.inferred_type == 'integer' df.columns = np.arange(1, len(df.columns) + 1) _check_data(df.plot(x=1, y=2), df.set_index(1)[2].plot()) @@ -303,7 +328,11 @@ def test_plot_xy_int_cols(self): _check_data(df.plot(y=1), df[1].plot()) def test_plot_xy_figsize_and_title(self): - df = tm.makeTimeDataFrame(5) + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=5, freq="B"), + ) # figsize and title ax = df.plot(x=1, y=2, title="Test", figsize=(16, 8)) _check_text_labels(ax.title, "Test") @@ -345,14 +374,22 @@ def test_invalid_logscale(self, input_param): df.plot.pie(subplots=True, **{input_param: True}) def test_xcompat(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) ax = df.plot(x_compat=True) lines = ax.get_lines() assert not isinstance(lines[0].get_xdata(), PeriodIndex) _check_ticks_props(ax, xrot=30) def test_xcompat_plot_params(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) plotting.plot_params["xaxis.compat"] = True ax = df.plot() lines = ax.get_lines() @@ -360,7 +397,11 @@ def test_xcompat_plot_params(self): _check_ticks_props(ax, xrot=30) def test_xcompat_plot_params_x_compat(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) plotting.plot_params["x_compat"] = False ax = df.plot() @@ -371,7 +412,11 @@ def test_xcompat_plot_params_x_compat(self): assert isinstance(PeriodIndex(lines[0].get_xdata()), PeriodIndex) def test_xcompat_plot_params_context_manager(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) # useful if you're plotting a bunch together with plotting.plot_params.use("x_compat", True): ax = df.plot() @@ -380,7 +425,11 @@ def test_xcompat_plot_params_context_manager(self): _check_ticks_props(ax, xrot=30) def test_xcompat_plot_period(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) ax = df.plot() lines = ax.get_lines() assert not isinstance(lines[0].get_xdata(), PeriodIndex) @@ -405,7 +454,7 @@ def test_period_compat(self): def test_unsorted_index(self, index_dtype): df = DataFrame( {"y": np.arange(100)}, - index=pd.Index(np.arange(99, -1, -1), dtype=index_dtype), + index=Index(np.arange(99, -1, -1), dtype=index_dtype), dtype=np.int64, ) ax = df.plot() @@ -723,7 +772,7 @@ def test_bar_nan_stacked(self): expected = [0.0, 0.0, 0.0, 10.0, 0.0, 20.0, 15.0, 10.0, 40.0] assert result == expected - @pytest.mark.parametrize("idx", [pd.Index, pd.CategoricalIndex]) + @pytest.mark.parametrize("idx", [Index, pd.CategoricalIndex]) def test_bar_categorical(self, idx): # GH 13019 df = DataFrame( @@ -1391,7 +1440,7 @@ def test_unordered_ts(self): # the ticks are sorted xticks = ax.xaxis.get_ticklabels() xlocs = [x.get_position()[0] for x in xticks] - assert pd.Index(xlocs).is_monotonic_increasing + assert Index(xlocs).is_monotonic_increasing xlabels = [x.get_text() for x in xticks] assert pd.to_datetime(xlabels, format="%Y-%m-%d").is_monotonic_increasing @@ -2062,9 +2111,17 @@ def test_memory_leak(self, kind): ) args = {"x": "A", "y": "B"} elif kind == "area": - df = tm.makeTimeDataFrame().abs() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ).abs() else: - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) # Use a weakref so we can see if the object gets collected without # also preventing it from being collected @@ -2513,7 +2570,11 @@ def test_secondary_y(self, secondary_y): def test_plot_no_warning(self): # GH 55138 # TODO(3.0): this can be removed once Period[B] deprecation is enforced - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) with tm.assert_produces_warning(False): _ = df.plot() _ = df.T.plot() diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index 3195b7637ee3c..401a7610b25d8 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -1247,7 +1247,11 @@ def test_secondary_legend(self): ax = fig.add_subplot(211) # ts - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) df.plot(secondary_y=["A", "B"], ax=ax) leg = ax.get_legend() assert len(leg.get_lines()) == 4 @@ -1265,7 +1269,11 @@ def test_secondary_legend(self): mpl.pyplot.close(fig) def test_secondary_legend_right(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) fig = mpl.pyplot.figure() ax = fig.add_subplot(211) df.plot(secondary_y=["A", "C"], mark_right=False, ax=ax) @@ -1278,7 +1286,11 @@ def test_secondary_legend_right(self): mpl.pyplot.close(fig) def test_secondary_legend_bar(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) fig, ax = mpl.pyplot.subplots() df.plot(kind="bar", secondary_y=["A"], ax=ax) leg = ax.get_legend() @@ -1287,7 +1299,11 @@ def test_secondary_legend_bar(self): mpl.pyplot.close(fig) def test_secondary_legend_bar_right(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) fig, ax = mpl.pyplot.subplots() df.plot(kind="bar", secondary_y=["A"], mark_right=False, ax=ax) leg = ax.get_legend() @@ -1296,10 +1312,18 @@ def test_secondary_legend_bar_right(self): mpl.pyplot.close(fig) def test_secondary_legend_multi_col(self): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) fig = mpl.pyplot.figure() ax = fig.add_subplot(211) - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) ax = df.plot(secondary_y=["C", "D"], ax=ax) leg = ax.get_legend() assert len(leg.get_lines()) == 4 diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index 865c02798c648..8a725c6e51e3f 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -11,6 +11,7 @@ import pandas as pd from pandas import ( DataFrame, + Index, Series, Timedelta, Timestamp, @@ -433,7 +434,11 @@ def test_resample_upsampling_picked_but_not_correct(unit): @pytest.mark.parametrize("f", ["sum", "mean", "prod", "min", "max", "var"]) def test_resample_frame_basic_cy_funcs(f, unit): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((50, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=50, freq="B"), + ) df.index = df.index.as_unit(unit) b = Grouper(freq="ME") @@ -445,7 +450,11 @@ def test_resample_frame_basic_cy_funcs(f, unit): @pytest.mark.parametrize("freq", ["YE", "ME"]) def test_resample_frame_basic_M_A(freq, unit): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((50, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=50, freq="B"), + ) df.index = df.index.as_unit(unit) result = df.resample(freq).mean() tm.assert_series_equal(result["A"], df["A"].resample(freq).mean()) @@ -453,7 +462,11 @@ def test_resample_frame_basic_M_A(freq, unit): @pytest.mark.parametrize("freq", ["W-WED", "ME"]) def test_resample_frame_basic_kind(freq, unit): - df = tm.makeTimeDataFrame() + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) df.index = df.index.as_unit(unit) msg = "The 'kind' keyword in DataFrame.resample is deprecated" with tm.assert_produces_warning(FutureWarning, match=msg): @@ -1465,7 +1478,11 @@ def test_resample_nunique(unit): def test_resample_nunique_preserves_column_level_names(unit): # see gh-23222 - df = tm.makeTimeDataFrame(freq="1D").abs() + df = DataFrame( + np.random.default_rng(2).standard_normal((5, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=5, freq="D"), + ).abs() df.index = df.index.as_unit(unit) df.columns = pd.MultiIndex.from_arrays( [df.columns.tolist()] * 2, names=["lev0", "lev1"] diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index f07c223bf0de2..3408e6e4731bd 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -168,7 +168,7 @@ def test_join_on_fails_with_different_right_index(self): "a": np.random.default_rng(2).choice(["m", "f"], size=10), "b": np.random.default_rng(2).standard_normal(10), }, - index=tm.makeCustomIndex(10, 2), + index=MultiIndex.from_product([range(5), ["A", "B"]]), ) msg = r'len\(left_on\) must equal the number of levels in the index of "right"' with pytest.raises(ValueError, match=msg): @@ -180,7 +180,7 @@ def test_join_on_fails_with_different_left_index(self): "a": np.random.default_rng(2).choice(["m", "f"], size=3), "b": np.random.default_rng(2).standard_normal(3), }, - index=tm.makeCustomIndex(3, 2), + index=MultiIndex.from_arrays([range(3), list("abc")]), ) df2 = DataFrame( { @@ -204,7 +204,7 @@ def test_join_on_fails_with_different_column_counts(self): "a": np.random.default_rng(2).choice(["m", "f"], size=10), "b": np.random.default_rng(2).standard_normal(10), }, - index=tm.makeCustomIndex(10, 2), + index=MultiIndex.from_product([range(5), ["A", "B"]]), ) msg = r"len\(right_on\) must equal len\(left_on\)" with pytest.raises(ValueError, match=msg): diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py index b10436889d829..ff9f927597956 100644 --- a/pandas/tests/reshape/test_melt.py +++ b/pandas/tests/reshape/test_melt.py @@ -6,6 +6,8 @@ import pandas as pd from pandas import ( DataFrame, + Index, + date_range, lreshape, melt, wide_to_long, @@ -15,7 +17,11 @@ @pytest.fixture def df(): - res = tm.makeTimeDataFrame()[:10] + res = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), + ) res["id1"] = (res["A"] > 0).astype(np.int64) res["id2"] = (res["B"] > 0).astype(np.int64) return res @@ -281,7 +287,7 @@ def test_multiindex(self, df1): @pytest.mark.parametrize( "col", [ - pd.Series(pd.date_range("2010", periods=5, tz="US/Pacific")), + pd.Series(date_range("2010", periods=5, tz="US/Pacific")), pd.Series(["a", "b", "c", "a", "d"], dtype="category"), pd.Series([0, 1, 0, 0, 0]), ], @@ -396,11 +402,11 @@ def test_ignore_multiindex(self): def test_ignore_index_name_and_type(self): # GH 17440 - index = pd.Index(["foo", "bar"], dtype="category", name="baz") + index = Index(["foo", "bar"], dtype="category", name="baz") df = DataFrame({"x": [0, 1], "y": [2, 3]}, index=index) result = melt(df, ignore_index=False) - expected_index = pd.Index(["foo", "bar"] * 2, dtype="category", name="baz") + expected_index = Index(["foo", "bar"] * 2, dtype="category", name="baz") expected = DataFrame( {"variable": ["x", "x", "y", "y"], "value": [0, 1, 2, 3]}, index=expected_index, @@ -1203,7 +1209,7 @@ def test_missing_stubname(self, dtype): j="num", sep="-", ) - index = pd.Index( + index = Index( [("1", 1), ("2", 1), ("1", 2), ("2", 2)], name=("id", "num"), ) diff --git a/pandas/tests/series/methods/test_unstack.py b/pandas/tests/series/methods/test_unstack.py index b294e2fcce9d8..3c70e839c8e20 100644 --- a/pandas/tests/series/methods/test_unstack.py +++ b/pandas/tests/series/methods/test_unstack.py @@ -4,8 +4,10 @@ import pandas as pd from pandas import ( DataFrame, + Index, MultiIndex, Series, + date_range, ) import pandas._testing as tm @@ -92,7 +94,7 @@ def test_unstack_tuplename_in_multiindex(): expected = DataFrame( [[1, 1, 1], [1, 1, 1], [1, 1, 1]], columns=MultiIndex.from_tuples([("a",), ("b",), ("c",)], names=[("A", "a")]), - index=pd.Index([1, 2, 3], name=("B", "b")), + index=Index([1, 2, 3], name=("B", "b")), ) tm.assert_frame_equal(result, expected) @@ -109,7 +111,7 @@ def test_unstack_tuplename_in_multiindex(): ( (("A", "a"), "B"), [[1, 1, 1, 1], [1, 1, 1, 1]], - pd.Index([3, 4], name="C"), + Index([3, 4], name="C"), MultiIndex.from_tuples( [("a", 1), ("a", 2), ("b", 1), ("b", 2)], names=[("A", "a"), "B"] ), @@ -133,9 +135,12 @@ def test_unstack_mixed_type_name_in_multiindex( def test_unstack_multi_index_categorical_values(): - mi = ( - tm.makeTimeDataFrame().stack(future_stack=True).index.rename(["major", "minor"]) + df = DataFrame( + np.random.default_rng(2).standard_normal((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=date_range("2000-01-01", periods=10, freq="B"), ) + mi = df.stack(future_stack=True).index.rename(["major", "minor"]) ser = Series(["foo"] * len(mi), index=mi, name="category", dtype="category") result = ser.unstack() @@ -144,7 +149,7 @@ def test_unstack_multi_index_categorical_values(): c = pd.Categorical(["foo"] * len(dti)) expected = DataFrame( {"A": c.copy(), "B": c.copy(), "C": c.copy(), "D": c.copy()}, - columns=pd.Index(list("ABCD"), name="minor"), + columns=Index(list("ABCD"), name="minor"), index=dti.rename("major"), ) tm.assert_frame_equal(result, expected) @@ -158,7 +163,7 @@ def test_unstack_mixed_level_names(): result = ser.unstack("x") expected = DataFrame( [[1], [2]], - columns=pd.Index(["a"], name="x"), + columns=Index(["a"], name="x"), index=MultiIndex.from_tuples([(1, "red"), (2, "blue")], names=[0, "y"]), ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 773d7e174feac..502096d41dde2 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -679,7 +679,7 @@ def test_constructor_broadcast_list(self): Series(["foo"], index=["a", "b", "c"]) def test_constructor_corner(self): - df = tm.makeTimeDataFrame() + df = DataFrame(range(5), index=date_range("2020-01-01", periods=5)) objs = [df, df] s = Series(objs, index=[0, 1]) assert isinstance(s, Series) diff --git a/pandas/tests/util/test_hashing.py b/pandas/tests/util/test_hashing.py index 4fa256a6b8630..1e7fdd920e365 100644 --- a/pandas/tests/util/test_hashing.py +++ b/pandas/tests/util/test_hashing.py @@ -146,8 +146,8 @@ def test_multiindex_objects(): "D": pd.date_range("20130101", periods=5), } ), - tm.makeTimeDataFrame(), - tm.makeTimeSeries(), + DataFrame(range(5), index=pd.date_range("2020-01-01", periods=5)), + Series(range(5), index=pd.date_range("2020-01-01", periods=5)), Series(period_range("2020-01-01", periods=10, freq="D")), Series(pd.date_range("20130101", periods=3, tz="US/Eastern")), ], @@ -179,8 +179,8 @@ def test_hash_pandas_object(obj, index): "D": pd.date_range("20130101", periods=5), } ), - tm.makeTimeDataFrame(), - tm.makeTimeSeries(), + DataFrame(range(5), index=pd.date_range("2020-01-01", periods=5)), + Series(range(5), index=pd.date_range("2020-01-01", periods=5)), Series(period_range("2020-01-01", periods=10, freq="D")), Series(pd.date_range("20130101", periods=3, tz="US/Eastern")), ],
null
https://api.github.com/repos/pandas-dev/pandas/pulls/56264
2023-11-30T19:58:56Z
2023-12-01T18:37:05Z
2023-12-01T18:37:05Z
2024-01-30T21:09:38Z
Backport PR #56179 on branch 2.1.x (BUG: to_numeric casting to ea for new string dtype)
diff --git a/doc/source/whatsnew/v2.1.4.rst b/doc/source/whatsnew/v2.1.4.rst index 684b68baa123c..3a72c0864d29c 100644 --- a/doc/source/whatsnew/v2.1.4.rst +++ b/doc/source/whatsnew/v2.1.4.rst @@ -23,6 +23,7 @@ Bug fixes ~~~~~~~~~ - Bug in :meth:`DataFrame.apply` where passing ``raw=True`` ignored ``args`` passed to the applied function (:issue:`55753`) - Bug in :meth:`Index.__getitem__` returning wrong result for Arrow dtypes and negative stepsize (:issue:`55832`) +- Fixed bug in :func:`to_numeric` converting to extension dtype for ``string[pyarrow_numpy]`` dtype (:issue:`56179`) - Fixed bug in :meth:`DataFrame.__setitem__` casting :class:`Index` with object-dtype to PyArrow backed strings when ``infer_string`` option is set (:issue:`55638`) - Fixed bug in :meth:`DataFrame.to_hdf` raising when columns have ``StringDtype`` (:issue:`55088`) - Fixed bug in :meth:`Index.insert` casting object-dtype to PyArrow backed strings when ``infer_string`` option is set (:issue:`55638`) diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py index a50dbeb110bff..f1b14cdc58b13 100644 --- a/pandas/core/tools/numeric.py +++ b/pandas/core/tools/numeric.py @@ -224,7 +224,8 @@ def to_numeric( set(), coerce_numeric=coerce_numeric, convert_to_masked_nullable=dtype_backend is not lib.no_default - or isinstance(values_dtype, StringDtype), + or isinstance(values_dtype, StringDtype) + and not values_dtype.storage == "pyarrow_numpy", ) except (ValueError, TypeError): if errors == "raise": @@ -239,6 +240,7 @@ def to_numeric( dtype_backend is not lib.no_default and new_mask is None or isinstance(values_dtype, StringDtype) + and not values_dtype.storage == "pyarrow_numpy" ): new_mask = np.zeros(values.shape, dtype=np.bool_) diff --git a/pandas/tests/tools/test_to_numeric.py b/pandas/tests/tools/test_to_numeric.py index 1d969e648b752..7f37e6003f313 100644 --- a/pandas/tests/tools/test_to_numeric.py +++ b/pandas/tests/tools/test_to_numeric.py @@ -4,12 +4,15 @@ from numpy import iinfo import pytest +import pandas.util._test_decorators as td + import pandas as pd from pandas import ( ArrowDtype, DataFrame, Index, Series, + option_context, to_numeric, ) import pandas._testing as tm @@ -67,10 +70,14 @@ def test_empty(input_kwargs, result_kwargs): tm.assert_series_equal(result, expected) +@pytest.mark.parametrize( + "infer_string", [False, pytest.param(True, marks=td.skip_if_no("pyarrow"))] +) @pytest.mark.parametrize("last_val", ["7", 7]) -def test_series(last_val): - ser = Series(["1", "-3.14", last_val]) - result = to_numeric(ser) +def test_series(last_val, infer_string): + with option_context("future.infer_string", infer_string): + ser = Series(["1", "-3.14", last_val]) + result = to_numeric(ser) expected = Series([1, -3.14, 7]) tm.assert_series_equal(result, expected)
Backport PR #56179: BUG: to_numeric casting to ea for new string dtype
https://api.github.com/repos/pandas-dev/pandas/pulls/56263
2023-11-30T17:47:57Z
2023-11-30T19:59:33Z
2023-11-30T19:59:33Z
2023-11-30T19:59:33Z
BUG: support non-nano times in ewm
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index c73adc25cb1dd..7b09d12697055 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -561,12 +561,14 @@ Groupby/resample/rolling - Bug in :meth:`.DataFrameGroupBy.idxmin`, :meth:`.DataFrameGroupBy.idxmax`, :meth:`.SeriesGroupBy.idxmin`, and :meth:`.SeriesGroupBy.idxmax` would not retain :class:`.Categorical` dtype when the index was a :class:`.CategoricalIndex` that contained NA values (:issue:`54234`) - Bug in :meth:`.DataFrameGroupBy.transform` and :meth:`.SeriesGroupBy.transform` when ``observed=False`` and ``f="idxmin"`` or ``f="idxmax"`` would incorrectly raise on unobserved categories (:issue:`54234`) - Bug in :meth:`DataFrame.asfreq` and :meth:`Series.asfreq` with a :class:`DatetimeIndex` with non-nanosecond resolution incorrectly converting to nanosecond resolution (:issue:`55958`) +- Bug in :meth:`DataFrame.ewm` when passed ``times`` with non-nanosecond ``datetime64`` or :class:`DatetimeTZDtype` dtype (:issue:`56262`) - Bug in :meth:`DataFrame.resample` not respecting ``closed`` and ``label`` arguments for :class:`~pandas.tseries.offsets.BusinessDay` (:issue:`55282`) - Bug in :meth:`DataFrame.resample` where bin edges were not correct for :class:`~pandas.tseries.offsets.BusinessDay` (:issue:`55281`) - Bug in :meth:`DataFrame.resample` where bin edges were not correct for :class:`~pandas.tseries.offsets.MonthBegin` (:issue:`55271`) - Bug in :meth:`DataFrameGroupBy.value_counts` and :meth:`SeriesGroupBy.value_count` could result in incorrect sorting if the columns of the DataFrame or name of the Series are integers (:issue:`55951`) - Bug in :meth:`DataFrameGroupBy.value_counts` and :meth:`SeriesGroupBy.value_count` would not respect ``sort=False`` in :meth:`DataFrame.groupby` and :meth:`Series.groupby` (:issue:`55951`) - Bug in :meth:`DataFrameGroupBy.value_counts` and :meth:`SeriesGroupBy.value_count` would sort by proportions rather than frequencies when ``sort=True`` and ``normalize=True`` (:issue:`55951`) +- Reshaping ^^^^^^^^^ diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index db659713c6f16..9ebf32d3e536e 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -12,13 +12,15 @@ from pandas.util._decorators import doc from pandas.core.dtypes.common import ( - is_datetime64_ns_dtype, + is_datetime64_dtype, is_numeric_dtype, ) +from pandas.core.dtypes.dtypes import DatetimeTZDtype from pandas.core.dtypes.generic import ABCSeries from pandas.core.dtypes.missing import isna from pandas.core import common +from pandas.core.arrays.datetimelike import dtype_to_unit from pandas.core.indexers.objects import ( BaseIndexer, ExponentialMovingWindowIndexer, @@ -56,6 +58,7 @@ from pandas._typing import ( Axis, TimedeltaConvertibleTypes, + npt, ) from pandas import ( @@ -101,7 +104,7 @@ def get_center_of_mass( def _calculate_deltas( times: np.ndarray | NDFrame, halflife: float | TimedeltaConvertibleTypes | None, -) -> np.ndarray: +) -> npt.NDArray[np.float64]: """ Return the diff of the times divided by the half-life. These values are used in the calculation of the ewm mean. @@ -119,11 +122,11 @@ def _calculate_deltas( np.ndarray Diff of the times divided by the half-life """ + unit = dtype_to_unit(times.dtype) if isinstance(times, ABCSeries): times = times._values _times = np.asarray(times.view(np.int64), dtype=np.float64) - # TODO: generalize to non-nano? - _halflife = float(Timedelta(halflife).as_unit("ns")._value) + _halflife = float(Timedelta(halflife).as_unit(unit)._value) return np.diff(_times) / _halflife @@ -366,8 +369,12 @@ def __init__( if self.times is not None: if not self.adjust: raise NotImplementedError("times is not supported with adjust=False.") - if not is_datetime64_ns_dtype(self.times): - raise ValueError("times must be datetime64[ns] dtype.") + times_dtype = getattr(self.times, "dtype", None) + if not ( + is_datetime64_dtype(times_dtype) + or isinstance(times_dtype, DatetimeTZDtype) + ): + raise ValueError("times must be datetime64 dtype.") if len(self.times) != len(obj): raise ValueError("times must be the same length as the object.") if not isinstance(self.halflife, (str, datetime.timedelta, np.timedelta64)): diff --git a/pandas/tests/window/test_ewm.py b/pandas/tests/window/test_ewm.py index 427780db79783..058e5ce36e53e 100644 --- a/pandas/tests/window/test_ewm.py +++ b/pandas/tests/window/test_ewm.py @@ -60,7 +60,7 @@ def test_constructor(frame_or_series): def test_ewma_times_not_datetime_type(): - msg = r"times must be datetime64\[ns\] dtype." + msg = r"times must be datetime64 dtype." with pytest.raises(ValueError, match=msg): Series(range(5)).ewm(times=np.arange(5)) @@ -102,30 +102,6 @@ def test_ewma_with_times_equal_spacing(halflife_with_times, times, min_periods): tm.assert_frame_equal(result, expected) -@pytest.mark.parametrize( - "unit", - [ - pytest.param( - "s", - marks=pytest.mark.xfail( - reason="ExponentialMovingWindow constructor raises on non-nano" - ), - ), - pytest.param( - "ms", - marks=pytest.mark.xfail( - reason="ExponentialMovingWindow constructor raises on non-nano" - ), - ), - pytest.param( - "us", - marks=pytest.mark.xfail( - reason="ExponentialMovingWindow constructor raises on non-nano" - ), - ), - "ns", - ], -) def test_ewma_with_times_variable_spacing(tz_aware_fixture, unit): tz = tz_aware_fixture halflife = "23 days"
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/56262
2023-11-30T16:42:10Z
2023-11-30T23:20:48Z
2023-11-30T23:20:48Z
2023-11-30T23:29:31Z
TST: dt64 units
diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index a635ac77566e1..4dc0d477f89e8 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -686,7 +686,8 @@ def na_value_for_dtype(dtype: DtypeObj, compat: bool = True): if isinstance(dtype, ExtensionDtype): return dtype.na_value elif dtype.kind in "mM": - return dtype.type("NaT", "ns") + unit = np.datetime_data(dtype)[0] + return dtype.type("NaT", unit) elif dtype.kind == "f": return np.nan elif dtype.kind in "iu": diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index c989b3d26677c..20f0dcc816408 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -664,11 +664,8 @@ def test_reset_index_dtypes_on_empty_frame_with_multiindex(array, dtype): def test_reset_index_empty_frame_with_datetime64_multiindex(): # https://github.com/pandas-dev/pandas/issues/35606 - idx = MultiIndex( - levels=[[Timestamp("2020-07-20 00:00:00")], [3, 4]], - codes=[[], []], - names=["a", "b"], - ) + dti = pd.DatetimeIndex(["2020-07-20 00:00:00"], dtype="M8[ns]") + idx = MultiIndex.from_product([dti, [3, 4]], names=["a", "b"])[:0] df = DataFrame(index=idx, columns=["c", "d"]) result = df.reset_index() expected = DataFrame( @@ -681,7 +678,8 @@ def test_reset_index_empty_frame_with_datetime64_multiindex(): def test_reset_index_empty_frame_with_datetime64_multiindex_from_groupby(): # https://github.com/pandas-dev/pandas/issues/35657 - df = DataFrame({"c1": [10.0], "c2": ["a"], "c3": pd.to_datetime("2020-01-01")}) + dti = pd.DatetimeIndex(["2020-01-01"], dtype="M8[ns]") + df = DataFrame({"c1": [10.0], "c2": ["a"], "c3": dti}) df = df.head(0).groupby(["c2", "c3"])[["c1"]].sum() result = df.reset_index() expected = DataFrame( diff --git a/pandas/tests/indexes/interval/test_formats.py b/pandas/tests/indexes/interval/test_formats.py index bf335d154e186..edd7993056512 100644 --- a/pandas/tests/indexes/interval/test_formats.py +++ b/pandas/tests/indexes/interval/test_formats.py @@ -3,6 +3,7 @@ from pandas import ( DataFrame, + DatetimeIndex, Index, Interval, IntervalIndex, @@ -100,18 +101,14 @@ def test_get_values_for_csv(self, tuples, closed, expected_data): expected = np.array(expected_data) tm.assert_numpy_array_equal(result, expected) - def test_timestamp_with_timezone(self): + def test_timestamp_with_timezone(self, unit): # GH 55035 - index = IntervalIndex( - [ - Interval( - Timestamp("2020-01-01", tz="UTC"), Timestamp("2020-01-02", tz="UTC") - ) - ] - ) + left = DatetimeIndex(["2020-01-01"], dtype=f"M8[{unit}, UTC]") + right = DatetimeIndex(["2020-01-02"], dtype=f"M8[{unit}, UTC]") + index = IntervalIndex.from_arrays(left, right) result = repr(index) expected = ( "IntervalIndex([(2020-01-01 00:00:00+00:00, 2020-01-02 00:00:00+00:00]], " - "dtype='interval[datetime64[ns, UTC], right]')" + f"dtype='interval[datetime64[{unit}, UTC], right]')" ) assert result == expected diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index a9e83f6ef87a3..fe9ad8de5765f 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -1,3 +1,5 @@ +from __future__ import annotations + from datetime import ( datetime, time, @@ -130,8 +132,15 @@ def df_ref(datapath): return df_ref -def adjust_expected(expected: DataFrame, read_ext: str) -> None: +def get_exp_unit(read_ext: str, engine: str | None) -> str: + return "ns" + + +def adjust_expected(expected: DataFrame, read_ext: str, engine: str) -> None: expected.index.name = None + unit = get_exp_unit(read_ext, engine) + # error: "Index" has no attribute "as_unit" + expected.index = expected.index.as_unit(unit) # type: ignore[attr-defined] def xfail_datetimes_with_pyxlsb(engine, request): @@ -225,7 +234,7 @@ def test_usecols_list(self, request, engine, read_ext, df_ref): xfail_datetimes_with_pyxlsb(engine, request) expected = df_ref[["B", "C"]] - adjust_expected(expected, read_ext) + adjust_expected(expected, read_ext, engine) df1 = pd.read_excel( "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=[0, 2, 3] @@ -246,7 +255,7 @@ def test_usecols_str(self, request, engine, read_ext, df_ref): xfail_datetimes_with_pyxlsb(engine, request) expected = df_ref[["A", "B", "C"]] - adjust_expected(expected, read_ext) + adjust_expected(expected, read_ext, engine) df2 = pd.read_excel( "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A:D" @@ -264,7 +273,7 @@ def test_usecols_str(self, request, engine, read_ext, df_ref): tm.assert_frame_equal(df3, expected) expected = df_ref[["B", "C"]] - adjust_expected(expected, read_ext) + adjust_expected(expected, read_ext, engine) df2 = pd.read_excel( "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,C,D" @@ -302,7 +311,7 @@ def test_usecols_diff_positional_int_columns_order( xfail_datetimes_with_pyxlsb(engine, request) expected = df_ref[["A", "C"]] - adjust_expected(expected, read_ext) + adjust_expected(expected, read_ext, engine) result = pd.read_excel( "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols=usecols @@ -321,7 +330,7 @@ def test_read_excel_without_slicing(self, request, engine, read_ext, df_ref): xfail_datetimes_with_pyxlsb(engine, request) expected = df_ref - adjust_expected(expected, read_ext) + adjust_expected(expected, read_ext, engine) result = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", index_col=0) tm.assert_frame_equal(result, expected) @@ -330,7 +339,7 @@ def test_usecols_excel_range_str(self, request, engine, read_ext, df_ref): xfail_datetimes_with_pyxlsb(engine, request) expected = df_ref[["C", "D"]] - adjust_expected(expected, read_ext) + adjust_expected(expected, read_ext, engine) result = pd.read_excel( "test1" + read_ext, sheet_name="Sheet1", index_col=0, usecols="A,D:E" @@ -428,7 +437,7 @@ def test_excel_table(self, request, engine, read_ext, df_ref): xfail_datetimes_with_pyxlsb(engine, request) expected = df_ref - adjust_expected(expected, read_ext) + adjust_expected(expected, read_ext, engine) df1 = pd.read_excel("test1" + read_ext, sheet_name="Sheet1", index_col=0) df2 = pd.read_excel( @@ -446,6 +455,7 @@ def test_excel_table(self, request, engine, read_ext, df_ref): def test_reader_special_dtypes(self, request, engine, read_ext): xfail_datetimes_with_pyxlsb(engine, request) + unit = get_exp_unit(read_ext, engine) expected = DataFrame.from_dict( { "IntCol": [1, 2, -3, 4, 0], @@ -453,13 +463,16 @@ def test_reader_special_dtypes(self, request, engine, read_ext): "BoolCol": [True, False, True, True, False], "StrCol": [1, 2, 3, 4, 5], "Str2Col": ["a", 3, "c", "d", "e"], - "DateCol": [ - datetime(2013, 10, 30), - datetime(2013, 10, 31), - datetime(1905, 1, 1), - datetime(2013, 12, 14), - datetime(2015, 3, 14), - ], + "DateCol": Index( + [ + datetime(2013, 10, 30), + datetime(2013, 10, 31), + datetime(1905, 1, 1), + datetime(2013, 12, 14), + datetime(2015, 3, 14), + ], + dtype=f"M8[{unit}]", + ), }, ) basename = "test_types" @@ -578,7 +591,7 @@ def test_reader_dtype_str(self, read_ext, dtype, expected): actual = pd.read_excel(basename + read_ext, dtype=dtype) tm.assert_frame_equal(actual, expected) - def test_dtype_backend(self, read_ext, dtype_backend): + def test_dtype_backend(self, read_ext, dtype_backend, engine): # GH#36712 if read_ext in (".xlsb", ".xls"): pytest.skip(f"No engine for filetype: '{read_ext}'") @@ -621,6 +634,9 @@ def test_dtype_backend(self, read_ext, dtype_backend): expected["j"] = ArrowExtensionArray(pa.array([None, None])) else: expected = df + unit = get_exp_unit(read_ext, engine) + expected["i"] = expected["i"].astype(f"M8[{unit}]") + tm.assert_frame_equal(result, expected) def test_dtype_backend_and_dtype(self, read_ext): @@ -812,7 +828,7 @@ def test_sheet_name(self, request, read_ext, engine, df_ref): sheet_name = "Sheet1" expected = df_ref - adjust_expected(expected, read_ext) + adjust_expected(expected, read_ext, engine) df1 = pd.read_excel( filename + read_ext, sheet_name=sheet_name, index_col=0 @@ -1010,6 +1026,8 @@ def test_read_excel_multiindex(self, request, engine, read_ext): # see gh-4679 xfail_datetimes_with_pyxlsb(engine, request) + unit = get_exp_unit(read_ext, engine) + mi = MultiIndex.from_product([["foo", "bar"], ["a", "b"]]) mi_file = "testmultiindex" + read_ext @@ -1023,6 +1041,7 @@ def test_read_excel_multiindex(self, request, engine, read_ext): ], columns=mi, ) + expected[mi[2]] = expected[mi[2]].astype(f"M8[{unit}]") actual = pd.read_excel( mi_file, sheet_name="mi_column", header=[0, 1], index_col=0 @@ -1102,6 +1121,9 @@ def test_read_excel_multiindex_blank_after_name( mi_file = "testmultiindex" + read_ext mi = MultiIndex.from_product([["foo", "bar"], ["a", "b"]], names=["c1", "c2"]) + + unit = get_exp_unit(read_ext, engine) + expected = DataFrame( [ [1, 2.5, pd.Timestamp("2015-01-01"), True], @@ -1115,6 +1137,7 @@ def test_read_excel_multiindex_blank_after_name( names=["ilvl1", "ilvl2"], ), ) + expected[mi[2]] = expected[mi[2]].astype(f"M8[{unit}]") result = pd.read_excel( mi_file, sheet_name=sheet_name, @@ -1218,6 +1241,8 @@ def test_read_excel_skiprows(self, request, engine, read_ext): # GH 4903 xfail_datetimes_with_pyxlsb(engine, request) + unit = get_exp_unit(read_ext, engine) + actual = pd.read_excel( "testskiprows" + read_ext, sheet_name="skiprows_list", skiprows=[0, 2] ) @@ -1230,6 +1255,7 @@ def test_read_excel_skiprows(self, request, engine, read_ext): ], columns=["a", "b", "c", "d"], ) + expected["c"] = expected["c"].astype(f"M8[{unit}]") tm.assert_frame_equal(actual, expected) actual = pd.read_excel( @@ -1262,11 +1288,13 @@ def test_read_excel_skiprows(self, request, engine, read_ext): ], columns=["a", "b", "c", "d"], ) + expected["c"] = expected["c"].astype(f"M8[{unit}]") tm.assert_frame_equal(actual, expected) def test_read_excel_skiprows_callable_not_in(self, request, engine, read_ext): # GH 4903 xfail_datetimes_with_pyxlsb(engine, request) + unit = get_exp_unit(read_ext, engine) actual = pd.read_excel( "testskiprows" + read_ext, @@ -1282,6 +1310,7 @@ def test_read_excel_skiprows_callable_not_in(self, request, engine, read_ext): ], columns=["a", "b", "c", "d"], ) + expected["c"] = expected["c"].astype(f"M8[{unit}]") tm.assert_frame_equal(actual, expected) def test_read_excel_nrows(self, read_ext): @@ -1538,7 +1567,7 @@ def test_excel_table_sheet_by_index(self, request, engine, read_ext, df_ref): xfail_datetimes_with_pyxlsb(engine, request) expected = df_ref - adjust_expected(expected, read_ext) + adjust_expected(expected, read_ext, engine) with pd.ExcelFile("test1" + read_ext) as excel: df1 = pd.read_excel(excel, sheet_name=0, index_col=0) @@ -1565,7 +1594,7 @@ def test_sheet_name(self, request, engine, read_ext, df_ref): xfail_datetimes_with_pyxlsb(engine, request) expected = df_ref - adjust_expected(expected, read_ext) + adjust_expected(expected, read_ext, engine) filename = "test1" sheet_name = "Sheet1" @@ -1657,11 +1686,14 @@ def test_read_datetime_multiindex(self, request, engine, read_ext): f = "test_datetime_mi" + read_ext with pd.ExcelFile(f) as excel: actual = pd.read_excel(excel, header=[0, 1], index_col=0, engine=engine) - expected_column_index = MultiIndex.from_tuples( - [(pd.to_datetime("02/29/2020"), pd.to_datetime("03/01/2020"))], + + unit = get_exp_unit(read_ext, engine) + dti = pd.DatetimeIndex(["2020-02-29", "2020-03-01"], dtype=f"M8[{unit}]") + expected_column_index = MultiIndex.from_arrays( + [dti[:1], dti[1:]], names=[ - pd.to_datetime("02/29/2020").to_pydatetime(), - pd.to_datetime("03/01/2020").to_pydatetime(), + dti[0].to_pydatetime(), + dti[1].to_pydatetime(), ], ) expected = DataFrame([], index=[], columns=expected_column_index) diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 74286a3ddd8ed..8452ec01a0936 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -35,6 +35,10 @@ from pandas.io.excel._util import _writers +def get_exp_unit(path: str) -> str: + return "ns" + + @pytest.fixture def frame(float_frame): """ @@ -461,6 +465,7 @@ def test_mixed(self, frame, path): tm.assert_frame_equal(mixed_frame, recons) def test_ts_frame(self, path): + unit = get_exp_unit(path) df = DataFrame( np.random.default_rng(2).standard_normal((5, 4)), columns=Index(list("ABCD"), dtype=object), @@ -471,10 +476,13 @@ def test_ts_frame(self, path): index = pd.DatetimeIndex(np.asarray(df.index), freq=None) df.index = index + expected = df[:] + expected.index = expected.index.as_unit(unit) + df.to_excel(path, sheet_name="test1") with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) - tm.assert_frame_equal(df, recons) + tm.assert_frame_equal(expected, recons) def test_basics_with_nan(self, frame, path): frame = frame.copy() @@ -538,6 +546,7 @@ def test_inf_roundtrip(self, path): def test_sheets(self, frame, path): # freq doesn't round-trip + unit = get_exp_unit(path) tsframe = DataFrame( np.random.default_rng(2).standard_normal((5, 4)), columns=Index(list("ABCD"), dtype=object), @@ -546,6 +555,9 @@ def test_sheets(self, frame, path): index = pd.DatetimeIndex(np.asarray(tsframe.index), freq=None) tsframe.index = index + expected = tsframe[:] + expected.index = expected.index.as_unit(unit) + frame = frame.copy() frame.iloc[:5, frame.columns.get_loc("A")] = np.nan @@ -562,7 +574,7 @@ def test_sheets(self, frame, path): recons = pd.read_excel(reader, sheet_name="test1", index_col=0) tm.assert_frame_equal(frame, recons) recons = pd.read_excel(reader, sheet_name="test2", index_col=0) - tm.assert_frame_equal(tsframe, recons) + tm.assert_frame_equal(expected, recons) assert 2 == len(reader.sheet_names) assert "test1" == reader.sheet_names[0] assert "test2" == reader.sheet_names[1] @@ -660,6 +672,7 @@ def test_excel_roundtrip_indexname(self, merge_cells, path): def test_excel_roundtrip_datetime(self, merge_cells, path): # datetime.date, not sure what to test here exactly + unit = get_exp_unit(path) # freq does not round-trip tsframe = DataFrame( @@ -678,12 +691,16 @@ def test_excel_roundtrip_datetime(self, merge_cells, path): with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=0) - tm.assert_frame_equal(tsframe, recons) + expected = tsframe[:] + expected.index = expected.index.as_unit(unit) + tm.assert_frame_equal(expected, recons) def test_excel_date_datetime_format(self, ext, path): # see gh-4133 # # Excel output format strings + unit = get_exp_unit(path) + df = DataFrame( [ [date(2014, 1, 31), date(1999, 9, 24)], @@ -700,6 +717,7 @@ def test_excel_date_datetime_format(self, ext, path): index=["DATE", "DATETIME"], columns=["X", "Y"], ) + df_expected = df_expected.astype(f"M8[{unit}]") with tm.ensure_clean(ext) as filename2: with ExcelWriter(path) as writer1: @@ -854,15 +872,20 @@ def test_to_excel_multiindex_cols(self, merge_cells, frame, path): def test_to_excel_multiindex_dates(self, merge_cells, path): # try multiindex with dates + unit = get_exp_unit(path) tsframe = DataFrame( np.random.default_rng(2).standard_normal((5, 4)), columns=Index(list("ABCD"), dtype=object), index=date_range("2000-01-01", periods=5, freq="B"), ) - new_index = [tsframe.index, np.arange(len(tsframe.index), dtype=np.int64)] - tsframe.index = MultiIndex.from_arrays(new_index) + tsframe.index = MultiIndex.from_arrays( + [ + tsframe.index.as_unit(unit), + np.arange(len(tsframe.index), dtype=np.int64), + ], + names=["time", "foo"], + ) - tsframe.index.names = ["time", "foo"] tsframe.to_excel(path, sheet_name="test1", merge_cells=merge_cells) with ExcelFile(path) as reader: recons = pd.read_excel(reader, sheet_name="test1", index_col=[0, 1]) @@ -1147,6 +1170,7 @@ def test_comment_empty_line(self, path): def test_datetimes(self, path): # Test writing and reading datetimes. For issue #9139. (xref #9185) + unit = get_exp_unit(path) datetimes = [ datetime(2013, 1, 13, 1, 2, 3), datetime(2013, 1, 13, 2, 45, 56), @@ -1165,7 +1189,8 @@ def test_datetimes(self, path): write_frame.to_excel(path, sheet_name="Sheet1") read_frame = pd.read_excel(path, sheet_name="Sheet1", header=0) - tm.assert_series_equal(write_frame["A"], read_frame["A"]) + expected = write_frame.astype(f"M8[{unit}]") + tm.assert_series_equal(expected["A"], read_frame["A"]) def test_bytes_io(self, engine): # see gh-7074
Aimed at trimming the diff in #55901
https://api.github.com/repos/pandas-dev/pandas/pulls/56261
2023-11-30T16:31:55Z
2023-12-04T19:11:54Z
2023-12-04T19:11:54Z
2023-12-04T20:09:23Z
TYP: overload tz_to_dtype
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index de5832ba31b70..496a6987c3264 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -8,6 +8,7 @@ from typing import ( TYPE_CHECKING, cast, + overload, ) import warnings @@ -93,6 +94,16 @@ _ITER_CHUNKSIZE = 10_000 +@overload +def tz_to_dtype(tz: tzinfo, unit: str = ...) -> DatetimeTZDtype: + ... + + +@overload +def tz_to_dtype(tz: None, unit: str = ...) -> np.dtype[np.datetime64]: + ... + + def tz_to_dtype( tz: tzinfo | None, unit: str = "ns" ) -> np.dtype[np.datetime64] | DatetimeTZDtype:
I'm getting bunches of bogus mypy failures on main locally, so will need the CI to tell me if this is OK.
https://api.github.com/repos/pandas-dev/pandas/pulls/56260
2023-11-30T16:20:12Z
2023-11-30T17:28:11Z
2023-11-30T17:28:11Z
2023-11-30T21:59:01Z
Less C89, most const, static funcs
diff --git a/pandas/_libs/src/vendored/ujson/python/objToJSON.c b/pandas/_libs/src/vendored/ujson/python/objToJSON.c index 89f101964aff7..6271791fe201e 100644 --- a/pandas/_libs/src/vendored/ujson/python/objToJSON.c +++ b/pandas/_libs/src/vendored/ujson/python/objToJSON.c @@ -146,12 +146,10 @@ typedef struct __PyObjectEncoder { enum PANDAS_FORMAT { SPLIT, RECORDS, INDEX, COLUMNS, VALUES }; -int PdBlock_iterNext(JSOBJ, JSONTypeContext *); +static int PdBlock_iterNext(JSOBJ, JSONTypeContext *); static TypeContext *createTypeContext(void) { - TypeContext *pc; - - pc = PyObject_Malloc(sizeof(TypeContext)); + TypeContext *pc = PyObject_Malloc(sizeof(TypeContext)); if (!pc) { PyErr_NoMemory(); return NULL; @@ -235,12 +233,10 @@ static PyObject *get_values(PyObject *obj) { static PyObject *get_sub_attr(PyObject *obj, char *attr, char *subAttr) { PyObject *tmp = PyObject_GetAttrString(obj, attr); - PyObject *ret; - if (tmp == 0) { return 0; } - ret = PyObject_GetAttrString(tmp, subAttr); + PyObject *ret = PyObject_GetAttrString(tmp, subAttr); Py_DECREF(tmp); return ret; @@ -248,12 +244,10 @@ static PyObject *get_sub_attr(PyObject *obj, char *attr, char *subAttr) { static Py_ssize_t get_attr_length(PyObject *obj, char *attr) { PyObject *tmp = PyObject_GetAttrString(obj, attr); - Py_ssize_t ret; - if (tmp == 0) { return 0; } - ret = PyObject_Length(tmp); + Py_ssize_t ret = PyObject_Length(tmp); Py_DECREF(tmp); if (ret == -1) { @@ -266,9 +260,8 @@ static Py_ssize_t get_attr_length(PyObject *obj, char *attr) { static npy_int64 get_long_attr(PyObject *o, const char *attr) { // NB we are implicitly assuming that o is a Timedelta or Timestamp, or NaT - npy_int64 long_val; PyObject *value = PyObject_GetAttrString(o, attr); - long_val = + const npy_int64 long_val = (PyLong_Check(value) ? PyLong_AsLongLong(value) : PyLong_AsLong(value)); Py_DECREF(value); @@ -293,20 +286,19 @@ static npy_int64 get_long_attr(PyObject *o, const char *attr) { } if (cReso == NPY_FR_us) { - long_val = long_val * 1000L; + return long_val * 1000L; } else if (cReso == NPY_FR_ms) { - long_val = long_val * 1000000L; + return long_val * 1000000L; } else if (cReso == NPY_FR_s) { - long_val = long_val * 1000000000L; + return long_val * 1000000000L; } return long_val; } static npy_float64 total_seconds(PyObject *td) { - npy_float64 double_val; PyObject *value = PyObject_CallMethod(td, "total_seconds", NULL); - double_val = PyFloat_AS_DOUBLE(value); + const npy_float64 double_val = PyFloat_AS_DOUBLE(value); Py_DECREF(value); return double_val; } @@ -361,10 +353,7 @@ static char *PyDateTimeToIsoCallback(JSOBJ obj, JSONTypeContext *tc, static char *PyTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, size_t *outLen) { PyObject *obj = (PyObject *)_obj; - PyObject *str; - PyObject *tmp; - - str = PyObject_CallMethod(obj, "isoformat", NULL); + PyObject *str = PyObject_CallMethod(obj, "isoformat", NULL); if (str == NULL) { *outLen = 0; if (!PyErr_Occurred()) { @@ -374,7 +363,7 @@ static char *PyTimeToJSON(JSOBJ _obj, JSONTypeContext *tc, size_t *outLen) { return NULL; } if (PyUnicode_Check(str)) { - tmp = str; + PyObject *tmp = str; str = PyUnicode_AsUTF8String(str); Py_DECREF(tmp); } @@ -398,21 +387,16 @@ static void NpyArr_freeItemValue(JSOBJ Py_UNUSED(_obj), JSONTypeContext *tc) { } } -int NpyArr_iterNextNone(JSOBJ Py_UNUSED(_obj), JSONTypeContext *Py_UNUSED(tc)) { +static int NpyArr_iterNextNone(JSOBJ Py_UNUSED(_obj), + JSONTypeContext *Py_UNUSED(tc)) { return 0; } -void NpyArr_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { - PyArrayObject *obj; - NpyArrContext *npyarr; - - if (GET_TC(tc)->newObj) { - obj = (PyArrayObject *)GET_TC(tc)->newObj; - } else { - obj = (PyArrayObject *)_obj; - } +static void NpyArr_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { + PyArrayObject *obj = + (PyArrayObject *)(GET_TC(tc)->newObj ? GET_TC(tc)->newObj : _obj); - npyarr = PyObject_Malloc(sizeof(NpyArrContext)); + NpyArrContext *npyarr = PyObject_Malloc(sizeof(NpyArrContext)); GET_TC(tc)->npyarr = npyarr; if (!npyarr) { @@ -446,7 +430,7 @@ void NpyArr_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { npyarr->rowLabels = GET_TC(tc)->rowLabels; } -void NpyArr_iterEnd(JSOBJ obj, JSONTypeContext *tc) { +static void NpyArr_iterEnd(JSOBJ obj, JSONTypeContext *tc) { NpyArrContext *npyarr = GET_TC(tc)->npyarr; if (npyarr) { @@ -455,10 +439,10 @@ void NpyArr_iterEnd(JSOBJ obj, JSONTypeContext *tc) { } } -void NpyArrPassThru_iterBegin(JSOBJ Py_UNUSED(obj), - JSONTypeContext *Py_UNUSED(tc)) {} +static void NpyArrPassThru_iterBegin(JSOBJ Py_UNUSED(obj), + JSONTypeContext *Py_UNUSED(tc)) {} -void NpyArrPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) { +static void NpyArrPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) { NpyArrContext *npyarr = GET_TC(tc)->npyarr; // finished this dimension, reset the data pointer npyarr->curdim--; @@ -471,7 +455,7 @@ void NpyArrPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) { NpyArr_freeItemValue(obj, tc); } -int NpyArr_iterNextItem(JSOBJ obj, JSONTypeContext *tc) { +static int NpyArr_iterNextItem(JSOBJ obj, JSONTypeContext *tc) { NpyArrContext *npyarr = GET_TC(tc)->npyarr; if (PyErr_Occurred()) { @@ -503,7 +487,7 @@ int NpyArr_iterNextItem(JSOBJ obj, JSONTypeContext *tc) { return 1; } -int NpyArr_iterNext(JSOBJ _obj, JSONTypeContext *tc) { +static int NpyArr_iterNext(JSOBJ _obj, JSONTypeContext *tc) { NpyArrContext *npyarr = GET_TC(tc)->npyarr; if (PyErr_Occurred()) { @@ -531,21 +515,20 @@ int NpyArr_iterNext(JSOBJ _obj, JSONTypeContext *tc) { return 1; } -JSOBJ NpyArr_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static JSOBJ NpyArr_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->itemValue; } -char *NpyArr_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, - size_t *outLen) { +static char *NpyArr_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, + size_t *outLen) { NpyArrContext *npyarr = GET_TC(tc)->npyarr; - npy_intp idx; char *cStr; if (GET_TC(tc)->iterNext == NpyArr_iterNextItem) { - idx = npyarr->index[npyarr->stridedim] - 1; + const npy_intp idx = npyarr->index[npyarr->stridedim] - 1; cStr = npyarr->columnLabels[idx]; } else { - idx = npyarr->index[npyarr->stridedim - npyarr->inc] - 1; + const npy_intp idx = npyarr->index[npyarr->stridedim - npyarr->inc] - 1; cStr = npyarr->rowLabels[idx]; } @@ -563,7 +546,7 @@ char *NpyArr_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, // Uses a dedicated NpyArrContext for each column. //============================================================================= -void PdBlockPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) { +static void PdBlockPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) { PdBlockContext *blkCtxt = GET_TC(tc)->pdblock; if (blkCtxt->transpose) { @@ -575,7 +558,7 @@ void PdBlockPassThru_iterEnd(JSOBJ obj, JSONTypeContext *tc) { NpyArr_freeItemValue(obj, tc); } -int PdBlock_iterNextItem(JSOBJ obj, JSONTypeContext *tc) { +static int PdBlock_iterNextItem(JSOBJ obj, JSONTypeContext *tc) { PdBlockContext *blkCtxt = GET_TC(tc)->pdblock; if (blkCtxt->colIdx >= blkCtxt->ncols) { @@ -587,20 +570,20 @@ int PdBlock_iterNextItem(JSOBJ obj, JSONTypeContext *tc) { return NpyArr_iterNextItem(obj, tc); } -char *PdBlock_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, - size_t *outLen) { +static char *PdBlock_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, + size_t *outLen) { PdBlockContext *blkCtxt = GET_TC(tc)->pdblock; NpyArrContext *npyarr = blkCtxt->npyCtxts[0]; - npy_intp idx; char *cStr; if (GET_TC(tc)->iterNext == PdBlock_iterNextItem) { - idx = blkCtxt->colIdx - 1; + const npy_intp idx = blkCtxt->colIdx - 1; cStr = npyarr->columnLabels[idx]; } else { - idx = GET_TC(tc)->iterNext != PdBlock_iterNext - ? npyarr->index[npyarr->stridedim - npyarr->inc] - 1 - : npyarr->index[npyarr->stridedim]; + const npy_intp idx = + GET_TC(tc)->iterNext != PdBlock_iterNext + ? npyarr->index[npyarr->stridedim - npyarr->inc] - 1 + : npyarr->index[npyarr->stridedim]; cStr = npyarr->rowLabels[idx]; } @@ -609,18 +592,18 @@ char *PdBlock_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, return cStr; } -char *PdBlock_iterGetName_Transpose(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, - size_t *outLen) { +static char *PdBlock_iterGetName_Transpose(JSOBJ Py_UNUSED(obj), + JSONTypeContext *tc, + size_t *outLen) { PdBlockContext *blkCtxt = GET_TC(tc)->pdblock; NpyArrContext *npyarr = blkCtxt->npyCtxts[blkCtxt->colIdx]; - npy_intp idx; char *cStr; if (GET_TC(tc)->iterNext == NpyArr_iterNextItem) { - idx = npyarr->index[npyarr->stridedim] - 1; + const npy_intp idx = npyarr->index[npyarr->stridedim] - 1; cStr = npyarr->columnLabels[idx]; } else { - idx = blkCtxt->colIdx; + const npy_intp idx = blkCtxt->colIdx; cStr = npyarr->rowLabels[idx]; } @@ -628,9 +611,8 @@ char *PdBlock_iterGetName_Transpose(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, return cStr; } -int PdBlock_iterNext(JSOBJ obj, JSONTypeContext *tc) { +static int PdBlock_iterNext(JSOBJ obj, JSONTypeContext *tc) { PdBlockContext *blkCtxt = GET_TC(tc)->pdblock; - NpyArrContext *npyarr; if (PyErr_Occurred() || ((JSONObjectEncoder *)tc->encoder)->errorMsg) { return 0; @@ -641,7 +623,7 @@ int PdBlock_iterNext(JSOBJ obj, JSONTypeContext *tc) { return 0; } } else { - npyarr = blkCtxt->npyCtxts[0]; + const NpyArrContext *npyarr = blkCtxt->npyCtxts[0]; if (npyarr->index[npyarr->stridedim] >= npyarr->dim) { return 0; } @@ -653,7 +635,8 @@ int PdBlock_iterNext(JSOBJ obj, JSONTypeContext *tc) { return 1; } -void PdBlockPassThru_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static void PdBlockPassThru_iterBegin(JSOBJ Py_UNUSED(obj), + JSONTypeContext *tc) { PdBlockContext *blkCtxt = GET_TC(tc)->pdblock; if (blkCtxt->transpose) { @@ -664,19 +647,14 @@ void PdBlockPassThru_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { } } -void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { - PyObject *obj, *values, *arrays, *array; - PdBlockContext *blkCtxt; - NpyArrContext *npyarr; - Py_ssize_t i; - - obj = (PyObject *)_obj; +static void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { + PyObject *obj = (PyObject *)_obj; GET_TC(tc)->iterGetName = GET_TC(tc)->transpose ? PdBlock_iterGetName_Transpose : PdBlock_iterGetName; - blkCtxt = PyObject_Malloc(sizeof(PdBlockContext)); + PdBlockContext *blkCtxt = PyObject_Malloc(sizeof(PdBlockContext)); if (!blkCtxt) { PyErr_NoMemory(); GET_TC(tc)->iterNext = NpyArr_iterNextNone; @@ -702,21 +680,21 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { return; } - arrays = get_sub_attr(obj, "_mgr", "column_arrays"); + PyObject *arrays = get_sub_attr(obj, "_mgr", "column_arrays"); if (!arrays) { GET_TC(tc)->iterNext = NpyArr_iterNextNone; return; } - for (i = 0; i < PyObject_Length(arrays); i++) { - array = PyList_GET_ITEM(arrays, i); + for (Py_ssize_t i = 0; i < PyObject_Length(arrays); i++) { + PyObject *array = PyList_GET_ITEM(arrays, i); if (!array) { GET_TC(tc)->iterNext = NpyArr_iterNextNone; goto ARR_RET; } // ensure we have a numpy array (i.e. np.asarray) - values = PyObject_CallMethod(array, "__array__", NULL); + PyObject *values = PyObject_CallMethod(array, "__array__", NULL); if ((!values) || (!PyArray_CheckExact(values))) { // Didn't get a numpy array ((JSONObjectEncoder *)tc->encoder)->errorMsg = ""; @@ -728,12 +706,11 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { // init a dedicated context for this column NpyArr_iterBegin(obj, tc); - npyarr = GET_TC(tc)->npyarr; GET_TC(tc)->itemValue = NULL; ((PyObjectEncoder *)tc->encoder)->npyCtxtPassthru = NULL; - blkCtxt->npyCtxts[i] = npyarr; + blkCtxt->npyCtxts[i] = GET_TC(tc)->npyarr; GET_TC(tc)->newObj = NULL; } GET_TC(tc)->npyarr = blkCtxt->npyCtxts[0]; @@ -743,18 +720,13 @@ void PdBlock_iterBegin(JSOBJ _obj, JSONTypeContext *tc) { Py_DECREF(arrays); } -void PdBlock_iterEnd(JSOBJ obj, JSONTypeContext *tc) { - PdBlockContext *blkCtxt; - NpyArrContext *npyarr; - int i; - +static void PdBlock_iterEnd(JSOBJ obj, JSONTypeContext *tc) { GET_TC(tc)->itemValue = NULL; - npyarr = GET_TC(tc)->npyarr; - - blkCtxt = GET_TC(tc)->pdblock; + NpyArrContext *npyarr = GET_TC(tc)->npyarr; + PdBlockContext *blkCtxt = GET_TC(tc)->pdblock; if (blkCtxt) { - for (i = 0; i < blkCtxt->ncols; i++) { + for (int i = 0; i < blkCtxt->ncols; i++) { npyarr = blkCtxt->npyCtxts[i]; if (npyarr) { if (npyarr->array) { @@ -780,34 +752,35 @@ void PdBlock_iterEnd(JSOBJ obj, JSONTypeContext *tc) { // Tuple iteration functions // itemValue is borrowed reference, no ref counting //============================================================================= -void Tuple_iterBegin(JSOBJ obj, JSONTypeContext *tc) { +static void Tuple_iterBegin(JSOBJ obj, JSONTypeContext *tc) { GET_TC(tc)->index = 0; GET_TC(tc)->size = PyTuple_GET_SIZE((PyObject *)obj); GET_TC(tc)->itemValue = NULL; } -int Tuple_iterNext(JSOBJ obj, JSONTypeContext *tc) { - PyObject *item; +static int Tuple_iterNext(JSOBJ obj, JSONTypeContext *tc) { if (GET_TC(tc)->index >= GET_TC(tc)->size) { return 0; } - item = PyTuple_GET_ITEM(obj, GET_TC(tc)->index); + PyObject *item = PyTuple_GET_ITEM(obj, GET_TC(tc)->index); GET_TC(tc)->itemValue = item; GET_TC(tc)->index++; return 1; } -void Tuple_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc)) {} +static void Tuple_iterEnd(JSOBJ Py_UNUSED(obj), + JSONTypeContext *Py_UNUSED(tc)) {} -JSOBJ Tuple_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static JSOBJ Tuple_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->itemValue; } -char *Tuple_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc), - size_t *Py_UNUSED(outLen)) { +static char *Tuple_iterGetName(JSOBJ Py_UNUSED(obj), + JSONTypeContext *Py_UNUSED(tc), + size_t *Py_UNUSED(outLen)) { return NULL; } @@ -815,20 +788,18 @@ char *Tuple_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc), // Set iteration functions // itemValue is borrowed reference, no ref counting //============================================================================= -void Set_iterBegin(JSOBJ obj, JSONTypeContext *tc) { +static void Set_iterBegin(JSOBJ obj, JSONTypeContext *tc) { GET_TC(tc)->itemValue = NULL; GET_TC(tc)->iterator = PyObject_GetIter(obj); } -int Set_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { - PyObject *item; - +static int Set_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { if (GET_TC(tc)->itemValue) { Py_DECREF(GET_TC(tc)->itemValue); GET_TC(tc)->itemValue = NULL; } - item = PyIter_Next(GET_TC(tc)->iterator); + PyObject *item = PyIter_Next(GET_TC(tc)->iterator); if (item == NULL) { return 0; @@ -838,7 +809,7 @@ int Set_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return 1; } -void Set_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static void Set_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { if (GET_TC(tc)->itemValue) { Py_DECREF(GET_TC(tc)->itemValue); GET_TC(tc)->itemValue = NULL; @@ -850,12 +821,13 @@ void Set_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { } } -JSOBJ Set_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static JSOBJ Set_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->itemValue; } -char *Set_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc), - size_t *Py_UNUSED(outLen)) { +static char *Set_iterGetName(JSOBJ Py_UNUSED(obj), + JSONTypeContext *Py_UNUSED(tc), + size_t *Py_UNUSED(outLen)) { return NULL; } @@ -864,13 +836,13 @@ char *Set_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc), // itemName ref is borrowed from PyObject_Dir (attrList). No refcount // itemValue ref is from PyObject_GetAttr. Ref counted //============================================================================= -void Dir_iterBegin(JSOBJ obj, JSONTypeContext *tc) { +static void Dir_iterBegin(JSOBJ obj, JSONTypeContext *tc) { GET_TC(tc)->attrList = PyObject_Dir(obj); GET_TC(tc)->index = 0; GET_TC(tc)->size = PyList_GET_SIZE(GET_TC(tc)->attrList); } -void Dir_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static void Dir_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { if (GET_TC(tc)->itemValue) { Py_DECREF(GET_TC(tc)->itemValue); GET_TC(tc)->itemValue = NULL; @@ -884,13 +856,10 @@ void Dir_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { Py_DECREF((PyObject *)GET_TC(tc)->attrList); } -int Dir_iterNext(JSOBJ _obj, JSONTypeContext *tc) { +static int Dir_iterNext(JSOBJ _obj, JSONTypeContext *tc) { PyObject *obj = (PyObject *)_obj; PyObject *itemValue = GET_TC(tc)->itemValue; PyObject *itemName = GET_TC(tc)->itemName; - PyObject *attr; - PyObject *attrName; - char *attrStr; if (PyErr_Occurred() || ((JSONObjectEncoder *)tc->encoder)->errorMsg) { return 0; @@ -907,9 +876,10 @@ int Dir_iterNext(JSOBJ _obj, JSONTypeContext *tc) { } for (; GET_TC(tc)->index < GET_TC(tc)->size; GET_TC(tc)->index++) { - attrName = PyList_GET_ITEM(GET_TC(tc)->attrList, GET_TC(tc)->index); - attr = PyUnicode_AsUTF8String(attrName); - attrStr = PyBytes_AS_STRING(attr); + PyObject *attrName = + PyList_GET_ITEM(GET_TC(tc)->attrList, GET_TC(tc)->index); + PyObject *attr = PyUnicode_AsUTF8String(attrName); + const char *attrStr = PyBytes_AS_STRING(attr); if (attrStr[0] == '_') { Py_DECREF(attr); @@ -949,12 +919,12 @@ int Dir_iterNext(JSOBJ _obj, JSONTypeContext *tc) { return 1; } -JSOBJ Dir_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static JSOBJ Dir_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->itemValue; } -char *Dir_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, - size_t *outLen) { +static char *Dir_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, + size_t *outLen) { *outLen = PyBytes_GET_SIZE(GET_TC(tc)->itemName); return PyBytes_AS_STRING(GET_TC(tc)->itemName); } @@ -963,12 +933,12 @@ char *Dir_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, // List iteration functions // itemValue is borrowed from object (which is list). No refcounting //============================================================================= -void List_iterBegin(JSOBJ obj, JSONTypeContext *tc) { +static void List_iterBegin(JSOBJ obj, JSONTypeContext *tc) { GET_TC(tc)->index = 0; GET_TC(tc)->size = PyList_GET_SIZE((PyObject *)obj); } -int List_iterNext(JSOBJ obj, JSONTypeContext *tc) { +static int List_iterNext(JSOBJ obj, JSONTypeContext *tc) { if (GET_TC(tc)->index >= GET_TC(tc)->size) { return 0; } @@ -978,21 +948,23 @@ int List_iterNext(JSOBJ obj, JSONTypeContext *tc) { return 1; } -void List_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc)) {} +static void List_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc)) { +} -JSOBJ List_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static JSOBJ List_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->itemValue; } -char *List_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc), - size_t *Py_UNUSED(outLen)) { +static char *List_iterGetName(JSOBJ Py_UNUSED(obj), + JSONTypeContext *Py_UNUSED(tc), + size_t *Py_UNUSED(outLen)) { return NULL; } //============================================================================= // pandas Index iteration functions //============================================================================= -void Index_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static void Index_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { GET_TC(tc)->index = 0; GET_TC(tc)->cStr = PyObject_Malloc(20 * sizeof(char)); if (!GET_TC(tc)->cStr) { @@ -1000,13 +972,12 @@ void Index_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { } } -int Index_iterNext(JSOBJ obj, JSONTypeContext *tc) { - Py_ssize_t index; +static int Index_iterNext(JSOBJ obj, JSONTypeContext *tc) { if (!GET_TC(tc)->cStr) { return 0; } - index = GET_TC(tc)->index; + const Py_ssize_t index = GET_TC(tc)->index; Py_XDECREF(GET_TC(tc)->itemValue); if (index == 0) { memcpy(GET_TC(tc)->cStr, "name", sizeof(char) * 5); @@ -1025,14 +996,15 @@ int Index_iterNext(JSOBJ obj, JSONTypeContext *tc) { return 1; } -void Index_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *Py_UNUSED(tc)) {} +static void Index_iterEnd(JSOBJ Py_UNUSED(obj), + JSONTypeContext *Py_UNUSED(tc)) {} -JSOBJ Index_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static JSOBJ Index_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->itemValue; } -char *Index_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, - size_t *outLen) { +static char *Index_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, + size_t *outLen) { *outLen = strlen(GET_TC(tc)->cStr); return GET_TC(tc)->cStr; } @@ -1040,7 +1012,7 @@ char *Index_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, //============================================================================= // pandas Series iteration functions //============================================================================= -void Series_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static void Series_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { PyObjectEncoder *enc = (PyObjectEncoder *)tc->encoder; GET_TC(tc)->index = 0; GET_TC(tc)->cStr = PyObject_Malloc(20 * sizeof(char)); @@ -1050,13 +1022,12 @@ void Series_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { } } -int Series_iterNext(JSOBJ obj, JSONTypeContext *tc) { - Py_ssize_t index; +static int Series_iterNext(JSOBJ obj, JSONTypeContext *tc) { if (!GET_TC(tc)->cStr) { return 0; } - index = GET_TC(tc)->index; + const Py_ssize_t index = GET_TC(tc)->index; Py_XDECREF(GET_TC(tc)->itemValue); if (index == 0) { memcpy(GET_TC(tc)->cStr, "name", sizeof(char) * 5); @@ -1078,17 +1049,17 @@ int Series_iterNext(JSOBJ obj, JSONTypeContext *tc) { return 1; } -void Series_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static void Series_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { PyObjectEncoder *enc = (PyObjectEncoder *)tc->encoder; enc->outputFormat = enc->originalOutputFormat; } -JSOBJ Series_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static JSOBJ Series_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->itemValue; } -char *Series_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, - size_t *outLen) { +static char *Series_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, + size_t *outLen) { *outLen = strlen(GET_TC(tc)->cStr); return GET_TC(tc)->cStr; } @@ -1096,7 +1067,7 @@ char *Series_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, //============================================================================= // pandas DataFrame iteration functions //============================================================================= -void DataFrame_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static void DataFrame_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { PyObjectEncoder *enc = (PyObjectEncoder *)tc->encoder; GET_TC(tc)->index = 0; GET_TC(tc)->cStr = PyObject_Malloc(20 * sizeof(char)); @@ -1106,13 +1077,12 @@ void DataFrame_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { } } -int DataFrame_iterNext(JSOBJ obj, JSONTypeContext *tc) { - Py_ssize_t index; +static int DataFrame_iterNext(JSOBJ obj, JSONTypeContext *tc) { if (!GET_TC(tc)->cStr) { return 0; } - index = GET_TC(tc)->index; + const Py_ssize_t index = GET_TC(tc)->index; Py_XDECREF(GET_TC(tc)->itemValue); if (index == 0) { memcpy(GET_TC(tc)->cStr, "columns", sizeof(char) * 8); @@ -1132,17 +1102,17 @@ int DataFrame_iterNext(JSOBJ obj, JSONTypeContext *tc) { return 1; } -void DataFrame_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static void DataFrame_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { PyObjectEncoder *enc = (PyObjectEncoder *)tc->encoder; enc->outputFormat = enc->originalOutputFormat; } -JSOBJ DataFrame_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static JSOBJ DataFrame_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->itemValue; } -char *DataFrame_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, - size_t *outLen) { +static char *DataFrame_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, + size_t *outLen) { *outLen = strlen(GET_TC(tc)->cStr); return GET_TC(tc)->cStr; } @@ -1152,13 +1122,11 @@ char *DataFrame_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, // itemName might converted to string (Python_Str). Do refCounting // itemValue is borrowed from object (which is dict). No refCounting //============================================================================= -void Dict_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static void Dict_iterBegin(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { GET_TC(tc)->index = 0; } -int Dict_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { - PyObject *itemNameTmp; - +static int Dict_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { if (GET_TC(tc)->itemName) { Py_DECREF(GET_TC(tc)->itemName); GET_TC(tc)->itemName = NULL; @@ -1173,7 +1141,7 @@ int Dict_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { GET_TC(tc)->itemName = PyUnicode_AsUTF8String(GET_TC(tc)->itemName); } else if (!PyBytes_Check(GET_TC(tc)->itemName)) { GET_TC(tc)->itemName = PyObject_Str(GET_TC(tc)->itemName); - itemNameTmp = GET_TC(tc)->itemName; + PyObject *itemNameTmp = GET_TC(tc)->itemName; GET_TC(tc)->itemName = PyUnicode_AsUTF8String(GET_TC(tc)->itemName); Py_DECREF(itemNameTmp); } else { @@ -1182,7 +1150,7 @@ int Dict_iterNext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return 1; } -void Dict_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static void Dict_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { if (GET_TC(tc)->itemName) { Py_DECREF(GET_TC(tc)->itemName); GET_TC(tc)->itemName = NULL; @@ -1190,21 +1158,19 @@ void Dict_iterEnd(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { Py_DECREF(GET_TC(tc)->dictObj); } -JSOBJ Dict_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static JSOBJ Dict_iterGetValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->itemValue; } -char *Dict_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, - size_t *outLen) { +static char *Dict_iterGetName(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc, + size_t *outLen) { *outLen = PyBytes_GET_SIZE(GET_TC(tc)->itemName); return PyBytes_AS_STRING(GET_TC(tc)->itemName); } -void NpyArr_freeLabels(char **labels, npy_intp len) { - npy_intp i; - +static void NpyArr_freeLabels(char **labels, npy_intp len) { if (labels) { - for (i = 0; i < len; i++) { + for (npy_intp i = 0; i < len; i++) { PyObject_Free(labels[i]); } PyObject_Free(labels); @@ -1228,17 +1194,11 @@ void NpyArr_freeLabels(char **labels, npy_intp len) { * this has instead just stringified any input save for datetime values, * which may need to be represented in various formats. */ -char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc, - npy_intp num) { +static char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc, + npy_intp num) { // NOTE this function steals a reference to labels. PyObject *item = NULL; - size_t len; - npy_intp i, stride; - char **ret; - char *dataptr, *cLabel; - int type_num; - PyArray_Descr *dtype; - NPY_DATETIMEUNIT base = enc->datetimeUnit; + const NPY_DATETIMEUNIT base = enc->datetimeUnit; if (!labels) { return 0; @@ -1251,23 +1211,23 @@ char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc, return 0; } - ret = PyObject_Malloc(sizeof(char *) * num); + char **ret = PyObject_Malloc(sizeof(char *) * num); if (!ret) { PyErr_NoMemory(); Py_DECREF(labels); return 0; } - for (i = 0; i < num; i++) { + for (npy_intp i = 0; i < num; i++) { ret[i] = NULL; } - stride = PyArray_STRIDE(labels, 0); - dataptr = PyArray_DATA(labels); - type_num = PyArray_TYPE(labels); - dtype = PyArray_DESCR(labels); + const npy_intp stride = PyArray_STRIDE(labels, 0); + char *dataptr = PyArray_DATA(labels); + const int type_num = PyArray_TYPE(labels); + PyArray_Descr *dtype = PyArray_DESCR(labels); - for (i = 0; i < num; i++) { + for (npy_intp i = 0; i < num; i++) { item = PyArray_GETITEM(labels, dataptr); if (!item) { NpyArr_freeLabels(ret, num); @@ -1298,6 +1258,8 @@ char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc, } } + size_t len; + char *cLabel; if (is_datetimelike) { if (i8date == get_nat()) { len = 4; @@ -1370,7 +1332,7 @@ char **NpyArr_encodeLabels(PyArrayObject *labels, PyObjectEncoder *enc, return ret; } -void Object_invokeDefaultHandler(PyObject *obj, PyObjectEncoder *enc) { +static void Object_invokeDefaultHandler(PyObject *obj, PyObjectEncoder *enc) { PyObject *tmpObj = NULL; tmpObj = PyObject_CallFunctionObjArgs(enc->defaultHandler, obj, NULL); if (!PyErr_Occurred()) { @@ -1384,14 +1346,7 @@ void Object_invokeDefaultHandler(PyObject *obj, PyObjectEncoder *enc) { return; } -void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { - PyObject *obj, *exc, *toDictFunc, *tmpObj, *values; - TypeContext *pc; - PyObjectEncoder *enc; - double val; - npy_int64 value; - int unit; - +static void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { tc->prv = NULL; if (!_obj) { @@ -1399,8 +1354,8 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { return; } - obj = (PyObject *)_obj; - enc = (PyObjectEncoder *)tc->encoder; + PyObject *obj = (PyObject *)_obj; + PyObjectEncoder *enc = (PyObjectEncoder *)tc->encoder; if (PyBool_Check(obj)) { tc->type = (obj == Py_True) ? JT_TRUE : JT_FALSE; @@ -1410,7 +1365,7 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { return; } - pc = createTypeContext(); + TypeContext *pc = createTypeContext(); if (!pc) { tc->type = JT_INVALID; return; @@ -1418,9 +1373,7 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { tc->prv = pc; if (PyTypeNum_ISDATETIME(enc->npyType)) { - int64_t longVal; - - longVal = *(npy_int64 *)enc->npyValue; + const int64_t longVal = *(npy_int64 *)enc->npyValue; if (longVal == get_nat()) { tc->type = JT_NULL; } else { @@ -1468,7 +1421,7 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { return; } else if (PyFloat_Check(obj)) { - val = PyFloat_AS_DOUBLE(obj); + const double val = PyFloat_AS_DOUBLE(obj); if (npy_isnan(val) || npy_isinf(val)) { tc->type = JT_NULL; } else { @@ -1535,12 +1488,10 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } return; } else if (PyDelta_Check(obj)) { - if (PyObject_HasAttrString(obj, "_value")) { - // pd.Timedelta object or pd.NaT - value = get_long_attr(obj, "_value"); - } else { - value = total_seconds(obj) * 1000000000LL; // nanoseconds per sec - } + npy_int64 value = + PyObject_HasAttrString(obj, "_value") ? get_long_attr(obj, "_value") + : // pd.Timedelta object or pd.NaT + total_seconds(obj) * 1000000000LL; // nanoseconds per sec if (value == get_nat()) { tc->type = JT_NULL; @@ -1549,14 +1500,12 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { pc->PyTypeToUTF8 = NpyTimeDeltaToIsoCallback; tc->type = JT_UTF8; } else { - unit = ((PyObjectEncoder *)tc->encoder)->datetimeUnit; + const int unit = ((PyObjectEncoder *)tc->encoder)->datetimeUnit; if (scaleNanosecToUnit(&value, unit) != 0) { // TODO(username): Add some kind of error handling here } - exc = PyErr_Occurred(); - - if (exc && PyErr_ExceptionMatches(PyExc_OverflowError)) { + if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_OverflowError)) { goto INVALID; } @@ -1569,9 +1518,7 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { PyArray_CastScalarToCtype(obj, &(pc->longValue), PyArray_DescrFromType(NPY_INT64)); - exc = PyErr_Occurred(); - - if (exc && PyErr_ExceptionMatches(PyExc_OverflowError)) { + if (PyErr_Occurred() && PyErr_ExceptionMatches(PyExc_OverflowError)) { goto INVALID; } @@ -1640,11 +1587,11 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { if (enc->outputFormat == INDEX || enc->outputFormat == COLUMNS) { tc->type = JT_OBJECT; - tmpObj = PyObject_GetAttrString(obj, "index"); + PyObject *tmpObj = PyObject_GetAttrString(obj, "index"); if (!tmpObj) { goto INVALID; } - values = get_values(tmpObj); + PyObject *values = get_values(tmpObj); Py_DECREF(tmpObj); if (!values) { goto INVALID; @@ -1722,11 +1669,11 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { tc->type = JT_ARRAY; } else if (enc->outputFormat == RECORDS) { tc->type = JT_ARRAY; - tmpObj = PyObject_GetAttrString(obj, "columns"); + PyObject *tmpObj = PyObject_GetAttrString(obj, "columns"); if (!tmpObj) { goto INVALID; } - values = get_values(tmpObj); + PyObject *values = get_values(tmpObj); if (!values) { Py_DECREF(tmpObj); goto INVALID; @@ -1740,13 +1687,13 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { } } else if (enc->outputFormat == INDEX || enc->outputFormat == COLUMNS) { tc->type = JT_OBJECT; - tmpObj = + PyObject *tmpObj = (enc->outputFormat == INDEX ? PyObject_GetAttrString(obj, "index") : PyObject_GetAttrString(obj, "columns")); if (!tmpObj) { goto INVALID; } - values = get_values(tmpObj); + PyObject *values = get_values(tmpObj); if (!values) { Py_DECREF(tmpObj); goto INVALID; @@ -1824,7 +1771,7 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { return; } - toDictFunc = PyObject_GetAttrString(obj, "toDict"); + PyObject *toDictFunc = PyObject_GetAttrString(obj, "toDict"); if (toDictFunc) { PyObject *tuple = PyTuple_New(0); @@ -1876,7 +1823,7 @@ void Object_beginTypeContext(JSOBJ _obj, JSONTypeContext *tc) { return; } -void Object_endTypeContext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static void Object_endTypeContext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { if (tc->prv) { Py_XDECREF(GET_TC(tc)->newObj); GET_TC(tc)->newObj = NULL; @@ -1891,21 +1838,21 @@ void Object_endTypeContext(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { } } -const char *Object_getStringValue(JSOBJ obj, JSONTypeContext *tc, - size_t *_outLen) { +static const char *Object_getStringValue(JSOBJ obj, JSONTypeContext *tc, + size_t *_outLen) { return GET_TC(tc)->PyTypeToUTF8(obj, tc, _outLen); } -JSINT64 Object_getLongValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static JSINT64 Object_getLongValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->longValue; } -double Object_getDoubleValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { +static double Object_getDoubleValue(JSOBJ Py_UNUSED(obj), JSONTypeContext *tc) { return GET_TC(tc)->doubleValue; } -const char *Object_getBigNumStringValue(JSOBJ obj, JSONTypeContext *tc, - size_t *_outLen) { +static const char *Object_getBigNumStringValue(JSOBJ obj, JSONTypeContext *tc, + size_t *_outLen) { PyObject *repr = PyObject_Str(obj); const char *str = PyUnicode_AsUTF8AndSize(repr, (Py_ssize_t *)_outLen); char *bytes = PyObject_Malloc(*_outLen + 1); @@ -1919,23 +1866,24 @@ const char *Object_getBigNumStringValue(JSOBJ obj, JSONTypeContext *tc, static void Object_releaseObject(JSOBJ _obj) { Py_DECREF((PyObject *)_obj); } -void Object_iterBegin(JSOBJ obj, JSONTypeContext *tc) { +static void Object_iterBegin(JSOBJ obj, JSONTypeContext *tc) { GET_TC(tc)->iterBegin(obj, tc); } -int Object_iterNext(JSOBJ obj, JSONTypeContext *tc) { +static int Object_iterNext(JSOBJ obj, JSONTypeContext *tc) { return GET_TC(tc)->iterNext(obj, tc); } -void Object_iterEnd(JSOBJ obj, JSONTypeContext *tc) { +static void Object_iterEnd(JSOBJ obj, JSONTypeContext *tc) { GET_TC(tc)->iterEnd(obj, tc); } -JSOBJ Object_iterGetValue(JSOBJ obj, JSONTypeContext *tc) { +static JSOBJ Object_iterGetValue(JSOBJ obj, JSONTypeContext *tc) { return GET_TC(tc)->iterGetValue(obj, tc); } -char *Object_iterGetName(JSOBJ obj, JSONTypeContext *tc, size_t *outLen) { +static char *Object_iterGetName(JSOBJ obj, JSONTypeContext *tc, + size_t *outLen) { return GET_TC(tc)->iterGetName(obj, tc, outLen); } @@ -1962,9 +1910,6 @@ PyObject *objToJSON(PyObject *Py_UNUSED(self), PyObject *args, "indent", NULL}; - char buffer[65536]; - char *ret; - PyObject *newobj; PyObject *oinput = NULL; PyObject *oensureAscii = NULL; int idoublePrecision = 10; // default double precision setting @@ -1994,9 +1939,9 @@ PyObject *objToJSON(PyObject *Py_UNUSED(self), PyObject *args, PyObject_Free, -1, // recursionMax idoublePrecision, - 1, // forceAscii - 0, // encodeHTMLChars - 0, // indent + 1, // forceAscii + 0, // encodeHTMLChars + indent, // indent }}; JSONObjectEncoder *encoder = (JSONObjectEncoder *)&pyEncoder; @@ -2080,7 +2025,9 @@ PyObject *objToJSON(PyObject *Py_UNUSED(self), PyObject *args, encoder->indent = indent; pyEncoder.originalOutputFormat = pyEncoder.outputFormat; - ret = JSON_EncodeObject(oinput, encoder, buffer, sizeof(buffer)); + + char buffer[65536]; + char *ret = JSON_EncodeObject(oinput, encoder, buffer, sizeof(buffer)); if (PyErr_Occurred()) { return NULL; } @@ -2093,7 +2040,7 @@ PyObject *objToJSON(PyObject *Py_UNUSED(self), PyObject *args, return NULL; } - newobj = PyUnicode_FromString(ret); + PyObject *newobj = PyUnicode_FromString(ret); if (ret != buffer) { encoder->free(ret);
Will have to do this in a few passes for other files, but generally we: 1. Are removing C89 style variable declarations at the top of functions 2. Adding `const` qualifiers where we can 3. Making more functions static that aren't intended to be linked outside of their translation unit Point 1 helps with code readability, Point 2 can help with code safety and compiler optimization. Point 3 helps with code structure and makes functions "local" to their translaction unit instead of "global"
https://api.github.com/repos/pandas-dev/pandas/pulls/56254
2023-11-30T08:07:47Z
2023-11-30T17:29:14Z
2023-11-30T17:29:14Z
2023-11-30T17:29:21Z
JSON code removals and cleanups
diff --git a/pandas/_libs/src/vendored/ujson/python/JSONtoObj.c b/pandas/_libs/src/vendored/ujson/python/JSONtoObj.c index 147282c476c3b..e7c58d498f9be 100644 --- a/pandas/_libs/src/vendored/ujson/python/JSONtoObj.c +++ b/pandas/_libs/src/vendored/ujson/python/JSONtoObj.c @@ -45,16 +45,11 @@ Numeric decoder derived from TCL library #include <Python.h> #include <numpy/arrayobject.h> -#define PRINTMARK() - typedef struct __PyObjectDecoder { JSONObjectDecoder dec; void *npyarr; // Numpy context buffer void *npyarr_addr; // Ref to npyarr ptr to track DECREF calls - npy_intp curdim; // Current array dimension - - PyArray_Descr *dtype; } PyObjectDecoder; typedef struct __NpyArrContext { @@ -63,39 +58,16 @@ typedef struct __NpyArrContext { PyArray_Dims shape; PyObjectDecoder *dec; - - npy_intp i; - npy_intp elsize; - npy_intp elcount; } NpyArrContext; -// Numpy handling based on numpy internal code, specifically the function -// PyArray_FromIter. - -// numpy related functions are inter-dependent so declare them all here, -// to ensure the compiler catches any errors - -// standard numpy array handling -JSOBJ Object_npyNewArray(void *prv, void *decoder); -JSOBJ Object_npyEndArray(void *prv, JSOBJ obj); -int Object_npyArrayAddItem(void *prv, JSOBJ obj, JSOBJ value); - -// for more complex dtypes (object and string) fill a standard Python list -// and convert to a numpy array when done. -JSOBJ Object_npyNewArrayList(void *prv, void *decoder); -JSOBJ Object_npyEndArrayList(void *prv, JSOBJ obj); -int Object_npyArrayListAddItem(void *prv, JSOBJ obj, JSOBJ value); - // free the numpy context buffer void Npy_releaseContext(NpyArrContext *npyarr) { - PRINTMARK(); if (npyarr) { if (npyarr->shape.ptr) { PyObject_Free(npyarr->shape.ptr); } if (npyarr->dec) { npyarr->dec->npyarr = NULL; - npyarr->dec->curdim = 0; } Py_XDECREF(npyarr->labels[0]); Py_XDECREF(npyarr->labels[1]); @@ -104,318 +76,58 @@ void Npy_releaseContext(NpyArrContext *npyarr) { } } -JSOBJ Object_npyNewArray(void *prv, void *_decoder) { - NpyArrContext *npyarr; - PyObjectDecoder *decoder = (PyObjectDecoder *)_decoder; - PRINTMARK(); - if (decoder->curdim <= 0) { - // start of array - initialise the context buffer - npyarr = decoder->npyarr = PyObject_Malloc(sizeof(NpyArrContext)); - decoder->npyarr_addr = npyarr; - - if (!npyarr) { - PyErr_NoMemory(); - return NULL; - } - - npyarr->dec = decoder; - npyarr->labels[0] = npyarr->labels[1] = NULL; - - npyarr->shape.ptr = PyObject_Malloc(sizeof(npy_intp) * NPY_MAXDIMS); - npyarr->shape.len = 1; - npyarr->ret = NULL; - - npyarr->elsize = 0; - npyarr->elcount = 4; - npyarr->i = 0; - } else { - // starting a new dimension continue the current array (and reshape - // after) - npyarr = (NpyArrContext *)decoder->npyarr; - if (decoder->curdim >= npyarr->shape.len) { - npyarr->shape.len++; - } - } - - npyarr->shape.ptr[decoder->curdim] = 0; - decoder->curdim++; - return npyarr; -} - -PyObject *Npy_returnLabelled(NpyArrContext *npyarr) { - PyObject *ret = npyarr->ret; - npy_intp i; - - if (npyarr->labels[0] || npyarr->labels[1]) { - // finished decoding, build tuple with values and labels - ret = PyTuple_New(npyarr->shape.len + 1); - for (i = 0; i < npyarr->shape.len; i++) { - if (npyarr->labels[i]) { - PyTuple_SET_ITEM(ret, i + 1, npyarr->labels[i]); - npyarr->labels[i] = NULL; - } else { - Py_INCREF(Py_None); - PyTuple_SET_ITEM(ret, i + 1, Py_None); - } - } - PyTuple_SET_ITEM(ret, 0, npyarr->ret); - } - - return ret; -} - -JSOBJ Object_npyEndArray(void *prv, JSOBJ obj) { - PyObject *ret; - char *new_data; - NpyArrContext *npyarr = (NpyArrContext *)obj; - int emptyType = NPY_DEFAULT_TYPE; - npy_intp i; - PRINTMARK(); - if (!npyarr) { - return NULL; - } - - ret = npyarr->ret; - i = npyarr->i; - - npyarr->dec->curdim--; - - if (i == 0 || !npyarr->ret) { - // empty array would not have been initialised so do it now. - if (npyarr->dec->dtype) { - emptyType = npyarr->dec->dtype->type_num; - } - npyarr->ret = ret = - PyArray_EMPTY(npyarr->shape.len, npyarr->shape.ptr, emptyType, 0); - } else if (npyarr->dec->curdim <= 0) { - // realloc to final size - new_data = PyDataMem_RENEW(PyArray_DATA(ret), i * npyarr->elsize); - if (new_data == NULL) { - PyErr_NoMemory(); - Npy_releaseContext(npyarr); - return NULL; - } - ((PyArrayObject *)ret)->data = (void *)new_data; - // PyArray_BYTES(ret) = new_data; - } - - if (npyarr->dec->curdim <= 0) { - // finished decoding array, reshape if necessary - if (npyarr->shape.len > 1) { - npyarr->ret = - PyArray_Newshape((PyArrayObject *)ret, &npyarr->shape, NPY_ANYORDER); - Py_DECREF(ret); - } - - ret = Npy_returnLabelled(npyarr); - - npyarr->ret = NULL; - Npy_releaseContext(npyarr); - } - - return ret; -} - -int Object_npyArrayAddItem(void *prv, JSOBJ obj, JSOBJ value) { - PyObject *type; - PyArray_Descr *dtype; - npy_intp i; - char *new_data, *item; - NpyArrContext *npyarr = (NpyArrContext *)obj; - PRINTMARK(); - if (!npyarr) { - return 0; - } - - i = npyarr->i; - - npyarr->shape.ptr[npyarr->dec->curdim - 1]++; - - if (PyArray_Check((PyObject *)value)) { - // multidimensional array, keep decoding values. - return 1; - } - - if (!npyarr->ret) { - // Array not initialised yet. - // We do it here so we can 'sniff' the data type if none was provided - if (!npyarr->dec->dtype) { - type = PyObject_Type(value); - if (!PyArray_DescrConverter(type, &dtype)) { - Py_DECREF(type); - goto fail; - } - Py_INCREF(dtype); - Py_DECREF(type); - } else { - dtype = PyArray_DescrNew(npyarr->dec->dtype); - } - - // If it's an object or string then fill a Python list and subsequently - // convert. Otherwise we would need to somehow mess about with - // reference counts when renewing memory. - npyarr->elsize = dtype->elsize; - if (PyDataType_REFCHK(dtype) || npyarr->elsize == 0) { - Py_XDECREF(dtype); - - if (npyarr->dec->curdim > 1) { - PyErr_SetString(PyExc_ValueError, - "Cannot decode multidimensional arrays with " - "variable length elements to numpy"); - goto fail; - } - npyarr->elcount = 0; - npyarr->ret = PyList_New(0); - if (!npyarr->ret) { - goto fail; - } - ((JSONObjectDecoder *)npyarr->dec)->newArray = Object_npyNewArrayList; - ((JSONObjectDecoder *)npyarr->dec)->arrayAddItem = - Object_npyArrayListAddItem; - ((JSONObjectDecoder *)npyarr->dec)->endArray = Object_npyEndArrayList; - return Object_npyArrayListAddItem(prv, obj, value); - } - - npyarr->ret = PyArray_NewFromDescr(&PyArray_Type, dtype, 1, - &npyarr->elcount, NULL, NULL, 0, NULL); - - if (!npyarr->ret) { - goto fail; - } - } - - if (i >= npyarr->elcount) { - // Grow PyArray_DATA(ret): - // this is similar for the strategy for PyListObject, but we use - // 50% overallocation => 0, 4, 8, 14, 23, 36, 56, 86 ... - if (npyarr->elsize == 0) { - PyErr_SetString(PyExc_ValueError, - "Cannot decode multidimensional arrays with " - "variable length elements to numpy"); - goto fail; - } - - npyarr->elcount = (i >> 1) + (i < 4 ? 4 : 2) + i; - if (npyarr->elcount <= NPY_MAX_INTP / npyarr->elsize) { - new_data = PyDataMem_RENEW(PyArray_DATA(npyarr->ret), - npyarr->elcount * npyarr->elsize); - } else { - PyErr_NoMemory(); - goto fail; - } - ((PyArrayObject *)npyarr->ret)->data = (void *)new_data; - - // PyArray_BYTES(npyarr->ret) = new_data; - } - - PyArray_DIMS(npyarr->ret)[0] = i + 1; - - if ((item = PyArray_GETPTR1(npyarr->ret, i)) == NULL || - PyArray_SETITEM(npyarr->ret, item, value) == -1) { - goto fail; - } - - Py_DECREF((PyObject *)value); - npyarr->i++; - return 1; - -fail: - - Npy_releaseContext(npyarr); - return 0; -} - -JSOBJ Object_npyNewArrayList(void *prv, void *_decoder) { - PyObjectDecoder *decoder = (PyObjectDecoder *)_decoder; - PRINTMARK(); - PyErr_SetString(PyExc_ValueError, - "nesting not supported for object or variable length dtypes"); - Npy_releaseContext(decoder->npyarr); - return NULL; -} - -JSOBJ Object_npyEndArrayList(void *prv, JSOBJ obj) { - PyObject *list, *ret; - NpyArrContext *npyarr = (NpyArrContext *)obj; - PRINTMARK(); - if (!npyarr) { - return NULL; - } - - // convert decoded list to numpy array - list = (PyObject *)npyarr->ret; - npyarr->ret = PyArray_FROM_O(list); - - ret = Npy_returnLabelled(npyarr); - npyarr->ret = list; - - ((JSONObjectDecoder *)npyarr->dec)->newArray = Object_npyNewArray; - ((JSONObjectDecoder *)npyarr->dec)->arrayAddItem = Object_npyArrayAddItem; - ((JSONObjectDecoder *)npyarr->dec)->endArray = Object_npyEndArray; - Npy_releaseContext(npyarr); - return ret; -} - -int Object_npyArrayListAddItem(void *prv, JSOBJ obj, JSOBJ value) { - NpyArrContext *npyarr = (NpyArrContext *)obj; - PRINTMARK(); - if (!npyarr) { - return 0; - } - PyList_Append((PyObject *)npyarr->ret, value); - Py_DECREF((PyObject *)value); - npyarr->elcount++; - return 1; -} - -int Object_objectAddKey(void *prv, JSOBJ obj, JSOBJ name, JSOBJ value) { +static int Object_objectAddKey(void *prv, JSOBJ obj, JSOBJ name, JSOBJ value) { int ret = PyDict_SetItem(obj, name, value); Py_DECREF((PyObject *)name); Py_DECREF((PyObject *)value); return ret == 0 ? 1 : 0; } -int Object_arrayAddItem(void *prv, JSOBJ obj, JSOBJ value) { +static int Object_arrayAddItem(void *prv, JSOBJ obj, JSOBJ value) { int ret = PyList_Append(obj, value); Py_DECREF((PyObject *)value); return ret == 0 ? 1 : 0; } -JSOBJ Object_newString(void *prv, wchar_t *start, wchar_t *end) { +static JSOBJ Object_newString(void *prv, wchar_t *start, wchar_t *end) { return PyUnicode_FromWideChar(start, (end - start)); } -JSOBJ Object_newTrue(void *prv) { Py_RETURN_TRUE; } +static JSOBJ Object_newTrue(void *prv) { Py_RETURN_TRUE; } -JSOBJ Object_newFalse(void *prv) { Py_RETURN_FALSE; } +static JSOBJ Object_newFalse(void *prv) { Py_RETURN_FALSE; } -JSOBJ Object_newNull(void *prv) { Py_RETURN_NONE; } +static JSOBJ Object_newNull(void *prv) { Py_RETURN_NONE; } -JSOBJ Object_newPosInf(void *prv) { return PyFloat_FromDouble(Py_HUGE_VAL); } +static JSOBJ Object_newPosInf(void *prv) { + return PyFloat_FromDouble(Py_HUGE_VAL); +} -JSOBJ Object_newNegInf(void *prv) { return PyFloat_FromDouble(-Py_HUGE_VAL); } +static JSOBJ Object_newNegInf(void *prv) { + return PyFloat_FromDouble(-Py_HUGE_VAL); +} -JSOBJ Object_newObject(void *prv, void *decoder) { return PyDict_New(); } +static JSOBJ Object_newObject(void *prv, void *decoder) { return PyDict_New(); } -JSOBJ Object_endObject(void *prv, JSOBJ obj) { return obj; } +static JSOBJ Object_endObject(void *prv, JSOBJ obj) { return obj; } -JSOBJ Object_newArray(void *prv, void *decoder) { return PyList_New(0); } +static JSOBJ Object_newArray(void *prv, void *decoder) { return PyList_New(0); } -JSOBJ Object_endArray(void *prv, JSOBJ obj) { return obj; } +static JSOBJ Object_endArray(void *prv, JSOBJ obj) { return obj; } -JSOBJ Object_newInteger(void *prv, JSINT32 value) { +static JSOBJ Object_newInteger(void *prv, JSINT32 value) { return PyLong_FromLong((long)value); } -JSOBJ Object_newLong(void *prv, JSINT64 value) { +static JSOBJ Object_newLong(void *prv, JSINT64 value) { return PyLong_FromLongLong(value); } -JSOBJ Object_newUnsignedLong(void *prv, JSUINT64 value) { +static JSOBJ Object_newUnsignedLong(void *prv, JSUINT64 value) { return PyLong_FromUnsignedLongLong(value); } -JSOBJ Object_newDouble(void *prv, double value) { +static JSOBJ Object_newDouble(void *prv, double value) { return PyFloat_FromDouble(value); } @@ -451,7 +163,6 @@ PyObject *JSONToObj(PyObject *self, PyObject *args, PyObject *kwargs) { dec.prv = NULL; pyDecoder.dec = dec; - pyDecoder.curdim = 0; pyDecoder.npyarr = NULL; pyDecoder.npyarr_addr = NULL;
Not sure this code ever did anything - seems to be optimized out. Still more to be done but this works for a first pass As far as the functions go, adding `static` is a best practice for functions that aren't meant to be exported from a shared library (C defaults functions to extern visibility, which you could argue is unfortunate)
https://api.github.com/repos/pandas-dev/pandas/pulls/56252
2023-11-30T07:10:36Z
2023-11-30T17:31:06Z
2023-11-30T17:31:06Z
2023-11-30T20:57:08Z
BUG: Read CSV on python engine fails when skiprows and chunk size are specified (#55677, #56323)
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 5ee2bb1778cb1..c20e667774b3c 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -566,6 +566,8 @@ MultiIndex I/O ^^^ +- Bug in :func:`read_csv` where ``engine="python"`` did not respect ``chunksize`` arg when ``skiprows`` was specified. (:issue:`56323`) +- Bug in :func:`read_csv` where ``engine="python"`` was causing a ``TypeError`` when a callable ``skiprows`` and a chunk size was specified. (:issue:`55677`) - Bug in :func:`read_csv` where ``on_bad_lines="warn"`` would write to ``stderr`` instead of raise a Python warning. This now yields a :class:`.errors.ParserWarning` (:issue:`54296`) - Bug in :func:`read_csv` with ``engine="pyarrow"`` where ``usecols`` wasn't working with a csv with no headers (:issue:`54459`) - Bug in :func:`read_excel`, with ``engine="xlrd"`` (``xls`` files) erroring when file contains NaNs/Infs (:issue:`54564`) diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py index fae3293414b02..79e7554a5744c 100644 --- a/pandas/io/parsers/python_parser.py +++ b/pandas/io/parsers/python_parser.py @@ -1117,18 +1117,18 @@ def _get_lines(self, rows: int | None = None) -> list[list[Scalar]]: new_rows = [] try: if rows is not None: - rows_to_skip = 0 - if self.skiprows is not None and self.pos is not None: - # Only read additional rows if pos is in skiprows - rows_to_skip = len( - set(self.skiprows) - set(range(self.pos)) - ) - - for _ in range(rows + rows_to_skip): + row_index = 0 + row_ct = 0 + offset = self.pos if self.pos is not None else 0 + while row_ct < rows: # assert for mypy, data is Iterator[str] or None, would # error in next assert self.data is not None - new_rows.append(next(self.data)) + new_row = next(self.data) + if not self.skipfunc(offset + row_index): + row_ct += 1 + row_index += 1 + new_rows.append(new_row) len_new_rows = len(new_rows) new_rows = self._remove_skipped_rows(new_rows) @@ -1137,11 +1137,11 @@ def _get_lines(self, rows: int | None = None) -> list[list[Scalar]]: rows = 0 while True: - new_row = self._next_iter_line(row_num=self.pos + rows + 1) + next_row = self._next_iter_line(row_num=self.pos + rows + 1) rows += 1 - if new_row is not None: - new_rows.append(new_row) + if next_row is not None: + new_rows.append(next_row) len_new_rows = len(new_rows) except StopIteration: diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py index 34cae289c0f22..480d579f7f400 100644 --- a/pandas/tests/io/parser/test_read_fwf.py +++ b/pandas/tests/io/parser/test_read_fwf.py @@ -898,7 +898,7 @@ def test_skip_rows_and_n_rows(): def test_skiprows_with_iterator(): - # GH#10261 + # GH#10261, GH#56323 data = """0 1 2 @@ -920,8 +920,8 @@ def test_skiprows_with_iterator(): ) expected_frames = [ DataFrame({"a": [3, 4]}), - DataFrame({"a": [5, 7, 8]}, index=[2, 3, 4]), - DataFrame({"a": []}, dtype="object"), + DataFrame({"a": [5, 7]}, index=[2, 3]), + DataFrame({"a": [8]}, index=[4]), ] for i, result in enumerate(df_iter): tm.assert_frame_equal(result, expected_frames[i]) diff --git a/pandas/tests/io/parser/test_skiprows.py b/pandas/tests/io/parser/test_skiprows.py index 47c3739c979a3..749bd47d5c1a3 100644 --- a/pandas/tests/io/parser/test_skiprows.py +++ b/pandas/tests/io/parser/test_skiprows.py @@ -301,3 +301,29 @@ def test_skip_rows_and_n_rows(all_parsers): result = parser.read_csv(StringIO(data), nrows=5, skiprows=[2, 4, 6]) expected = DataFrame({"a": [1, 3, 5, 7, 8], "b": ["a", "c", "e", "g", "h"]}) tm.assert_frame_equal(result, expected) + + +@xfail_pyarrow +def test_skip_rows_with_chunks(all_parsers): + # GH 55677 + data = """col_a +10 +20 +30 +40 +50 +60 +70 +80 +90 +100 +""" + parser = all_parsers + reader = parser.read_csv( + StringIO(data), engine=parser, skiprows=lambda x: x in [1, 4, 5], chunksize=4 + ) + df1 = next(reader) + df2 = next(reader) + + tm.assert_frame_equal(df1, DataFrame({"col_a": [20, 30, 60, 70]})) + tm.assert_frame_equal(df2, DataFrame({"col_a": [80, 90, 100]}, index=[4, 5, 6]))
-Added support for the python parser to handle using skiprows and chunk_size options at the same time to ensure API contract is met. -Added a regression test to ensure this #55677 can be quickly caught in the future if it reappears. -Fixed a flawed test case that now screens for #56323 regressions. - [✅ ] closes #55677 (Replace xxxx with the GitHub issue number) - [✅ ] closes #56323 (Replace xxxx with the GitHub issue number) - [✅] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [✅] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [✅] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [✅] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/56250
2023-11-30T02:24:35Z
2023-12-05T00:27:37Z
2023-12-05T00:27:37Z
2023-12-05T00:27:44Z
BUG: __eq__ raising for new arrow string dtype for incompatible objects
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 70039cc697b8a..cda4da9d76c42 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -604,6 +604,7 @@ Strings - Bug in :meth:`Series.str.find` when ``start < 0`` for :class:`ArrowDtype` with ``pyarrow.string`` (:issue:`56411`) - Bug in :meth:`Series.str.replace` when ``n < 0`` for :class:`ArrowDtype` with ``pyarrow.string`` (:issue:`56404`) - Bug in :meth:`Series.str.startswith` and :meth:`Series.str.endswith` with arguments of type ``tuple[str, ...]`` for ``string[pyarrow]`` (:issue:`54942`) +- Bug in comparison operations for ``dtype="string[pyarrow_numpy]"`` raising if dtypes can't be compared (:issue:`56008`) Interval ^^^^^^^^ diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index 32ab3054c0f51..50cd052f80abd 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -41,6 +41,7 @@ BaseStringArray, StringDtype, ) +from pandas.core.ops import invalid_comparison from pandas.core.strings.object_array import ObjectStringArrayMixin if not pa_version_under10p1: @@ -662,7 +663,10 @@ def _convert_int_dtype(self, result): return result def _cmp_method(self, other, op): - result = super()._cmp_method(other, op) + try: + result = super()._cmp_method(other, op) + except pa.ArrowNotImplementedError: + return invalid_comparison(self, other, op) if op == operator.ne: return result.to_numpy(np.bool_, na_value=True) else: diff --git a/pandas/tests/series/test_logical_ops.py b/pandas/tests/series/test_logical_ops.py index 153b4bfaaf444..d9c94e871bd4b 100644 --- a/pandas/tests/series/test_logical_ops.py +++ b/pandas/tests/series/test_logical_ops.py @@ -530,3 +530,19 @@ def test_int_dtype_different_index_not_bool(self): result = ser1 ^ ser2 tm.assert_series_equal(result, expected) + + def test_pyarrow_numpy_string_invalid(self): + # GH#56008 + pytest.importorskip("pyarrow") + ser = Series([False, True]) + ser2 = Series(["a", "b"], dtype="string[pyarrow_numpy]") + result = ser == ser2 + expected = Series(False, index=ser.index) + tm.assert_series_equal(result, expected) + + result = ser != ser2 + expected = Series(True, index=ser.index) + tm.assert_series_equal(result, expected) + + with pytest.raises(TypeError, match="Invalid comparison"): + ser > ser2
- [ ] closes #56008 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/56245
2023-11-29T23:22:39Z
2023-12-21T22:45:36Z
2023-12-21T22:45:36Z
2023-12-21T22:45:39Z
DEPR: Deprecate dtype inference on pandas objects
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 8209525721b98..89a03ddbef2a2 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -460,6 +460,7 @@ Other Deprecations - Deprecated behavior of :meth:`Index.insert` with an object-dtype index silently performing type inference on the result, explicitly call ``result.infer_objects(copy=False)`` for the old behavior instead (:issue:`51363`) - Deprecated casting non-datetimelike values (mainly strings) in :meth:`Series.isin` and :meth:`Index.isin` with ``datetime64``, ``timedelta64``, and :class:`PeriodDtype` dtypes (:issue:`53111`) - Deprecated downcasting behavior in :meth:`Series.where`, :meth:`DataFrame.where`, :meth:`Series.mask`, :meth:`DataFrame.mask`, :meth:`Series.clip`, :meth:`DataFrame.clip`; in a future version these will not infer object-dtype columns to non-object dtype, or all-round floats to integer dtype. Call ``result.infer_objects(copy=False)`` on the result for object inference, or explicitly cast floats to ints. To opt in to the future version, use ``pd.set_option("future.no_silent_downcasting", True)`` (:issue:`53656`) +- Deprecated dtype inference in :class:`Index`, :class:`Series` and :class:`DataFrame` constructors when giving a pandas input, call ``.infer_objects`` on the input to keep the current behavior (:issue:`56012`) - Deprecated dtype inference when setting a :class:`Index` into a :class:`DataFrame`, cast explicitly instead (:issue:`56102`) - Deprecated including the groups in computations when using :meth:`.DataFrameGroupBy.apply` and :meth:`.DataFrameGroupBy.resample`; pass ``include_groups=False`` to exclude the groups (:issue:`7155`) - Deprecated indexing an :class:`Index` with a boolean indexer of length zero (:issue:`55820`) diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index 69b2b0876fc80..672c16a85086c 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -10,6 +10,7 @@ ContextManager, cast, ) +import warnings import numpy as np @@ -285,11 +286,17 @@ def box_expected(expected, box_cls, transpose: bool = True): else: expected = pd.array(expected, copy=False) elif box_cls is Index: - expected = Index(expected) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", "Dtype inference", category=FutureWarning) + expected = Index(expected) elif box_cls is Series: - expected = Series(expected) + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", "Dtype inference", category=FutureWarning) + expected = Series(expected) elif box_cls is DataFrame: - expected = Series(expected).to_frame() + with warnings.catch_warnings(): + warnings.filterwarnings("ignore", "Dtype inference", category=FutureWarning) + expected = Series(expected).to_frame() if transpose: # for vector operations, we need a DataFrame to be a single-row, # not a single-column, in order to operate against non-DataFrame diff --git a/pandas/core/frame.py b/pandas/core/frame.py index e741fa7b37f33..e1048a51089ac 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -726,6 +726,10 @@ def __init__( manager = _get_option("mode.data_manager", silent=True) + is_pandas_object = isinstance(data, (Series, Index, ExtensionArray)) + data_dtype = getattr(data, "dtype", None) + original_dtype = dtype + # GH47215 if isinstance(index, set): raise ValueError("index cannot be a set") @@ -912,6 +916,18 @@ def __init__( NDFrame.__init__(self, mgr) + if original_dtype is None and is_pandas_object and data_dtype == np.object_: + if self.dtypes.iloc[0] != data_dtype: + warnings.warn( + "Dtype inference on a pandas object " + "(Series, Index, ExtensionArray) is deprecated. The DataFrame " + "constructor will keep the original dtype in the future. " + "Call `infer_objects` on the result to get the old " + "behavior.", + FutureWarning, + stacklevel=2, + ) + # ---------------------------------------------------------------------- def __dataframe__( diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 5dc4a85ba9792..e01c4e75e9f8a 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -492,6 +492,8 @@ def __new__( if not copy and isinstance(data, (ABCSeries, Index)): refs = data._references + is_pandas_object = isinstance(data, (ABCSeries, Index, ExtensionArray)) + # range if isinstance(data, (range, RangeIndex)): result = RangeIndex(start=data, copy=copy, name=name) @@ -571,7 +573,19 @@ def __new__( klass = cls._dtype_to_subclass(arr.dtype) arr = klass._ensure_array(arr, arr.dtype, copy=False) - return klass._simple_new(arr, name, refs=refs) + result = klass._simple_new(arr, name, refs=refs) + if dtype is None and is_pandas_object and data_dtype == np.object_: + if result.dtype != data_dtype: + warnings.warn( + "Dtype inference on a pandas object " + "(Series, Index, ExtensionArray) is deprecated. The Index " + "constructor will keep the original dtype in the future. " + "Call `infer_objects` on the result to get the old " + "behavior.", + FutureWarning, + stacklevel=2, + ) + return result # type: ignore[return-value] @classmethod def _ensure_array(cls, data, dtype, copy: bool): diff --git a/pandas/core/series.py b/pandas/core/series.py index e4dca97bc645d..d46068b6338c5 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -424,6 +424,10 @@ def __init__( self.name = name return + is_pandas_object = isinstance(data, (Series, Index, ExtensionArray)) + data_dtype = getattr(data, "dtype", None) + original_dtype = dtype + if isinstance(data, (ExtensionArray, np.ndarray)): if copy is not False and using_copy_on_write(): if dtype is None or astype_is_view(data.dtype, pandas_dtype(dtype)): @@ -581,6 +585,17 @@ def __init__( self.name = name self._set_axis(0, index) + if original_dtype is None and is_pandas_object and data_dtype == np.object_: + if self.dtype != data_dtype: + warnings.warn( + "Dtype inference on a pandas object " + "(Series, Index, ExtensionArray) is deprecated. The Series " + "constructor will keep the original dtype in the future. " + "Call `infer_objects` on the result to get the old behavior.", + FutureWarning, + stacklevel=find_stack_level(), + ) + def _init_dict( self, data, index: Index | None = None, dtype: DtypeObj | None = None ): diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 75866c6f6013a..1b7d632c0fa80 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -689,19 +689,18 @@ def cat( result = cat_safe(all_cols, sep) out: Index | Series + if isinstance(self._orig.dtype, CategoricalDtype): + # We need to infer the new categories. + dtype = self._orig.dtype.categories.dtype + else: + dtype = self._orig.dtype if isinstance(self._orig, ABCIndex): # add dtype for case that result is all-NA - dtype = None if isna(result).all(): - dtype = object + dtype = object # type: ignore[assignment] out = Index(result, dtype=dtype, name=self._orig.name) else: # Series - if isinstance(self._orig.dtype, CategoricalDtype): - # We need to infer the new categories. - dtype = self._orig.dtype.categories.dtype # type: ignore[assignment] - else: - dtype = self._orig.dtype res_ser = Series( result, dtype=dtype, index=data.index, name=self._orig.name, copy=False ) diff --git a/pandas/tests/copy_view/test_constructors.py b/pandas/tests/copy_view/test_constructors.py index 7d5c485958039..1aa458a625028 100644 --- a/pandas/tests/copy_view/test_constructors.py +++ b/pandas/tests/copy_view/test_constructors.py @@ -314,7 +314,8 @@ def test_dataframe_from_series_or_index_different_dtype(using_copy_on_write, con def test_dataframe_from_series_infer_datetime(using_copy_on_write): ser = Series([Timestamp("2019-12-31"), Timestamp("2020-12-31")], dtype=object) - df = DataFrame(ser) + with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): + df = DataFrame(ser) assert not np.shares_memory(get_array(ser), get_array(df, 0)) if using_copy_on_write: assert df._mgr._has_no_reference(0) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index e1abd0344e356..4c4760501db4e 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2768,6 +2768,23 @@ def test_frame_string_inference_block_dim(self): df = DataFrame(np.array([["hello", "goodbye"], ["hello", "Hello"]])) assert df._mgr.blocks[0].ndim == 2 + def test_inference_on_pandas_objects(self): + # GH#56012 + idx = Index([Timestamp("2019-12-31")], dtype=object) + with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): + result = DataFrame(idx, columns=["a"]) + assert result.dtypes.iloc[0] != np.object_ + result = DataFrame({"a": idx}) + assert result.dtypes.iloc[0] == np.object_ + + ser = Series([Timestamp("2019-12-31")], dtype=object) + + with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): + result = DataFrame(ser, columns=["a"]) + assert result.dtypes.iloc[0] != np.object_ + result = DataFrame({"a": ser}) + assert result.dtypes.iloc[0] == np.object_ + class TestDataFrameConstructorIndexInference: def test_frame_from_dict_of_series_overlapping_monthly_period_indexes(self): diff --git a/pandas/tests/indexes/base_class/test_constructors.py b/pandas/tests/indexes/base_class/test_constructors.py index 60abbfc441e8e..fd5176a28565e 100644 --- a/pandas/tests/indexes/base_class/test_constructors.py +++ b/pandas/tests/indexes/base_class/test_constructors.py @@ -5,6 +5,7 @@ from pandas import ( Index, MultiIndex, + Series, ) import pandas._testing as tm @@ -57,3 +58,16 @@ def test_index_string_inference(self): with pd.option_context("future.infer_string", True): ser = Index(["a", 1]) tm.assert_index_equal(ser, expected) + + def test_inference_on_pandas_objects(self): + # GH#56012 + idx = Index([pd.Timestamp("2019-12-31")], dtype=object) + with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): + result = Index(idx) + assert result.dtype != np.object_ + + ser = Series([pd.Timestamp("2019-12-31")], dtype=object) + + with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): + result = Index(ser) + assert result.dtype != np.object_ diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 185e34efdc177..666d92064c86c 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -104,7 +104,8 @@ def test_constructor_copy(self, index, using_infer_string): ) def test_constructor_from_index_dtlike(self, cast_as_obj, index): if cast_as_obj: - result = Index(index.astype(object)) + with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): + result = Index(index.astype(object)) else: result = Index(index) diff --git a/pandas/tests/series/accessors/test_dt_accessor.py b/pandas/tests/series/accessors/test_dt_accessor.py index 083a4c4b24adb..34465a7c12c18 100644 --- a/pandas/tests/series/accessors/test_dt_accessor.py +++ b/pandas/tests/series/accessors/test_dt_accessor.py @@ -259,9 +259,9 @@ def test_dt_accessor_limited_display_api(self): tm.assert_almost_equal(results, sorted(set(ok_for_dt + ok_for_dt_methods))) # Period - ser = Series( - period_range("20130101", periods=5, freq="D", name="xxx").astype(object) - ) + idx = period_range("20130101", periods=5, freq="D", name="xxx").astype(object) + with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): + ser = Series(idx) results = get_dir(ser) tm.assert_almost_equal( results, sorted(set(ok_for_period + ok_for_period_methods)) diff --git a/pandas/tests/series/methods/test_between.py b/pandas/tests/series/methods/test_between.py index 8f4931beae589..3913419038876 100644 --- a/pandas/tests/series/methods/test_between.py +++ b/pandas/tests/series/methods/test_between.py @@ -20,7 +20,7 @@ def test_between(self): tm.assert_series_equal(result, expected) def test_between_datetime_object_dtype(self): - ser = Series(bdate_range("1/1/2000", periods=20).astype(object)) + ser = Series(bdate_range("1/1/2000", periods=20), dtype=object) ser[::2] = np.nan result = ser[ser.between(ser[3], ser[17])] diff --git a/pandas/tests/series/methods/test_equals.py b/pandas/tests/series/methods/test_equals.py index b94723b7cbddf..875ffdd3fe851 100644 --- a/pandas/tests/series/methods/test_equals.py +++ b/pandas/tests/series/methods/test_equals.py @@ -82,13 +82,15 @@ def test_equals_matching_nas(): left = Series([np.datetime64("NaT")], dtype=object) right = Series([np.datetime64("NaT")], dtype=object) assert left.equals(right) - assert Index(left).equals(Index(right)) + with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): + assert Index(left).equals(Index(right)) assert left.array.equals(right.array) left = Series([np.timedelta64("NaT")], dtype=object) right = Series([np.timedelta64("NaT")], dtype=object) assert left.equals(right) - assert Index(left).equals(Index(right)) + with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): + assert Index(left).equals(Index(right)) assert left.array.equals(right.array) left = Series([np.float64("NaN")], dtype=object) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 0e6f1c284a988..5f591b4b22f1c 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1316,7 +1316,8 @@ def test_constructor_periodindex(self): pi = period_range("20130101", periods=5, freq="D") s = Series(pi) assert s.dtype == "Period[D]" - expected = Series(pi.astype(object)) + with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): + expected = Series(pi.astype(object)) tm.assert_series_equal(s, expected) def test_constructor_dict(self): @@ -2137,6 +2138,20 @@ def test_series_string_inference_na_first(self): result = Series([pd.NA, "b"]) tm.assert_series_equal(result, expected) + def test_inference_on_pandas_objects(self): + # GH#56012 + ser = Series([Timestamp("2019-12-31")], dtype=object) + with tm.assert_produces_warning(None): + # This doesn't do inference + result = Series(ser) + assert result.dtype == np.object_ + + idx = Index([Timestamp("2019-12-31")], dtype=object) + + with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): + result = Series(idx) + assert result.dtype != np.object_ + class TestSeriesConstructorIndexCoercion: def test_series_constructor_datetimelike_index_coercion(self): diff --git a/pandas/tests/strings/test_cat.py b/pandas/tests/strings/test_cat.py index 284932491a65e..c1e7ad6e02779 100644 --- a/pandas/tests/strings/test_cat.py +++ b/pandas/tests/strings/test_cat.py @@ -98,14 +98,18 @@ def test_str_cat_categorical( with option_context("future.infer_string", infer_string): s = Index(["a", "a", "b", "a"], dtype=dtype_caller) - s = s if box == Index else Series(s, index=s) + s = s if box == Index else Series(s, index=s, dtype=s.dtype) t = Index(["b", "a", "b", "c"], dtype=dtype_target) - expected = Index(["ab", "aa", "bb", "ac"]) + expected = Index( + ["ab", "aa", "bb", "ac"], dtype=object if dtype_caller == "object" else None + ) expected = ( expected if box == Index - else Series(expected, index=Index(s, dtype=dtype_caller)) + else Series( + expected, index=Index(s, dtype=dtype_caller), dtype=expected.dtype + ) ) # Series/Index with unaligned Index -> t.values @@ -123,12 +127,19 @@ def test_str_cat_categorical( # Series/Index with Series having different Index t = Series(t.values, index=t.values) - expected = Index(["aa", "aa", "bb", "bb", "aa"]) + expected = Index( + ["aa", "aa", "bb", "bb", "aa"], + dtype=object if dtype_caller == "object" else None, + ) dtype = object if dtype_caller == "object" else s.dtype.categories.dtype expected = ( expected if box == Index - else Series(expected, index=Index(expected.str[:1], dtype=dtype)) + else Series( + expected, + index=Index(expected.str[:1], dtype=dtype), + dtype=expected.dtype, + ) ) result = s.str.cat(t, sep=sep) diff --git a/pandas/tests/tseries/frequencies/test_inference.py b/pandas/tests/tseries/frequencies/test_inference.py index 45741e852fef7..99a504f4188c1 100644 --- a/pandas/tests/tseries/frequencies/test_inference.py +++ b/pandas/tests/tseries/frequencies/test_inference.py @@ -23,6 +23,7 @@ date_range, period_range, ) +import pandas._testing as tm from pandas.core.arrays import ( DatetimeArray, TimedeltaArray, @@ -206,7 +207,8 @@ def test_infer_freq_custom(base_delta_code_pair, constructor): ) def test_infer_freq_index(freq, expected): rng = period_range("1959Q2", "2009Q3", freq=freq) - rng = Index(rng.to_timestamp("D", how="e").astype(object)) + with tm.assert_produces_warning(FutureWarning, match="Dtype inference"): + rng = Index(rng.to_timestamp("D", how="e").astype(object)) assert rng.inferred_freq == expected
- [ ] closes #56012 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. This is very weird to begin with and becomes a real PITA when we infer strings as arrow backed strings
https://api.github.com/repos/pandas-dev/pandas/pulls/56244
2023-11-29T22:26:14Z
2023-12-21T22:45:21Z
2023-12-21T22:45:21Z
2023-12-21T22:45:24Z
ENH: Raise TypeError when converting DatetimeIndex to PeriodIndex with invalid period frequency
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 8cb4b3f24d435..85dfc3ebde873 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -195,6 +195,7 @@ Other enhancements - Allow passing ``read_only``, ``data_only`` and ``keep_links`` arguments to openpyxl using ``engine_kwargs`` of :func:`read_excel` (:issue:`55027`) - DataFrame.apply now allows the usage of numba (via ``engine="numba"``) to JIT compile the passed function, allowing for potential speedups (:issue:`54666`) - Implement masked algorithms for :meth:`Series.value_counts` (:issue:`54984`) +- Improved error message that appears in :meth:`DatetimeIndex.to_period` with frequencies which are not supported as period frequencies, such as "BMS" (:issue:`56243`) - Improved error message when constructing :class:`Period` with invalid offsets such as "QS" (:issue:`55785`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 57b244e8d02e9..a8c21cfbb6e2f 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -1174,7 +1174,12 @@ def dt64arr_to_periodarr( reso = get_unit_from_dtype(data.dtype) freq = Period._maybe_convert_freq(freq) - base = freq._period_dtype_code + try: + base = freq._period_dtype_code + except (AttributeError, TypeError): + # AttributeError: _period_dtype_code might not exist + # TypeError: _period_dtype_code might intentionally raise + raise TypeError(f"{freq.name} is not supported as period frequency") return c_dt64arr_to_periodarr(data.view("i8"), base, tz, reso=reso), freq diff --git a/pandas/tests/indexes/datetimes/methods/test_to_period.py b/pandas/tests/indexes/datetimes/methods/test_to_period.py index aa217e895c30a..2c68ddd3d3d15 100644 --- a/pandas/tests/indexes/datetimes/methods/test_to_period.py +++ b/pandas/tests/indexes/datetimes/methods/test_to_period.py @@ -230,3 +230,11 @@ def test_to_period_nofreq(self): idx = DatetimeIndex(["2000-01-01", "2000-01-02", "2000-01-03"]) assert idx.freqstr is None tm.assert_index_equal(idx.to_period(), expected) + + @pytest.mark.parametrize("freq", ["2BMS", "1SME-15"]) + def test_to_period_offsets_not_supported(self, freq): + # GH#56243 + msg = f"{freq[1:]} is not supported as period frequency" + ts = date_range("1/1/2012", periods=4, freq=freq) + with pytest.raises(TypeError, match=msg): + ts.to_period()
xref #55844 Added to `dt64arr_to_periodarr` check if frequency is supported as period frequency, if not a TypeError is raised. The reason: so far in the example below ``` >>> ts = pd.date_range('1/1/2012', periods=4, freq="BMS") >>> ts.to_period() ``` we get `AttributeError: 'pandas._libs.tslibs.offsets.BusinessMonthBegin' object has no attribute '_period_dtype_code'`
https://api.github.com/repos/pandas-dev/pandas/pulls/56243
2023-11-29T22:03:13Z
2023-12-04T11:14:58Z
2023-12-04T11:14:58Z
2023-12-04T11:15:02Z
CoW: Remove false positive warnings for inplace operators
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 56001fabfdc9d..30646cea706e5 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -12500,6 +12500,7 @@ def _inplace_method(self, other, op) -> Self: and result._indexed_same(self) and result.dtype == self.dtype and not using_copy_on_write() + and not (warn_copy_on_write() and not warn) ): # GH#36498 this inplace op can _actually_ be inplace. # Item "ArrayManager" of "Union[ArrayManager, SingleArrayManager, diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py index 787b77a5c725a..0f27eae1a3bfc 100644 --- a/pandas/tests/frame/methods/test_quantile.py +++ b/pandas/tests/frame/methods/test_quantile.py @@ -110,8 +110,6 @@ def test_non_numeric_exclusion(self, interp_method, request, using_array_manager request.applymarker(pytest.mark.xfail(reason="Axis name incorrectly set.")) tm.assert_series_equal(rs, xp) - # TODO(CoW-warn) should not need to warn - @pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") def test_axis(self, interp_method, request, using_array_manager): # axis interpolation, method = interp_method diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 5b17484de9c93..3c6419ab86494 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -41,8 +41,6 @@ def test_repr(): assert result == expected -# TODO(CoW-warn) this should NOT warn -> inplace operator triggers it -@pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") def test_groupby_std_datetimelike(warn_copy_on_write): # GH#48481 tdi = pd.timedelta_range("1 Day", periods=10000) diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index bf0975a803dce..a0ece7cd72cd8 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -121,11 +121,7 @@ def test_setitem_cache_updating_slices( out = DataFrame({"A": [0, 0, 0]}, index=date_range("5/7/2014", "5/9/2014")) for ix, row in df.iterrows(): - # TODO(CoW-warn) should not warn - with tm.assert_produces_warning( - FutureWarning if warn_copy_on_write else None - ): - out.loc[six:eix, row["C"]] += row["D"] + out.loc[six:eix, row["C"]] += row["D"] tm.assert_frame_equal(out, expected) tm.assert_series_equal(out["A"], expected["A"]) diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index baf2cdae43fe4..31263b44ed205 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -426,9 +426,7 @@ def test_iloc_getitem_slice_dups(self): tm.assert_frame_equal(df.iloc[10:, :2], df2) tm.assert_frame_equal(df.iloc[10:, 2:], df1) - # TODO(CoW-warn) this should NOT warn -> Series inplace operator - @pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") - def test_iloc_setitem(self): + def test_iloc_setitem(self, warn_copy_on_write): df = DataFrame( np.random.default_rng(2).standard_normal((4, 4)), index=np.arange(0, 8, 2), @@ -1147,7 +1145,7 @@ def test_iloc_getitem_with_duplicates2(self): expected = df.take([0], axis=1) tm.assert_frame_equal(result, expected) - def test_iloc_interval(self, warn_copy_on_write): + def test_iloc_interval(self): # GH#17130 df = DataFrame({Interval(1, 2): [1, 2]}) @@ -1160,9 +1158,7 @@ def test_iloc_interval(self, warn_copy_on_write): tm.assert_series_equal(result, expected) result = df.copy() - # TODO(CoW-warn) false positive - with tm.assert_cow_warning(warn_copy_on_write): - result.iloc[:, 0] += 1 + result.iloc[:, 0] += 1 expected = DataFrame({Interval(1, 2): [2, 3]}) tm.assert_frame_equal(result, expected)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. xref https://github.com/pandas-dev/pandas/issues/56019
https://api.github.com/repos/pandas-dev/pandas/pulls/56242
2023-11-29T21:11:31Z
2023-12-04T10:13:33Z
2023-12-04T10:13:33Z
2023-12-04T11:05:37Z
TST/CLN: Remove getSeriesData/makeObjectSeries/makeDatetimeIndex
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index b1918e1b1d7c2..ead00cd778d7b 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -2,7 +2,6 @@ import collections from collections import Counter -from datetime import datetime from decimal import Decimal import operator import os @@ -36,12 +35,10 @@ ArrowDtype, Categorical, DataFrame, - DatetimeIndex, Index, MultiIndex, RangeIndex, Series, - bdate_range, date_range, period_range, timedelta_range, @@ -348,34 +345,12 @@ def getCols(k) -> str: return string.ascii_uppercase[:k] -def makeDateIndex( - k: int = 10, freq: Frequency = "B", name=None, **kwargs -) -> DatetimeIndex: - dt = datetime(2000, 1, 1) - dr = bdate_range(dt, periods=k, freq=freq, name=name) - return DatetimeIndex(dr, name=name, **kwargs) - - -def makeObjectSeries(name=None) -> Series: - data = [f"foo_{i}" for i in range(_N)] - index = Index([f"bar_{i}" for i in range(_N)]) - return Series(data, index=index, name=name, dtype=object) - - -def getSeriesData() -> dict[str, Series]: - index = Index([f"foo_{i}" for i in range(_N)]) - return { - c: Series(np.random.default_rng(i).standard_normal(_N), index=index) - for i, c in enumerate(getCols(_K)) - } - - def makeTimeSeries(nper=None, freq: Frequency = "B", name=None) -> Series: if nper is None: nper = _N return Series( np.random.default_rng(2).standard_normal(nper), - index=makeDateIndex(nper, freq=freq), + index=date_range("2000-01-01", periods=nper, freq=freq), name=name, ) @@ -390,11 +365,6 @@ def makeTimeDataFrame(nper=None, freq: Frequency = "B") -> DataFrame: return DataFrame(data) -def makeDataFrame() -> DataFrame: - data = getSeriesData() - return DataFrame(data) - - def makeCustomIndex( nentries, nlevels, @@ -925,16 +895,12 @@ def shares_memory(left, right) -> bool: "get_finest_unit", "get_obj", "get_op_from_name", - "getSeriesData", "getTimeSeriesData", "iat", "iloc", "loc", "makeCustomDataframe", "makeCustomIndex", - "makeDataFrame", - "makeDateIndex", - "makeObjectSeries", "makeTimeDataFrame", "makeTimeSeries", "maybe_produces_warning", diff --git a/pandas/conftest.py b/pandas/conftest.py index 1bc067eb32aef..9ed6f8f43ae03 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -68,6 +68,7 @@ Series, Timedelta, Timestamp, + date_range, period_range, timedelta_range, ) @@ -608,15 +609,15 @@ def _create_mi_with_dt64tz_level(): """ # GH#8367 round trip with pickle return MultiIndex.from_product( - [[1, 2], ["a", "b"], pd.date_range("20130101", periods=3, tz="US/Eastern")], + [[1, 2], ["a", "b"], date_range("20130101", periods=3, tz="US/Eastern")], names=["one", "two", "three"], ) indices_dict = { "string": Index([f"pandas_{i}" for i in range(100)]), - "datetime": tm.makeDateIndex(100), - "datetime-tz": tm.makeDateIndex(100, tz="US/Pacific"), + "datetime": date_range("2020-01-01", periods=100), + "datetime-tz": date_range("2020-01-01", periods=100, tz="US/Pacific"), "period": period_range("2020-01-01", periods=100, freq="D"), "timedelta": timedelta_range(start="1 day", periods=100, freq="D"), "range": RangeIndex(100), @@ -631,7 +632,7 @@ def _create_mi_with_dt64tz_level(): "float32": Index(np.arange(100), dtype="float32"), "float64": Index(np.arange(100), dtype="float64"), "bool-object": Index([True, False] * 5, dtype=object), - "bool-dtype": Index(np.random.default_rng(2).standard_normal(10) < 0), + "bool-dtype": Index([True, False] * 5, dtype=bool), "complex64": Index( np.arange(100, dtype="complex64") + 1.0j * np.arange(100, dtype="complex64") ), @@ -751,9 +752,9 @@ def object_series() -> Series: """ Fixture for Series of dtype object with Index of unique strings """ - s = tm.makeObjectSeries() - s.name = "objects" - return s + data = [f"foo_{i}" for i in range(30)] + index = Index([f"bar_{i}" for i in range(30)], dtype=object) + return Series(data, index=index, name="objects", dtype=object) @pytest.fixture @@ -839,27 +840,12 @@ def int_frame() -> DataFrame: Fixture for DataFrame of ints with index of unique strings Columns are ['A', 'B', 'C', 'D'] - - A B C D - vpBeWjM651 1 0 1 0 - 5JyxmrP1En -1 0 0 0 - qEDaoD49U2 -1 1 0 0 - m66TkTfsFe 0 0 0 0 - EHPaNzEUFm -1 0 -1 0 - fpRJCevQhi 2 0 0 0 - OlQvnmfi3Q 0 0 -2 0 - ... .. .. .. .. - uB1FPlz4uP 0 0 0 1 - EcSe6yNzCU 0 0 -1 0 - L50VudaiI8 -1 1 -2 0 - y3bpw4nwIp 0 -1 0 0 - H0RdLLwrCT 1 1 0 0 - rY82K0vMwm 0 0 0 0 - 1OPIUjnkjk 2 0 0 0 - - [30 rows x 4 columns] """ - return DataFrame(tm.getSeriesData()).astype("int64") + return DataFrame( + np.ones((30, 4), dtype=np.int64), + index=Index([f"foo_{i}" for i in range(30)], dtype=object), + columns=Index(list("ABCD"), dtype=object), + ) @pytest.fixture @@ -868,27 +854,12 @@ def float_frame() -> DataFrame: Fixture for DataFrame of floats with index of unique strings Columns are ['A', 'B', 'C', 'D']. - - A B C D - P7GACiRnxd -0.465578 -0.361863 0.886172 -0.053465 - qZKh6afn8n -0.466693 -0.373773 0.266873 1.673901 - tkp0r6Qble 0.148691 -0.059051 0.174817 1.598433 - wP70WOCtv8 0.133045 -0.581994 -0.992240 0.261651 - M2AeYQMnCz -1.207959 -0.185775 0.588206 0.563938 - QEPzyGDYDo -0.381843 -0.758281 0.502575 -0.565053 - r78Jwns6dn -0.653707 0.883127 0.682199 0.206159 - ... ... ... ... ... - IHEGx9NO0T -0.277360 0.113021 -1.018314 0.196316 - lPMj8K27FA -1.313667 -0.604776 -1.305618 -0.863999 - qa66YMWQa5 1.110525 0.475310 -0.747865 0.032121 - yOa0ATsmcE -0.431457 0.067094 0.096567 -0.264962 - 65znX3uRNG 1.528446 0.160416 -0.109635 -0.032987 - eCOBvKqf3e 0.235281 1.622222 0.781255 0.392871 - xSucinXxuV -1.263557 0.252799 -0.552247 0.400426 - - [30 rows x 4 columns] - """ - return DataFrame(tm.getSeriesData()) + """ + return DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + index=Index([f"foo_{i}" for i in range(30)], dtype=object), + columns=Index(list("ABCD"), dtype=object), + ) @pytest.fixture diff --git a/pandas/tests/apply/test_numba.py b/pandas/tests/apply/test_numba.py index 85d7baee1bdf5..57b81711ddb48 100644 --- a/pandas/tests/apply/test_numba.py +++ b/pandas/tests/apply/test_numba.py @@ -60,9 +60,10 @@ def test_numba_vs_python_indexing(): "reduction", [lambda x: x.mean(), lambda x: x.min(), lambda x: x.max(), lambda x: x.sum()], ) -def test_numba_vs_python_reductions(float_frame, reduction, apply_axis): - result = float_frame.apply(reduction, engine="numba", axis=apply_axis) - expected = float_frame.apply(reduction, engine="python", axis=apply_axis) +def test_numba_vs_python_reductions(reduction, apply_axis): + df = DataFrame(np.ones((4, 4), dtype=np.float64)) + result = df.apply(reduction, engine="numba", axis=apply_axis) + expected = df.apply(reduction, engine="python", axis=apply_axis) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 9014ba4b6093e..4bd0e6c1c3694 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -394,7 +394,7 @@ def test_dt64_compare_datetime_scalar(self, datetimelike, op, expected): class TestDatetimeIndexComparisons: # TODO: moved from tests.indexes.test_base; parametrize and de-duplicate def test_comparators(self, comparison_op): - index = tm.makeDateIndex(100) + index = date_range("2020-01-01", periods=10) element = index[len(index) // 2] element = Timestamp(element).to_datetime64() diff --git a/pandas/tests/arithmetic/test_object.py b/pandas/tests/arithmetic/test_object.py index 6b36f447eb7d5..7d27f940daa4c 100644 --- a/pandas/tests/arithmetic/test_object.py +++ b/pandas/tests/arithmetic/test_object.py @@ -169,8 +169,7 @@ def test_objarr_add_invalid(self, op, box_with_array): # invalid ops box = box_with_array - obj_ser = tm.makeObjectSeries() - obj_ser.name = "objects" + obj_ser = Series(list("abc"), dtype=object, name="objects") obj_ser = tm.box_expected(obj_ser, box) msg = "|".join( diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index 88cec50c08aba..e1f8d8eca2537 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -78,8 +78,12 @@ def test_notna_notnull(notna_f): @pytest.mark.parametrize( "ser", [ - tm.makeObjectSeries(), - tm.makeTimeSeries(), + Series( + [str(i) for i in range(5)], + index=Index([str(i) for i in range(5)], dtype=object), + dtype=object, + ), + Series(range(5), date_range("2020-01-01", periods=5)), Series(range(5), period_range("2020-01-01", periods=5)), ], ) diff --git a/pandas/tests/frame/conftest.py b/pandas/tests/frame/conftest.py index f7ed5180b46d9..99ea565e5b60c 100644 --- a/pandas/tests/frame/conftest.py +++ b/pandas/tests/frame/conftest.py @@ -3,6 +3,7 @@ from pandas import ( DataFrame, + Index, NaT, date_range, ) @@ -44,27 +45,12 @@ def float_string_frame(): Fixture for DataFrame of floats and strings with index of unique strings Columns are ['A', 'B', 'C', 'D', 'foo']. - - A B C D foo - w3orJvq07g -1.594062 -1.084273 -1.252457 0.356460 bar - PeukuVdmz2 0.109855 -0.955086 -0.809485 0.409747 bar - ahp2KvwiM8 -1.533729 -0.142519 -0.154666 1.302623 bar - 3WSJ7BUCGd 2.484964 0.213829 0.034778 -2.327831 bar - khdAmufk0U -0.193480 -0.743518 -0.077987 0.153646 bar - LE2DZiFlrE -0.193566 -1.343194 -0.107321 0.959978 bar - HJXSJhVn7b 0.142590 1.257603 -0.659409 -0.223844 bar - ... ... ... ... ... ... - 9a1Vypttgw -1.316394 1.601354 0.173596 1.213196 bar - h5d1gVFbEy 0.609475 1.106738 -0.155271 0.294630 bar - mK9LsTQG92 1.303613 0.857040 -1.019153 0.369468 bar - oOLksd9gKH 0.558219 -0.134491 -0.289869 -0.951033 bar - 9jgoOjKyHg 0.058270 -0.496110 -0.413212 -0.852659 bar - jZLDHclHAO 0.096298 1.267510 0.549206 -0.005235 bar - lR0nxDp1C2 -2.119350 -0.794384 0.544118 0.145849 bar - - [30 rows x 5 columns] """ - df = DataFrame(tm.getSeriesData()) + df = DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + index=Index([f"foo_{i}" for i in range(30)], dtype=object), + columns=Index(list("ABCD"), dtype=object), + ) df["foo"] = "bar" return df @@ -75,31 +61,18 @@ def mixed_float_frame(): Fixture for DataFrame of different float types with index of unique strings Columns are ['A', 'B', 'C', 'D']. - - A B C D - GI7bbDaEZe -0.237908 -0.246225 -0.468506 0.752993 - KGp9mFepzA -1.140809 -0.644046 -1.225586 0.801588 - VeVYLAb1l2 -1.154013 -1.677615 0.690430 -0.003731 - kmPME4WKhO 0.979578 0.998274 -0.776367 0.897607 - CPyopdXTiz 0.048119 -0.257174 0.836426 0.111266 - 0kJZQndAj0 0.274357 -0.281135 -0.344238 0.834541 - tqdwQsaHG8 -0.979716 -0.519897 0.582031 0.144710 - ... ... ... ... ... - 7FhZTWILQj -2.906357 1.261039 -0.780273 -0.537237 - 4pUDPM4eGq -2.042512 -0.464382 -0.382080 1.132612 - B8dUgUzwTi -1.506637 -0.364435 1.087891 0.297653 - hErlVYjVv9 1.477453 -0.495515 -0.713867 1.438427 - 1BKN3o7YLs 0.127535 -0.349812 -0.881836 0.489827 - 9S4Ekn7zga 1.445518 -2.095149 0.031982 0.373204 - xN1dNn6OV6 1.425017 -0.983995 -0.363281 -0.224502 - - [30 rows x 4 columns] """ - df = DataFrame(tm.getSeriesData()) - df.A = df.A.astype("float32") - df.B = df.B.astype("float32") - df.C = df.C.astype("float16") - df.D = df.D.astype("float64") + df = DataFrame( + { + col: np.random.default_rng(2).random(30, dtype=dtype) + for col, dtype in zip( + list("ABCD"), ["float32", "float32", "float32", "float64"] + ) + }, + index=Index([f"foo_{i}" for i in range(30)], dtype=object), + ) + # not supported by numpy random + df["C"] = df["C"].astype("float16") return df @@ -109,32 +82,14 @@ def mixed_int_frame(): Fixture for DataFrame of different int types with index of unique strings Columns are ['A', 'B', 'C', 'D']. - - A B C D - mUrCZ67juP 0 1 2 2 - rw99ACYaKS 0 1 0 0 - 7QsEcpaaVU 0 1 1 1 - xkrimI2pcE 0 1 0 0 - dz01SuzoS8 0 1 255 255 - ccQkqOHX75 -1 1 0 0 - DN0iXaoDLd 0 1 0 0 - ... .. .. ... ... - Dfb141wAaQ 1 1 254 254 - IPD8eQOVu5 0 1 0 0 - CcaKulsCmv 0 1 0 0 - rIBa8gu7E5 0 1 0 0 - RP6peZmh5o 0 1 1 1 - NMb9pipQWQ 0 1 0 0 - PqgbJEzjib 0 1 3 3 - - [30 rows x 4 columns] """ - df = DataFrame({k: v.astype(int) for k, v in tm.getSeriesData().items()}) - df.A = df.A.astype("int32") - df.B = np.ones(len(df.B), dtype="uint64") - df.C = df.C.astype("uint8") - df.D = df.C.astype("int64") - return df + return DataFrame( + { + col: np.ones(30, dtype=dtype) + for col, dtype in zip(list("ABCD"), ["int32", "uint64", "uint8", "int64"]) + }, + index=Index([f"foo_{i}" for i in range(30)], dtype=object), + ) @pytest.fixture diff --git a/pandas/tests/frame/methods/test_info.py b/pandas/tests/frame/methods/test_info.py index 7d9e0fe90f44c..fcb7677f03f27 100644 --- a/pandas/tests/frame/methods/test_info.py +++ b/pandas/tests/frame/methods/test_info.py @@ -532,11 +532,11 @@ def test_info_compute_numba(): with option_context("compute.use_numba", True): buf = StringIO() - df.info() + df.info(buf=buf) result = buf.getvalue() buf = StringIO() - df.info() + df.info(buf=buf) expected = buf.getvalue() assert result == expected diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 1ca9ec6feecae..b079c331eeebb 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -156,36 +156,18 @@ def bool_frame_with_na(): Fixture for DataFrame of booleans with index of unique strings Columns are ['A', 'B', 'C', 'D']; some entries are missing - - A B C D - zBZxY2IDGd False False False False - IhBWBMWllt False True True True - ctjdvZSR6R True False True True - AVTujptmxb False True False True - G9lrImrSWq False False False True - sFFwdIUfz2 NaN NaN NaN NaN - s15ptEJnRb NaN NaN NaN NaN - ... ... ... ... ... - UW41KkDyZ4 True True False False - l9l6XkOdqV True False False False - X2MeZfzDYA False True False False - xWkIKU7vfX False True False True - QOhL6VmpGU False False False True - 22PwkRJdat False True False False - kfboQ3VeIK True False True False - - [30 rows x 4 columns] """ - df = DataFrame(tm.getSeriesData()) > 0 - df = df.astype(object) + df = DataFrame( + np.concatenate( + [np.ones((15, 4), dtype=bool), np.zeros((15, 4), dtype=bool)], axis=0 + ), + index=Index([f"foo_{i}" for i in range(30)], dtype=object), + columns=Index(list("ABCD"), dtype=object), + dtype=object, + ) # set some NAs df.iloc[5:10] = np.nan df.iloc[15:20, -2:] = np.nan - - # For `any` tests we need to have at least one True before the first NaN - # in each column - for i in range(4): - df.iloc[i, i] = True return df @@ -195,27 +177,12 @@ def float_frame_with_na(): Fixture for DataFrame of floats with index of unique strings Columns are ['A', 'B', 'C', 'D']; some entries are missing - - A B C D - ABwBzA0ljw -1.128865 -0.897161 0.046603 0.274997 - DJiRzmbyQF 0.728869 0.233502 0.722431 -0.890872 - neMgPD5UBF 0.486072 -1.027393 -0.031553 1.449522 - 0yWA4n8VeX -1.937191 -1.142531 0.805215 -0.462018 - 3slYUbbqU1 0.153260 1.164691 1.489795 -0.545826 - soujjZ0A08 NaN NaN NaN NaN - 7W6NLGsjB9 NaN NaN NaN NaN - ... ... ... ... ... - uhfeaNkCR1 -0.231210 -0.340472 0.244717 -0.901590 - n6p7GYuBIV -0.419052 1.922721 -0.125361 -0.727717 - ZhzAeY6p1y 1.234374 -1.425359 -0.827038 -0.633189 - uWdPsORyUh 0.046738 -0.980445 -1.102965 0.605503 - 3DJA6aN590 -0.091018 -1.684734 -1.100900 0.215947 - 2GBPAzdbMk -2.883405 -1.021071 1.209877 1.633083 - sHadBoyVHw -2.223032 -0.326384 0.258931 0.245517 - - [30 rows x 4 columns] """ - df = DataFrame(tm.getSeriesData()) + df = DataFrame( + np.random.default_rng(2).standard_normal((30, 4)), + index=Index([f"foo_{i}" for i in range(30)], dtype=object), + columns=Index(list("ABCD"), dtype=object), + ) # set some NAs df.iloc[5:10] = np.nan df.iloc[15:20, -2:] = np.nan diff --git a/pandas/tests/indexes/datetimes/methods/test_asof.py b/pandas/tests/indexes/datetimes/methods/test_asof.py index f52b6da5b2f07..dc92f533087bc 100644 --- a/pandas/tests/indexes/datetimes/methods/test_asof.py +++ b/pandas/tests/indexes/datetimes/methods/test_asof.py @@ -6,7 +6,6 @@ date_range, isna, ) -import pandas._testing as tm class TestAsOf: @@ -18,7 +17,7 @@ def test_asof_partial(self): assert not isinstance(result, Index) def test_asof(self): - index = tm.makeDateIndex(100) + index = date_range("2020-01-01", periods=10) dt = index[0] assert index.asof(dt) == dt diff --git a/pandas/tests/indexes/datetimes/methods/test_isocalendar.py b/pandas/tests/indexes/datetimes/methods/test_isocalendar.py index 3f5a18675735a..97f1003e0f43f 100644 --- a/pandas/tests/indexes/datetimes/methods/test_isocalendar.py +++ b/pandas/tests/indexes/datetimes/methods/test_isocalendar.py @@ -1,6 +1,7 @@ from pandas import ( DataFrame, DatetimeIndex, + date_range, ) import pandas._testing as tm @@ -21,7 +22,7 @@ def test_isocalendar_returns_correct_values_close_to_new_year_with_tz(): def test_dti_timestamp_isocalendar_fields(): - idx = tm.makeDateIndex(100) + idx = date_range("2020-01-01", periods=10) expected = tuple(idx.isocalendar().iloc[-1].to_list()) result = idx[-1].isocalendar() assert result == expected diff --git a/pandas/tests/indexes/datetimes/test_scalar_compat.py b/pandas/tests/indexes/datetimes/test_scalar_compat.py index 81992219d71b4..e93fc0e2a4e2e 100644 --- a/pandas/tests/indexes/datetimes/test_scalar_compat.py +++ b/pandas/tests/indexes/datetimes/test_scalar_compat.py @@ -106,7 +106,7 @@ def test_dti_timetz(self, tz_naive_fixture): ) def test_dti_timestamp_fields(self, field): # extra fields from DatetimeIndex like quarter and week - idx = tm.makeDateIndex(100) + idx = date_range("2020-01-01", periods=10) expected = getattr(idx, field)[-1] result = getattr(Timestamp(idx[-1]), field) diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py index 993f88db38ea6..3ed7fcc027a06 100644 --- a/pandas/tests/indexes/datetimes/test_setops.py +++ b/pandas/tests/indexes/datetimes/test_setops.py @@ -42,7 +42,7 @@ class TestDatetimeIndexSetOps: # TODO: moved from test_datetimelike; dedup with version below def test_union2(self, sort): - everything = tm.makeDateIndex(10) + everything = date_range("2020-01-01", periods=10) first = everything[:5] second = everything[5:] union = first.union(second, sort=sort) @@ -50,7 +50,7 @@ def test_union2(self, sort): @pytest.mark.parametrize("box", [np.array, Series, list]) def test_union3(self, sort, box): - everything = tm.makeDateIndex(10) + everything = date_range("2020-01-01", periods=10) first = everything[:5] second = everything[5:] @@ -203,7 +203,7 @@ def test_union_same_timezone_different_units(self): # TODO: moved from test_datetimelike; de-duplicate with version below def test_intersection2(self): - first = tm.makeDateIndex(10) + first = date_range("2020-01-01", periods=10) second = first[5:] intersect = first.intersection(second) tm.assert_index_equal(intersect, second) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 3db81c0285bd2..bb8822f047330 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -540,7 +540,9 @@ def test_map_tseries_indices_return_index(self, index): tm.assert_index_equal(expected, result) def test_map_tseries_indices_accsr_return_index(self): - date_index = tm.makeDateIndex(24, freq="h", name="hourly") + date_index = DatetimeIndex( + date_range("2020-01-01", periods=24, freq="h"), name="hourly" + ) result = date_index.map(lambda x: x.hour) expected = Index(np.arange(24, dtype="int64"), name="hourly") tm.assert_index_equal(result, expected, exact=True) @@ -1001,7 +1003,7 @@ def test_str_attribute(self, method): "index", [ Index(range(5)), - tm.makeDateIndex(10), + date_range("2020-01-01", periods=10), MultiIndex.from_tuples([("foo", "1"), ("bar", "3")]), period_range(start="2000", end="2010", freq="Y"), ], @@ -1065,7 +1067,7 @@ def test_indexing_doesnt_change_class(self): def test_outer_join_sort(self): left_index = Index(np.random.default_rng(2).permutation(15)) - right_index = tm.makeDateIndex(10) + right_index = date_range("2020-01-01", periods=10) with tm.assert_produces_warning(RuntimeWarning): result = left_index.join(right_index, how="outer") diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 5275050391ca3..37bc2812a2095 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -90,15 +90,14 @@ def assert_json_roundtrip_equal(result, expected, orient): class TestPandasContainer: @pytest.fixture def categorical_frame(self): - _seriesd = tm.getSeriesData() - - _cat_frame = DataFrame(_seriesd) - - cat = ["bah"] * 5 + ["bar"] * 5 + ["baz"] * 5 + ["foo"] * (len(_cat_frame) - 15) - _cat_frame.index = pd.CategoricalIndex(cat, name="E") - _cat_frame["E"] = list(reversed(cat)) - _cat_frame["sort"] = np.arange(len(_cat_frame), dtype="int64") - return _cat_frame + data = { + c: np.random.default_rng(i).standard_normal(30) + for i, c in enumerate(list("ABCD")) + } + cat = ["bah"] * 5 + ["bar"] * 5 + ["baz"] * 5 + ["foo"] * 15 + data["E"] = list(reversed(cat)) + data["sort"] = np.arange(30, dtype="int64") + return DataFrame(data, index=pd.CategoricalIndex(cat, name="E")) @pytest.fixture def datetime_series(self): diff --git a/pandas/tests/io/pytables/test_time_series.py b/pandas/tests/io/pytables/test_time_series.py index 4afcf5600dce6..726dd0d420347 100644 --- a/pandas/tests/io/pytables/test_time_series.py +++ b/pandas/tests/io/pytables/test_time_series.py @@ -8,6 +8,7 @@ DatetimeIndex, Series, _testing as tm, + date_range, period_range, ) from pandas.tests.io.pytables.common import ensure_clean_store @@ -28,7 +29,7 @@ def test_store_datetime_fractional_secs(setup_path, unit): @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_tseries_indices_series(setup_path): with ensure_clean_store(setup_path) as store: - idx = tm.makeDateIndex(10) + idx = date_range("2020-01-01", periods=10) ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx) store["a"] = ser result = store["a"] @@ -50,7 +51,7 @@ def test_tseries_indices_series(setup_path): @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") def test_tseries_indices_frame(setup_path): with ensure_clean_store(setup_path) as store: - idx = tm.makeDateIndex(10) + idx = date_range("2020-01-01", periods=10) df = DataFrame( np.random.default_rng(2).standard_normal((len(idx), 3)), index=idx ) diff --git a/pandas/tests/plotting/test_converter.py b/pandas/tests/plotting/test_converter.py index 509e0ea5c482e..f748d7c5fc758 100644 --- a/pandas/tests/plotting/test_converter.py +++ b/pandas/tests/plotting/test_converter.py @@ -260,7 +260,7 @@ def test_time_formatter(self, time, format_expected): @pytest.mark.parametrize("freq", ("B", "ms", "s")) def test_dateindex_conversion(self, freq, dtc): rtol = 10**-9 - dateindex = tm.makeDateIndex(k=10, freq=freq) + dateindex = date_range("2020-01-01", periods=10, freq=freq) rs = dtc.convert(dateindex, None, None) xp = converter.mdates.date2num(dateindex._mpl_repr()) tm.assert_almost_equal(rs, xp, rtol=rtol) diff --git a/pandas/tests/plotting/test_series.py b/pandas/tests/plotting/test_series.py index c8b47666e1b4a..9bf76637e1d71 100644 --- a/pandas/tests/plotting/test_series.py +++ b/pandas/tests/plotting/test_series.py @@ -237,7 +237,7 @@ def test_boolean(self): with pytest.raises(TypeError, match=msg): _check_plot_works(s.plot) - @pytest.mark.parametrize("index", [None, tm.makeDateIndex(k=4)]) + @pytest.mark.parametrize("index", [None, date_range("2020-01-01", periods=4)]) def test_line_area_nan_series(self, index): values = [1, 2, np.nan, 3] d = Series(values, index=index) diff --git a/pandas/tests/series/indexing/test_get.py b/pandas/tests/series/indexing/test_get.py index 61007c08b50e0..1f3711ad91903 100644 --- a/pandas/tests/series/indexing/test_get.py +++ b/pandas/tests/series/indexing/test_get.py @@ -3,8 +3,10 @@ import pandas as pd from pandas import ( + DatetimeIndex, Index, Series, + date_range, ) import pandas._testing as tm @@ -168,7 +170,9 @@ def test_get_with_default(): "arr", [ np.random.default_rng(2).standard_normal(10), - tm.makeDateIndex(10, name="a").tz_localize(tz="US/Eastern"), + DatetimeIndex(date_range("2020-01-01", periods=10), name="a").tz_localize( + tz="US/Eastern" + ), ], ) def test_get_with_ea(arr): diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py index 5d0ef893d5723..a5170898b1720 100644 --- a/pandas/tests/series/methods/test_fillna.py +++ b/pandas/tests/series/methods/test_fillna.py @@ -71,7 +71,9 @@ def test_fillna_value_or_method(self, datetime_series): datetime_series.fillna(value=0, method="ffill") def test_fillna(self): - ts = Series([0.0, 1.0, 2.0, 3.0, 4.0], index=tm.makeDateIndex(5)) + ts = Series( + [0.0, 1.0, 2.0, 3.0, 4.0], index=date_range("2020-01-01", periods=5) + ) tm.assert_series_equal(ts, ts.fillna(method="ffill")) @@ -880,7 +882,9 @@ def test_fillna_bug(self): tm.assert_series_equal(filled, expected) def test_ffill(self): - ts = Series([0.0, 1.0, 2.0, 3.0, 4.0], index=tm.makeDateIndex(5)) + ts = Series( + [0.0, 1.0, 2.0, 3.0, 4.0], index=date_range("2020-01-01", periods=5) + ) ts.iloc[2] = np.nan tm.assert_series_equal(ts.ffill(), ts.fillna(method="ffill")) @@ -891,7 +895,9 @@ def test_ffill_mixed_dtypes_without_missing_data(self): tm.assert_series_equal(series, result) def test_bfill(self): - ts = Series([0.0, 1.0, 2.0, 3.0, 4.0], index=tm.makeDateIndex(5)) + ts = Series( + [0.0, 1.0, 2.0, 3.0, 4.0], index=date_range("2020-01-01", periods=5) + ) ts.iloc[2] = np.nan tm.assert_series_equal(ts.bfill(), ts.fillna(method="bfill")) diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index fe0f79b766f72..477f36bdf4214 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -52,7 +52,7 @@ def test_replace_noop_doesnt_downcast(self): assert res.dtype == object def test_replace(self): - N = 100 + N = 50 ser = pd.Series(np.random.default_rng(2).standard_normal(N)) ser[0:4] = np.nan ser[6:10] = 0 @@ -70,7 +70,7 @@ def test_replace(self): ser = pd.Series( np.fabs(np.random.default_rng(2).standard_normal(N)), - tm.makeDateIndex(N), + pd.date_range("2020-01-01", periods=N), dtype=object, ) ser[:5] = np.nan @@ -290,10 +290,10 @@ def test_replace_Int_with_na(self, any_int_ea_dtype): tm.assert_series_equal(result, expected) def test_replace2(self): - N = 100 + N = 50 ser = pd.Series( np.fabs(np.random.default_rng(2).standard_normal(N)), - tm.makeDateIndex(N), + pd.date_range("2020-01-01", periods=N), dtype=object, ) ser[:5] = np.nan diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index e08f8d0c15f39..773d7e174feac 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -2147,7 +2147,7 @@ def test_series_string_inference_na_first(self): class TestSeriesConstructorIndexCoercion: def test_series_constructor_datetimelike_index_coercion(self): - idx = tm.makeDateIndex(10000) + idx = date_range("2020-01-01", periods=5) ser = Series( np.random.default_rng(2).standard_normal(len(idx)), idx.astype(object) )
null
https://api.github.com/repos/pandas-dev/pandas/pulls/56241
2023-11-29T19:46:43Z
2023-11-30T17:35:19Z
2023-11-30T17:35:19Z
2023-11-30T17:35:22Z
TST: dt64 units
diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 149bc2d932f0e..26cbc77e4e8ae 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -467,13 +467,15 @@ def _array_strptime_with_fallback( """ result, tz_out = array_strptime(arg, fmt, exact=exact, errors=errors, utc=utc) if tz_out is not None: - dtype = DatetimeTZDtype(tz=tz_out) + unit = np.datetime_data(result.dtype)[0] + dtype = DatetimeTZDtype(tz=tz_out, unit=unit) dta = DatetimeArray._simple_new(result, dtype=dtype) if utc: dta = dta.tz_convert("UTC") return Index(dta, name=name) elif result.dtype != object and utc: - res = Index(result, dtype="M8[ns, UTC]", name=name) + unit = np.datetime_data(result.dtype)[0] + res = Index(result, dtype=f"M8[{unit}, UTC]", name=name) return res return Index(result, dtype=result.dtype, name=name) diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index e88bde07aee90..73c6b4a1b2a0d 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -746,20 +746,10 @@ def test_timedelta_ops_with_missing_values(self): s1 = pd.to_timedelta(Series(["00:00:01"])) s2 = pd.to_timedelta(Series(["00:00:02"])) - msg = r"dtype datetime64\[ns\] cannot be converted to timedelta64\[ns\]" - with pytest.raises(TypeError, match=msg): - # Passing datetime64-dtype data to TimedeltaIndex is no longer - # supported GH#29794 - pd.to_timedelta(Series([NaT])) # TODO: belongs elsewhere? - sn = pd.to_timedelta(Series([NaT], dtype="m8[ns]")) df1 = DataFrame(["00:00:01"]).apply(pd.to_timedelta) df2 = DataFrame(["00:00:02"]).apply(pd.to_timedelta) - with pytest.raises(TypeError, match=msg): - # Passing datetime64-dtype data to TimedeltaIndex is no longer - # supported GH#29794 - DataFrame([NaT]).apply(pd.to_timedelta) # TODO: belongs elsewhere? dfn = DataFrame([NaT._value]).apply(pd.to_timedelta) diff --git a/pandas/tests/arrays/test_array.py b/pandas/tests/arrays/test_array.py index eb6e93b490574..e2b8ebcb79a3b 100644 --- a/pandas/tests/arrays/test_array.py +++ b/pandas/tests/arrays/test_array.py @@ -268,7 +268,7 @@ def test_array_copy(): ), ( [datetime.datetime(2000, 1, 1), datetime.datetime(2001, 1, 1)], - DatetimeArray._from_sequence(["2000", "2001"]), + DatetimeArray._from_sequence(["2000", "2001"], dtype="M8[ns]"), ), ( np.array([1, 2], dtype="M8[ns]"), @@ -284,7 +284,7 @@ def test_array_copy(): ( [pd.Timestamp("2000", tz="CET"), pd.Timestamp("2001", tz="CET")], DatetimeArray._from_sequence( - ["2000", "2001"], dtype=pd.DatetimeTZDtype(tz="CET") + ["2000", "2001"], dtype=pd.DatetimeTZDtype(tz="CET", unit="ns") ), ), ( @@ -293,7 +293,7 @@ def test_array_copy(): datetime.datetime(2001, 1, 1, tzinfo=cet), ], DatetimeArray._from_sequence( - ["2000", "2001"], dtype=pd.DatetimeTZDtype(tz=cet) + ["2000", "2001"], dtype=pd.DatetimeTZDtype(tz=cet, unit="ns") ), ), # timedelta diff --git a/pandas/tests/frame/constructors/test_from_records.py b/pandas/tests/frame/constructors/test_from_records.py index 4ad4e29550d56..bcf4e8fb0e64a 100644 --- a/pandas/tests/frame/constructors/test_from_records.py +++ b/pandas/tests/frame/constructors/test_from_records.py @@ -442,26 +442,27 @@ def test_from_records_misc_brokenness(self): exp = DataFrame(data, index=["a", "b", "c"]) tm.assert_frame_equal(result, exp) + def test_from_records_misc_brokenness2(self): # GH#2623 rows = [] rows.append([datetime(2010, 1, 1), 1]) rows.append([datetime(2010, 1, 2), "hi"]) # test col upconverts to obj - df2_obj = DataFrame.from_records(rows, columns=["date", "test"]) - result = df2_obj.dtypes - expected = Series( - [np.dtype("datetime64[ns]"), np.dtype("object")], index=["date", "test"] + result = DataFrame.from_records(rows, columns=["date", "test"]) + expected = DataFrame( + {"date": [row[0] for row in rows], "test": [row[1] for row in rows]} ) - tm.assert_series_equal(result, expected) + tm.assert_frame_equal(result, expected) + assert result.dtypes["test"] == np.dtype(object) + def test_from_records_misc_brokenness3(self): rows = [] rows.append([datetime(2010, 1, 1), 1]) rows.append([datetime(2010, 1, 2), 1]) - df2_obj = DataFrame.from_records(rows, columns=["date", "test"]) - result = df2_obj.dtypes - expected = Series( - [np.dtype("datetime64[ns]"), np.dtype("int64")], index=["date", "test"] + result = DataFrame.from_records(rows, columns=["date", "test"]) + expected = DataFrame( + {"date": [row[0] for row in rows], "test": [row[1] for row in rows]} ) - tm.assert_series_equal(result, expected) + tm.assert_frame_equal(result, expected) def test_from_records_empty(self): # GH#3562 diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index f07c53060a06b..4b32d3de59ca2 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -809,11 +809,13 @@ def test_replace_for_new_dtypes(self, datetime_frame): Timestamp("20130104", tz="US/Eastern"), DataFrame( { - "A": [ - Timestamp("20130101", tz="US/Eastern"), - Timestamp("20130104", tz="US/Eastern"), - Timestamp("20130103", tz="US/Eastern"), - ], + "A": pd.DatetimeIndex( + [ + Timestamp("20130101", tz="US/Eastern"), + Timestamp("20130104", tz="US/Eastern"), + Timestamp("20130103", tz="US/Eastern"), + ] + ).as_unit("ns"), "B": [0, np.nan, 2], } ), @@ -1174,6 +1176,7 @@ def test_replace_datetimetz(self): "B": [0, np.nan, 2], } ) + expected["A"] = expected["A"].dt.as_unit("ns") tm.assert_frame_equal(result, expected) result = df.copy() @@ -1195,6 +1198,7 @@ def test_replace_datetimetz(self): "B": [0, np.nan, 2], } ) + expected["A"] = expected["A"].dt.as_unit("ns") tm.assert_frame_equal(result, expected) result = df.copy() diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index 377128ee12ee6..c989b3d26677c 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -699,9 +699,12 @@ def test_reset_index_multiindex_nat(): df = DataFrame({"id": idx, "tstamp": tstamp, "a": list("abc")}) df.loc[2, "tstamp"] = pd.NaT result = df.set_index(["id", "tstamp"]).reset_index("id") + exp_dti = pd.DatetimeIndex( + ["2015-07-01", "2015-07-02", "NaT"], dtype="M8[ns]", name="tstamp" + ) expected = DataFrame( {"id": range(3), "a": list("abc")}, - index=pd.DatetimeIndex(["2015-07-01", "2015-07-02", "NaT"], name="tstamp"), + index=exp_dti, ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index 4a0b192244dc8..73969457135f0 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -592,13 +592,13 @@ def test_integer_values_and_tz_interpreted_as_utc(self): result = DatetimeIndex(values).tz_localize("US/Central") - expected = DatetimeIndex(["2000-01-01T00:00:00"], tz="US/Central") + expected = DatetimeIndex(["2000-01-01T00:00:00"], dtype="M8[ns, US/Central]") tm.assert_index_equal(result, expected) # but UTC is *not* deprecated. with tm.assert_produces_warning(None): result = DatetimeIndex(values, tz="UTC") - expected = DatetimeIndex(["2000-01-01T00:00:00"], tz="UTC") + expected = DatetimeIndex(["2000-01-01T00:00:00"], dtype="M8[ns, UTC]") tm.assert_index_equal(result, expected) def test_constructor_coverage(self): diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 411cc90ba41a7..5275050391ca3 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -1625,7 +1625,8 @@ def test_read_timezone_information(self): result = read_json( StringIO('{"2019-01-01T11:00:00.000Z":88}'), typ="series", orient="index" ) - expected = Series([88], index=DatetimeIndex(["2019-01-01 11:00:00"], tz="UTC")) + exp_dti = DatetimeIndex(["2019-01-01 11:00:00"], dtype="M8[ns, UTC]") + expected = Series([88], index=exp_dti) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( diff --git a/pandas/tests/reshape/concat/test_datetimes.py b/pandas/tests/reshape/concat/test_datetimes.py index c00a2dc92a52b..71ddff7438254 100644 --- a/pandas/tests/reshape/concat/test_datetimes.py +++ b/pandas/tests/reshape/concat/test_datetimes.py @@ -61,7 +61,6 @@ def test_concat_datetime_timezone(self): dtype="M8[ns, Europe/Paris]", freq="h", ) - expected = DataFrame( [[1, 1], [2, 2], [3, 3]], index=exp_idx, columns=["a", "b"] ) diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index f8ececf6c0540..4a852daaadf98 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -437,8 +437,10 @@ def test_pivot_no_values(self): index=idx, ) res = df.pivot_table(index=df.index.month, columns=Grouper(key="dt", freq="ME")) - exp_columns = MultiIndex.from_tuples([("A", pd.Timestamp("2011-01-31"))]) - exp_columns.names = [None, "dt"] + exp_columns = MultiIndex.from_arrays( + [["A"], pd.DatetimeIndex(["2011-01-31"], dtype="M8[ns]")], + names=[None, "dt"], + ) exp = DataFrame( [3.25, 2.0], index=Index([1, 2], dtype=np.int32), columns=exp_columns ) diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 0f3577a214186..fce0581260210 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -88,7 +88,8 @@ def test_setitem_with_tz(self, tz, indexer_sli): Timestamp("2016-01-01 00:00", tz=tz), Timestamp("2011-01-01 00:00", tz=tz), Timestamp("2016-01-01 02:00", tz=tz), - ] + ], + dtype=orig.dtype, ) # scalar @@ -100,6 +101,7 @@ def test_setitem_with_tz(self, tz, indexer_sli): vals = Series( [Timestamp("2011-01-01", tz=tz), Timestamp("2012-01-01", tz=tz)], index=[1, 2], + dtype=orig.dtype, ) assert vals.dtype == f"datetime64[ns, {tz}]" @@ -108,7 +110,8 @@ def test_setitem_with_tz(self, tz, indexer_sli): Timestamp("2016-01-01 00:00", tz=tz), Timestamp("2011-01-01 00:00", tz=tz), Timestamp("2012-01-01 00:00", tz=tz), - ] + ], + dtype=orig.dtype, ) ser = orig.copy() diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 8139fe52c7037..f74fe459eb4d6 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -2058,7 +2058,11 @@ def test_to_datetime_unit(self, dtype): ser = Series([epoch + t for t in range(20)]).astype(dtype) result = to_datetime(ser, unit="s") expected = Series( - [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] + [ + Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) + for t in range(20) + ], + dtype="M8[ns]", ) tm.assert_series_equal(result, expected) @@ -2208,7 +2212,8 @@ def test_dataframe_field_aliases_column_subset(self, df, cache, unit): # unit mappings result = to_datetime(df[list(unit.keys())].rename(columns=unit), cache=cache) expected = Series( - [Timestamp("20150204 06:58:10"), Timestamp("20160305 07:59:11")] + [Timestamp("20150204 06:58:10"), Timestamp("20160305 07:59:11")], + dtype="M8[ns]", ) tm.assert_series_equal(result, expected) @@ -2970,7 +2975,8 @@ def test_to_datetime_iso8601_noleading_0s(self, cache, format): Timestamp("2015-03-03"), ] ) - tm.assert_series_equal(to_datetime(ser, format=format, cache=cache), expected) + result = to_datetime(ser, format=format, cache=cache) + tm.assert_series_equal(result, expected) def test_parse_dates_infer_datetime_format_warning(self): # GH 49024 @@ -3364,7 +3370,8 @@ def test_julian(self, julian_dates): def test_unix(self): result = Series(to_datetime([0, 1, 2], unit="D", origin="unix")) expected = Series( - [Timestamp("1970-01-01"), Timestamp("1970-01-02"), Timestamp("1970-01-03")] + [Timestamp("1970-01-01"), Timestamp("1970-01-02"), Timestamp("1970-01-03")], + dtype="M8[ns]", ) tm.assert_series_equal(result, expected) @@ -3483,7 +3490,7 @@ def test_arg_tz_ns_unit(self, offset, utc, exp): # GH 25546 arg = "2019-01-01T00:00:00.000" + offset result = to_datetime([arg], unit="ns", utc=utc) - expected = to_datetime([exp]) + expected = to_datetime([exp]).as_unit("ns") tm.assert_index_equal(result, expected) @@ -3610,11 +3617,12 @@ def test_to_datetime_monotonic_increasing_index(cache): ) def test_to_datetime_cache_coerce_50_lines_outofbounds(series_length): # GH#45319 - s = Series( + ser = Series( [datetime.fromisoformat("1446-04-12 00:00:00+00:00")] - + ([datetime.fromisoformat("1991-10-20 00:00:00+00:00")] * series_length) + + ([datetime.fromisoformat("1991-10-20 00:00:00+00:00")] * series_length), + dtype=object, ) - result1 = to_datetime(s, errors="coerce", utc=True) + result1 = to_datetime(ser, errors="coerce", utc=True) expected1 = Series( [NaT] + ([Timestamp("1991-10-20 00:00:00+00:00")] * series_length) @@ -3622,7 +3630,7 @@ def test_to_datetime_cache_coerce_50_lines_outofbounds(series_length): tm.assert_series_equal(result1, expected1) - result2 = to_datetime(s, errors="ignore", utc=True) + result2 = to_datetime(ser, errors="ignore", utc=True) expected2 = Series( [datetime.fromisoformat("1446-04-12 00:00:00+00:00")] @@ -3632,7 +3640,7 @@ def test_to_datetime_cache_coerce_50_lines_outofbounds(series_length): tm.assert_series_equal(result2, expected2) with pytest.raises(OutOfBoundsDatetime, match="Out of bounds nanosecond timestamp"): - to_datetime(s, errors="raise", utc=True) + to_datetime(ser, errors="raise", utc=True) def test_to_datetime_format_f_parse_nanos(): diff --git a/pandas/tests/tools/test_to_timedelta.py b/pandas/tests/tools/test_to_timedelta.py index e588bc83b0de8..b3d4d9d67190f 100644 --- a/pandas/tests/tools/test_to_timedelta.py +++ b/pandas/tests/tools/test_to_timedelta.py @@ -21,6 +21,17 @@ class TestTimedeltas: + def test_to_timedelta_dt64_raises(self): + # Passing datetime64-dtype data to TimedeltaIndex is no longer + # supported GH#29794 + msg = r"dtype datetime64\[ns\] cannot be converted to timedelta64\[ns\]" + + ser = Series([pd.NaT]) + with pytest.raises(TypeError, match=msg): + to_timedelta(ser) + with pytest.raises(TypeError, match=msg): + ser.to_frame().apply(to_timedelta) + @pytest.mark.parametrize("readonly", [True, False]) def test_to_timedelta_readonly(self, readonly): # GH#34857
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. aimed at trimming the diff in #55901
https://api.github.com/repos/pandas-dev/pandas/pulls/56239
2023-11-29T16:51:01Z
2023-11-29T17:50:27Z
2023-11-29T17:50:27Z
2023-11-30T01:31:26Z
DEPR: Default of observed=False in DataFrame.pivot_table
diff --git a/doc/source/user_guide/categorical.rst b/doc/source/user_guide/categorical.rst index 34d04745ccdb5..8fb991dca02db 100644 --- a/doc/source/user_guide/categorical.rst +++ b/doc/source/user_guide/categorical.rst @@ -647,7 +647,7 @@ Pivot tables: raw_cat = pd.Categorical(["a", "a", "b", "b"], categories=["a", "b", "c"]) df = pd.DataFrame({"A": raw_cat, "B": ["c", "d", "c", "d"], "values": [1, 2, 3, 4]}) - pd.pivot_table(df, values="values", index=["A", "B"]) + pd.pivot_table(df, values="values", index=["A", "B"], observed=False) Data munging ------------ diff --git a/doc/source/whatsnew/v0.23.0.rst b/doc/source/whatsnew/v0.23.0.rst index cdffc6968a170..808741ccf4475 100644 --- a/doc/source/whatsnew/v0.23.0.rst +++ b/doc/source/whatsnew/v0.23.0.rst @@ -286,12 +286,33 @@ For pivoting operations, this behavior is *already* controlled by the ``dropna`` df = pd.DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]}) df -.. ipython:: python - pd.pivot_table(df, values='values', index=['A', 'B'], - dropna=True) - pd.pivot_table(df, values='values', index=['A', 'B'], - dropna=False) +.. code-block:: ipython + + In [1]: pd.pivot_table(df, values='values', index=['A', 'B'], dropna=True) + + Out[1]: + values + A B + a c 1.0 + d 2.0 + b c 3.0 + d 4.0 + + In [2]: pd.pivot_table(df, values='values', index=['A', 'B'], dropna=False) + + Out[2]: + values + A B + a c 1.0 + d 2.0 + y NaN + b c 3.0 + d 4.0 + y NaN + z c NaN + d NaN + y NaN .. _whatsnew_0230.enhancements.window_raw: diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index ade87c4215a38..c8fddd8ac49c2 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -434,6 +434,7 @@ Other Deprecations - Deprecated the ``ordinal`` keyword in :class:`PeriodIndex`, use :meth:`PeriodIndex.from_ordinals` instead (:issue:`55960`) - Deprecated the ``unit`` keyword in :class:`TimedeltaIndex` construction, use :func:`to_timedelta` instead (:issue:`55499`) - Deprecated the behavior of :meth:`Series.value_counts` and :meth:`Index.value_counts` with object dtype; in a future version these will not perform dtype inference on the resulting :class:`Index`, do ``result.index = result.index.infer_objects()`` to retain the old behavior (:issue:`56161`) +- Deprecated the default of ``observed=False`` in :meth:`DataFrame.pivot_table`; will be ``True`` in a future version (:issue:`56236`) - Deprecated the extension test classes ``BaseNoReduceTests``, ``BaseBooleanReduceTests``, and ``BaseNumericReduceTests``, use ``BaseReduceTests`` instead (:issue:`54663`) - Deprecated the option ``mode.data_manager`` and the ``ArrayManager``; only the ``BlockManager`` will be available in future versions (:issue:`55043`) - Deprecated the previous implementation of :class:`DataFrame.stack`; specify ``future_stack=True`` to adopt the future version (:issue:`53515`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 008c1e0d10ba4..c0c91d808f31d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -9297,6 +9297,11 @@ def pivot( If True: only show observed values for categorical groupers. If False: show all values for categorical groupers. + .. deprecated:: 2.2.0 + + The default value of ``False`` is deprecated and will change to + ``True`` in a future version of pandas. + sort : bool, default True Specifies if the result should be sorted. @@ -9407,7 +9412,7 @@ def pivot_table( margins: bool = False, dropna: bool = True, margins_name: Level = "All", - observed: bool = False, + observed: bool | lib.NoDefault = lib.no_default, sort: bool = True, ) -> DataFrame: from pandas.core.reshape.pivot import pivot_table diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index eba4f72b5eb8f..82718d4c43a65 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -10,6 +10,7 @@ Literal, cast, ) +import warnings import numpy as np @@ -18,6 +19,7 @@ Appender, Substitution, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.cast import maybe_downcast_to_dtype from pandas.core.dtypes.common import ( @@ -68,7 +70,7 @@ def pivot_table( margins: bool = False, dropna: bool = True, margins_name: Hashable = "All", - observed: bool = False, + observed: bool | lib.NoDefault = lib.no_default, sort: bool = True, ) -> DataFrame: index = _convert_by(index) @@ -123,7 +125,7 @@ def __internal_pivot_table( margins: bool, dropna: bool, margins_name: Hashable, - observed: bool, + observed: bool | lib.NoDefault, sort: bool, ) -> DataFrame: """ @@ -166,7 +168,18 @@ def __internal_pivot_table( pass values = list(values) - grouped = data.groupby(keys, observed=observed, sort=sort, dropna=dropna) + observed_bool = False if observed is lib.no_default else observed + grouped = data.groupby(keys, observed=observed_bool, sort=sort, dropna=dropna) + if observed is lib.no_default and any( + ping._passed_categorical for ping in grouped.grouper.groupings + ): + warnings.warn( + "The default value of observed=False is deprecated and will change " + "to observed=True in a future version of pandas. Specify " + "observed=False to silence this warning and retain the current behavior", + category=FutureWarning, + stacklevel=find_stack_level(), + ) agged = grouped.agg(aggfunc) if dropna and isinstance(agged, ABCDataFrame) and len(agged.columns): @@ -719,6 +732,7 @@ def crosstab( margins=margins, margins_name=margins_name, dropna=dropna, + observed=False, **kwargs, # type: ignore[arg-type] ) diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 4a852daaadf98..dab2b034d3fd4 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -201,7 +201,9 @@ def test_pivot_table_categorical(self): ["c", "d", "c", "d"], categories=["c", "d", "y"], ordered=True ) df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]}) - result = pivot_table(df, values="values", index=["A", "B"], dropna=True) + msg = "The default value of observed=False is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = pivot_table(df, values="values", index=["A", "B"], dropna=True) exp_index = MultiIndex.from_arrays([cat1, cat2], names=["A", "B"]) expected = DataFrame({"values": [1.0, 2.0, 3.0, 4.0]}, index=exp_index) @@ -220,7 +222,9 @@ def test_pivot_table_dropna_categoricals(self, dropna): ) df["A"] = df["A"].astype(CategoricalDtype(categories, ordered=False)) - result = df.pivot_table(index="B", columns="A", values="C", dropna=dropna) + msg = "The default value of observed=False is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.pivot_table(index="B", columns="A", values="C", dropna=dropna) expected_columns = Series(["a", "b", "c"], name="A") expected_columns = expected_columns.astype( CategoricalDtype(categories, ordered=False) @@ -250,7 +254,9 @@ def test_pivot_with_non_observable_dropna(self, dropna): } ) - result = df.pivot_table(index="A", values="B", dropna=dropna) + msg = "The default value of observed=False is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.pivot_table(index="A", values="B", dropna=dropna) if dropna: values = [2.0, 3.0] codes = [0, 1] @@ -283,7 +289,9 @@ def test_pivot_with_non_observable_dropna_multi_cat(self, dropna): } ) - result = df.pivot_table(index="A", values="B", dropna=dropna) + msg = "The default value of observed=False is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.pivot_table(index="A", values="B", dropna=dropna) expected = DataFrame( {"B": [2.0, 3.0, 0.0]}, index=Index( @@ -301,7 +309,10 @@ def test_pivot_with_non_observable_dropna_multi_cat(self, dropna): def test_pivot_with_interval_index(self, interval_values, dropna): # GH 25814 df = DataFrame({"A": interval_values, "B": 1}) - result = df.pivot_table(index="A", values="B", dropna=dropna) + + msg = "The default value of observed=False is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.pivot_table(index="A", values="B", dropna=dropna) expected = DataFrame( {"B": 1.0}, index=Index(interval_values.unique(), name="A") ) @@ -322,9 +333,11 @@ def test_pivot_with_interval_index_margins(self): } ) - pivot_tab = pivot_table( - df, index="C", columns="B", values="A", aggfunc="sum", margins=True - ) + msg = "The default value of observed=False is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + pivot_tab = pivot_table( + df, index="C", columns="B", values="A", aggfunc="sum", margins=True + ) result = pivot_tab["All"] expected = Series( @@ -1827,7 +1840,9 @@ def test_categorical_margins_category(self, observed): df.y = df.y.astype("category") df.z = df.z.astype("category") - table = df.pivot_table("x", "y", "z", dropna=observed, margins=True) + msg = "The default value of observed=False is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + table = df.pivot_table("x", "y", "z", dropna=observed, margins=True) tm.assert_frame_equal(table, expected) def test_margins_casted_to_float(self): @@ -1889,9 +1904,11 @@ def test_categorical_aggfunc(self, observed): {"C1": ["A", "B", "C", "C"], "C2": ["a", "a", "b", "b"], "V": [1, 2, 3, 4]} ) df["C1"] = df["C1"].astype("category") - result = df.pivot_table( - "V", index="C1", columns="C2", dropna=observed, aggfunc="count" - ) + msg = "The default value of observed=False is deprecated" + with tm.assert_produces_warning(FutureWarning, match=msg): + result = df.pivot_table( + "V", index="C1", columns="C2", dropna=observed, aggfunc="count" + ) expected_index = pd.CategoricalIndex( ["A", "B", "C"], categories=["A", "B", "C"], ordered=False, name="C1"
- [x] closes #56236 (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/56237
2023-11-29T04:17:59Z
2023-12-04T18:27:36Z
2023-12-04T18:27:35Z
2023-12-04T23:38:37Z
DOC: Fix typo in copy_on_write docs
diff --git a/doc/source/user_guide/copy_on_write.rst b/doc/source/user_guide/copy_on_write.rst index 9dbc46ca2db0e..fb0da70a0ea07 100644 --- a/doc/source/user_guide/copy_on_write.rst +++ b/doc/source/user_guide/copy_on_write.rst @@ -26,7 +26,7 @@ Previous behavior ----------------- pandas indexing behavior is tricky to understand. Some operations return views while -other return copies. Depending on the result of the operation, mutation one object +other return copies. Depending on the result of the operation, mutating one object might accidentally mutate another: .. ipython:: python
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/56234
2023-11-29T01:47:11Z
2023-11-29T17:51:27Z
2023-11-29T17:51:27Z
2023-11-29T17:51:34Z
DOC: Update release instructions
diff --git a/doc/source/development/maintaining.rst b/doc/source/development/maintaining.rst index 29cc256f35a4e..c7803d8401e4e 100644 --- a/doc/source/development/maintaining.rst +++ b/doc/source/development/maintaining.rst @@ -449,9 +449,13 @@ which will be triggered when the tag is pushed. git tag -a v1.5.0.dev0 -m "DEV: Start 1.5.0" git push upstream main --follow-tags -3. Build the source distribution (git must be in the tag commit):: +3. Download the source distribution and wheels from the `wheel staging area <https://anaconda.org/scientific-python-nightly-wheels/pandas>`_. + Be careful to make sure that no wheels are missing (e.g. due to failed builds). - ./setup.py sdist --formats=gztar --quiet + Running scripts/download_wheels.sh with the version that you want to download wheels/the sdist for should do the trick. + This script will make a ``dist`` folder inside your clone of pandas and put the downloaded wheels and sdist there:: + + scripts/download_wheels.sh <VERSION> 4. Create a `new GitHub release <https://github.com/pandas-dev/pandas/releases/new>`_: @@ -463,23 +467,19 @@ which will be triggered when the tag is pushed. - Set as the latest release: Leave checked, unless releasing a patch release for an older version (e.g. releasing 1.4.5 after 1.5 has been released) -5. The GitHub release will after some hours trigger an +5. Upload wheels to PyPI:: + + twine upload pandas/dist/pandas-<version>*.{whl,tar.gz} --skip-existing + +6. The GitHub release will after some hours trigger an `automated conda-forge PR <https://github.com/conda-forge/pandas-feedstock/pulls>`_. + (If you don't want to wait, you can open an issue titled ``@conda-forge-admin, please update version`` to trigger the bot.) Merge it once the CI is green, and it will generate the conda-forge packages. + In case a manual PR needs to be done, the version, sha256 and build fields are the ones that usually need to be changed. If anything else in the recipe has changed since the last release, those changes should be available in ``ci/meta.yaml``. -6. Packages for supported versions in PyPI are built automatically from our CI. - Once all packages are build download all wheels from the - `Anaconda repository <https://anaconda.org/multibuild-wheels-staging/pandas/files?version=\<version\>>`_ - where our CI published them to the ``dist/`` directory in your local pandas copy. - You can use the script ``scripts/download_wheels.sh`` to download all wheels at once. - -7. Upload wheels to PyPI:: - - twine upload pandas/dist/pandas-<version>*.{whl,tar.gz} --skip-existing - Post-Release ```````````` diff --git a/scripts/download_wheels.sh b/scripts/download_wheels.sh index 0b92e83113f5f..84279ac7a04d1 100755 --- a/scripts/download_wheels.sh +++ b/scripts/download_wheels.sh @@ -11,6 +11,7 @@ # one by one to the dist/ directory where they would be generated. VERSION=$1 +mkdir -p $(dirname -- $0)/../dist DIST_DIR="$(realpath $(dirname -- $0)/../dist)" if [ -z $VERSION ]; then @@ -20,7 +21,7 @@ fi curl "https://anaconda.org/multibuild-wheels-staging/pandas/files?version=${VERSION}" | \ grep "href=\"/multibuild-wheels-staging/pandas/${VERSION}" | \ - sed -r 's/.*<a href="([^"]+\.whl)">.*/\1/g' | \ + sed -r 's/.*<a href="([^"]+\.(whl|tar.gz))">.*/\1/g' | \ awk '{print "https://anaconda.org" $0 }' | \ xargs wget -P $DIST_DIR
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/56232
2023-11-28T22:57:04Z
2023-11-29T17:43:03Z
2023-11-29T17:43:03Z
2023-12-18T16:26:09Z
CoW warning mode: enable chained assignment warning for DataFrame setitem in default mode
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 008c1e0d10ba4..847f514451add 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4230,15 +4230,14 @@ def __setitem__(self, key, value) -> None: warnings.warn( _chained_assignment_msg, ChainedAssignmentError, stacklevel=2 ) - # elif not PYPY and not using_copy_on_write(): - elif not PYPY and warn_copy_on_write(): - if sys.getrefcount(self) <= 3: # and ( - # warn_copy_on_write() - # or ( - # not warn_copy_on_write() - # and self._mgr.blocks[0].refs.has_reference() - # ) - # ): + elif not PYPY and not using_copy_on_write(): + if sys.getrefcount(self) <= 3 and ( + warn_copy_on_write() + or ( + not warn_copy_on_write() + and any(b.refs.has_reference() for b in self._mgr.blocks) # type: ignore[union-attr] + ) + ): warnings.warn( _chained_assignment_warning_msg, FutureWarning, stacklevel=2 ) diff --git a/pandas/tests/copy_view/test_chained_assignment_deprecation.py b/pandas/tests/copy_view/test_chained_assignment_deprecation.py index 7b08d9b80fc9b..32d0f55f67185 100644 --- a/pandas/tests/copy_view/test_chained_assignment_deprecation.py +++ b/pandas/tests/copy_view/test_chained_assignment_deprecation.py @@ -1,9 +1,15 @@ import numpy as np import pytest -from pandas.errors import ChainedAssignmentError +from pandas.errors import ( + ChainedAssignmentError, + SettingWithCopyWarning, +) -from pandas import DataFrame +from pandas import ( + DataFrame, + option_context, +) import pandas._testing as tm @@ -85,3 +91,17 @@ def test_series_setitem(indexer, using_copy_on_write): else: assert record[0].category == FutureWarning assert "ChainedAssignmentError" in record[0].message.args[0] + + +@pytest.mark.filterwarnings("ignore::pandas.errors.SettingWithCopyWarning") +@pytest.mark.parametrize( + "indexer", ["a", ["a", "b"], slice(0, 2), np.array([True, False, True])] +) +def test_frame_setitem(indexer, using_copy_on_write): + df = DataFrame({"a": [1, 2, 3, 4, 5], "b": 1}) + + extra_warnings = () if using_copy_on_write else (SettingWithCopyWarning,) + + with option_context("chained_assignment", "warn"): + with tm.raises_chained_assignment_error(extra_warnings=extra_warnings): + df[0:3][indexer] = 10 diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py index e613f1102b03b..53ad4d6b41687 100644 --- a/pandas/tests/indexing/multiindex/test_setitem.py +++ b/pandas/tests/indexing/multiindex/test_setitem.py @@ -548,7 +548,8 @@ def test_frame_setitem_copy_raises( else: msg = "A value is trying to be set on a copy of a slice from a DataFrame" with pytest.raises(SettingWithCopyError, match=msg): - df["foo"]["one"] = 2 + with tm.raises_chained_assignment_error(): + df["foo"]["one"] = 2 def test_frame_setitem_copy_no_write( @@ -563,7 +564,8 @@ def test_frame_setitem_copy_no_write( else: msg = "A value is trying to be set on a copy of a slice from a DataFrame" with pytest.raises(SettingWithCopyError, match=msg): - df["foo"]["one"] = 2 + with tm.raises_chained_assignment_error(): + df["foo"]["one"] = 2 result = df tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index 230c575e6ed10..88cac9b16f8f7 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -452,7 +452,8 @@ def test_detect_chained_assignment_undefined_column( df.iloc[0:5]["group"] = "a" else: with pytest.raises(SettingWithCopyError, match=msg): - df.iloc[0:5]["group"] = "a" + with tm.raises_chained_assignment_error(): + df.iloc[0:5]["group"] = "a" @pytest.mark.arm_slow def test_detect_chained_assignment_changing_dtype(
Follow-up on https://github.com/pandas-dev/pandas/pull/55522#discussion_r1406831714 This ensures the chained assignment warning is shown in the default mode as well. This does mean you currently get some noise cases of both this new warning and the existing SettingWithCopyWarning. But either this SettingWithCopy was a false positive and it was setting on a view (eg a far-fetched case like `df[0:3][0:2] = 10`), and then we really need to have the new warning as well because it will change behaviour. Or either it was a correct warning (e.g. `df[mask][other_indexer] = ..`, and in that case this has never been working, and adding an additional warning for a case that never works does no harm (and so a user can only have by accident, or potentially unaware it doesn't do what they intend). xref https://github.com/pandas-dev/pandas/issues/56019
https://api.github.com/repos/pandas-dev/pandas/pulls/56230
2023-11-28T19:15:08Z
2023-12-04T08:29:32Z
2023-12-04T08:29:32Z
2023-12-04T08:29:50Z
TST/CLN: Remove makeFloat/Period/Int/NumericIndex
diff --git a/asv_bench/benchmarks/arithmetic.py b/asv_bench/benchmarks/arithmetic.py index d70ad144a3455..5e23cba2e1074 100644 --- a/asv_bench/benchmarks/arithmetic.py +++ b/asv_bench/benchmarks/arithmetic.py @@ -6,12 +6,12 @@ import pandas as pd from pandas import ( DataFrame, + Index, Series, Timestamp, date_range, to_timedelta, ) -import pandas._testing as tm from pandas.core.algorithms import checked_add_with_arr from .pandas_vb_common import numeric_dtypes @@ -323,8 +323,10 @@ class IndexArithmetic: def setup(self, dtype): N = 10**6 - indexes = {"int": "makeIntIndex", "float": "makeFloatIndex"} - self.index = getattr(tm, indexes[dtype])(N) + if dtype == "float": + self.index = Index(np.arange(N), dtype=np.float64) + elif dtype == "int": + self.index = Index(np.arange(N), dtype=np.int64) def time_add(self, dtype): self.index + 2 diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index b58a8f706e5a6..b1918e1b1d7c2 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -27,12 +27,8 @@ from pandas.compat import pa_version_under10p1 from pandas.core.dtypes.common import ( - is_float_dtype, is_sequence, - is_signed_integer_dtype, is_string_dtype, - is_unsigned_integer_dtype, - pandas_dtype, ) import pandas as pd @@ -46,6 +42,8 @@ RangeIndex, Series, bdate_range, + date_range, + period_range, timedelta_range, ) from pandas._testing._io import ( @@ -111,7 +109,6 @@ NpDtype, ) - from pandas import PeriodIndex from pandas.core.arrays import ArrowExtensionArray _N = 30 @@ -351,38 +348,6 @@ def getCols(k) -> str: return string.ascii_uppercase[:k] -def makeNumericIndex(k: int = 10, *, name=None, dtype: Dtype | None) -> Index: - dtype = pandas_dtype(dtype) - assert isinstance(dtype, np.dtype) - - if dtype.kind in "iu": - values = np.arange(k, dtype=dtype) - if is_unsigned_integer_dtype(dtype): - values += 2 ** (dtype.itemsize * 8 - 1) - elif dtype.kind == "f": - values = np.random.default_rng(2).random(k) - np.random.default_rng(2).random(1) - values.sort() - values = values * (10 ** np.random.default_rng(2).integers(0, 9)) - else: - raise NotImplementedError(f"wrong dtype {dtype}") - - return Index(values, dtype=dtype, name=name) - - -def makeIntIndex(k: int = 10, *, name=None, dtype: Dtype = "int64") -> Index: - dtype = pandas_dtype(dtype) - if not is_signed_integer_dtype(dtype): - raise TypeError(f"Wrong dtype {dtype}") - return makeNumericIndex(k, name=name, dtype=dtype) - - -def makeFloatIndex(k: int = 10, *, name=None, dtype: Dtype = "float64") -> Index: - dtype = pandas_dtype(dtype) - if not is_float_dtype(dtype): - raise TypeError(f"Wrong dtype {dtype}") - return makeNumericIndex(k, name=name, dtype=dtype) - - def makeDateIndex( k: int = 10, freq: Frequency = "B", name=None, **kwargs ) -> DatetimeIndex: @@ -391,12 +356,6 @@ def makeDateIndex( return DatetimeIndex(dr, name=name, **kwargs) -def makePeriodIndex(k: int = 10, name=None, **kwargs) -> PeriodIndex: - dt = datetime(2000, 1, 1) - pi = pd.period_range(start=dt, periods=k, freq="D", name=name, **kwargs) - return pi - - def makeObjectSeries(name=None) -> Series: data = [f"foo_{i}" for i in range(_N)] index = Index([f"bar_{i}" for i in range(_N)]) @@ -487,12 +446,12 @@ def makeCustomIndex( # specific 1D index type requested? idx_func_dict: dict[str, Callable[..., Index]] = { - "i": makeIntIndex, - "f": makeFloatIndex, + "i": lambda n: Index(np.arange(n), dtype=np.int64), + "f": lambda n: Index(np.arange(n), dtype=np.float64), "s": lambda n: Index([f"{i}_{chr(i)}" for i in range(97, 97 + n)]), - "dt": makeDateIndex, + "dt": lambda n: date_range("2020-01-01", periods=n), "td": lambda n: timedelta_range("1 day", periods=n), - "p": makePeriodIndex, + "p": lambda n: period_range("2020-01-01", periods=n, freq="D"), } idx_func = idx_func_dict.get(idx_type) if idx_func: @@ -975,11 +934,7 @@ def shares_memory(left, right) -> bool: "makeCustomIndex", "makeDataFrame", "makeDateIndex", - "makeFloatIndex", - "makeIntIndex", - "makeNumericIndex", "makeObjectSeries", - "makePeriodIndex", "makeTimeDataFrame", "makeTimeSeries", "maybe_produces_warning", diff --git a/pandas/conftest.py b/pandas/conftest.py index 1dae6d0043b61..1bc067eb32aef 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -68,6 +68,7 @@ Series, Timedelta, Timestamp, + period_range, timedelta_range, ) import pandas._testing as tm @@ -616,23 +617,27 @@ def _create_mi_with_dt64tz_level(): "string": Index([f"pandas_{i}" for i in range(100)]), "datetime": tm.makeDateIndex(100), "datetime-tz": tm.makeDateIndex(100, tz="US/Pacific"), - "period": tm.makePeriodIndex(100), + "period": period_range("2020-01-01", periods=100, freq="D"), "timedelta": timedelta_range(start="1 day", periods=100, freq="D"), "range": RangeIndex(100), - "int8": tm.makeIntIndex(100, dtype="int8"), - "int16": tm.makeIntIndex(100, dtype="int16"), - "int32": tm.makeIntIndex(100, dtype="int32"), - "int64": tm.makeIntIndex(100, dtype="int64"), + "int8": Index(np.arange(100), dtype="int8"), + "int16": Index(np.arange(100), dtype="int16"), + "int32": Index(np.arange(100), dtype="int32"), + "int64": Index(np.arange(100), dtype="int64"), "uint8": Index(np.arange(100), dtype="uint8"), "uint16": Index(np.arange(100), dtype="uint16"), "uint32": Index(np.arange(100), dtype="uint32"), "uint64": Index(np.arange(100), dtype="uint64"), - "float32": tm.makeFloatIndex(100, dtype="float32"), - "float64": tm.makeFloatIndex(100, dtype="float64"), + "float32": Index(np.arange(100), dtype="float32"), + "float64": Index(np.arange(100), dtype="float64"), "bool-object": Index([True, False] * 5, dtype=object), "bool-dtype": Index(np.random.default_rng(2).standard_normal(10) < 0), - "complex64": tm.makeNumericIndex(100, dtype="float64").astype("complex64"), - "complex128": tm.makeNumericIndex(100, dtype="float64").astype("complex128"), + "complex64": Index( + np.arange(100, dtype="complex64") + 1.0j * np.arange(100, dtype="complex64") + ), + "complex128": Index( + np.arange(100, dtype="complex128") + 1.0j * np.arange(100, dtype="complex128") + ), "categorical": CategoricalIndex(list("abcd") * 25), "interval": IntervalIndex.from_breaks(np.linspace(0, 100, num=101)), "empty": Index([]), diff --git a/pandas/tests/extension/test_masked.py b/pandas/tests/extension/test_masked.py index a5e8b2ed1efe5..be4077d921a9e 100644 --- a/pandas/tests/extension/test_masked.py +++ b/pandas/tests/extension/test_masked.py @@ -24,6 +24,12 @@ ) from pandas.compat.numpy import np_version_gt2 +from pandas.core.dtypes.common import ( + is_float_dtype, + is_signed_integer_dtype, + is_unsigned_integer_dtype, +) + import pandas as pd import pandas._testing as tm from pandas.core.arrays.boolean import BooleanDtype @@ -281,7 +287,7 @@ def check_reduce(self, ser: pd.Series, op_name: str, skipna: bool): tm.assert_almost_equal(result, expected) def _get_expected_reduction_dtype(self, arr, op_name: str, skipna: bool): - if tm.is_float_dtype(arr.dtype): + if is_float_dtype(arr.dtype): cmp_dtype = arr.dtype.name elif op_name in ["mean", "median", "var", "std", "skew"]: cmp_dtype = "Float64" @@ -289,7 +295,7 @@ def _get_expected_reduction_dtype(self, arr, op_name: str, skipna: bool): cmp_dtype = arr.dtype.name elif arr.dtype in ["Int64", "UInt64"]: cmp_dtype = arr.dtype.name - elif tm.is_signed_integer_dtype(arr.dtype): + elif is_signed_integer_dtype(arr.dtype): # TODO: Why does Window Numpy 2.0 dtype depend on skipna? cmp_dtype = ( "Int32" @@ -297,7 +303,7 @@ def _get_expected_reduction_dtype(self, arr, op_name: str, skipna: bool): or not IS64 else "Int64" ) - elif tm.is_unsigned_integer_dtype(arr.dtype): + elif is_unsigned_integer_dtype(arr.dtype): cmp_dtype = ( "UInt32" if (is_platform_windows() and (not np_version_gt2 or not skipna)) diff --git a/pandas/tests/indexes/interval/test_constructors.py b/pandas/tests/indexes/interval/test_constructors.py index 078a0e06e0ed7..778c07b46e57c 100644 --- a/pandas/tests/indexes/interval/test_constructors.py +++ b/pandas/tests/indexes/interval/test_constructors.py @@ -3,6 +3,7 @@ import numpy as np import pytest +from pandas.core.dtypes.common import is_unsigned_integer_dtype from pandas.core.dtypes.dtypes import IntervalDtype from pandas import ( @@ -330,7 +331,7 @@ def get_kwargs_from_breaks(self, breaks, closed="right"): converts intervals in breaks format to a dictionary of kwargs to specific to the format expected by IntervalIndex.from_tuples """ - if tm.is_unsigned_integer_dtype(breaks): + if is_unsigned_integer_dtype(breaks): pytest.skip(f"{breaks.dtype} not relevant IntervalIndex.from_tuples tests") if len(breaks) == 0: @@ -388,7 +389,7 @@ def get_kwargs_from_breaks(self, breaks, closed="right"): converts intervals in breaks format to a dictionary of kwargs to specific to the format expected by the IntervalIndex/Index constructors """ - if tm.is_unsigned_integer_dtype(breaks): + if is_unsigned_integer_dtype(breaks): pytest.skip(f"{breaks.dtype} not relevant for class constructor tests") if len(breaks) == 0: diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 662f31cc3560e..3db81c0285bd2 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -507,8 +507,8 @@ def test_map_with_tuples(self): # Test that returning a single tuple from an Index # returns an Index. - index = tm.makeIntIndex(3) - result = tm.makeIntIndex(3).map(lambda x: (x,)) + index = Index(np.arange(3), dtype=np.int64) + result = index.map(lambda x: (x,)) expected = Index([(i,) for i in index]) tm.assert_index_equal(result, expected) @@ -555,7 +555,7 @@ def test_map_tseries_indices_accsr_return_index(self): def test_map_dictlike_simple(self, mapper): # GH 12756 expected = Index(["foo", "bar", "baz"]) - index = tm.makeIntIndex(3) + index = Index(np.arange(3), dtype=np.int64) result = index.map(mapper(expected.values, index)) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/io/pytables/test_time_series.py b/pandas/tests/io/pytables/test_time_series.py index cfe25f03e1aab..4afcf5600dce6 100644 --- a/pandas/tests/io/pytables/test_time_series.py +++ b/pandas/tests/io/pytables/test_time_series.py @@ -8,6 +8,7 @@ DatetimeIndex, Series, _testing as tm, + period_range, ) from pandas.tests.io.pytables.common import ensure_clean_store @@ -36,7 +37,7 @@ def test_tseries_indices_series(setup_path): assert result.index.freq == ser.index.freq tm.assert_class_equal(result.index, ser.index, obj="series index") - idx = tm.makePeriodIndex(10) + idx = period_range("2020-01-01", periods=10, freq="D") ser = Series(np.random.default_rng(2).standard_normal(len(idx)), idx) store["a"] = ser result = store["a"] @@ -60,7 +61,7 @@ def test_tseries_indices_frame(setup_path): assert result.index.freq == df.index.freq tm.assert_class_equal(result.index, df.index, obj="dataframe index") - idx = tm.makePeriodIndex(10) + idx = period_range("2020-01-01", periods=10, freq="D") df = DataFrame(np.random.default_rng(2).standard_normal((len(idx), 3)), idx) store["a"] = df result = store["a"] diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index 303f8550c5a80..ccfa3be702dae 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -23,6 +23,7 @@ Timestamp, date_range, isna, + period_range, timedelta_range, to_timedelta, ) @@ -34,11 +35,13 @@ def get_objs(): indexes = [ Index([True, False] * 5, name="a"), - tm.makeIntIndex(10, name="a"), - tm.makeFloatIndex(10, name="a"), - tm.makeDateIndex(10, name="a"), - tm.makeDateIndex(10, name="a").tz_localize(tz="US/Eastern"), - tm.makePeriodIndex(10, name="a"), + Index(np.arange(10), dtype=np.int64, name="a"), + Index(np.arange(10), dtype=np.float64, name="a"), + DatetimeIndex(date_range("2020-01-01", periods=10), name="a"), + DatetimeIndex(date_range("2020-01-01", periods=10), name="a").tz_localize( + tz="US/Eastern" + ), + PeriodIndex(period_range("2020-01-01", periods=10, freq="D"), name="a"), Index([str(i) for i in range(10)], name="a"), ] @@ -534,7 +537,7 @@ def test_minmax_period_empty_nat(self, op, data): assert result is NaT def test_numpy_minmax_period(self): - pr = pd.period_range(start="2016-01-15", end="2016-01-20") + pr = period_range(start="2016-01-15", end="2016-01-20") assert np.min(pr) == Period("2016-01-15", freq="D") assert np.max(pr) == Period("2016-01-20", freq="D") diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 0f3577a214186..cac7bd6de9d3b 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -237,7 +237,9 @@ def test_setitem_slice_integers(self): def test_setitem_slicestep(self): # caught this bug when writing tests - series = Series(tm.makeIntIndex(20).astype(float), index=tm.makeIntIndex(20)) + series = Series( + np.arange(20, dtype=np.float64), index=np.arange(20, dtype=np.int64) + ) series[::2] = 0 assert (series[::2] == 0).all() diff --git a/pandas/tests/series/methods/test_combine_first.py b/pandas/tests/series/methods/test_combine_first.py index 1cbb7c7982802..e1ec8afda33a9 100644 --- a/pandas/tests/series/methods/test_combine_first.py +++ b/pandas/tests/series/methods/test_combine_first.py @@ -32,8 +32,8 @@ def test_combine_first_name(self, datetime_series): assert result.name == datetime_series.name def test_combine_first(self): - values = tm.makeIntIndex(20).values.astype(float) - series = Series(values, index=tm.makeIntIndex(20)) + values = np.arange(20, dtype=np.float64) + series = Series(values, index=np.arange(20, dtype=np.int64)) series_copy = series * 2 series_copy[::2] = np.nan diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index e23302b58b197..29d6e2036476e 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -10,6 +10,7 @@ Index, Series, date_range, + period_range, timedelta_range, ) import pandas._testing as tm @@ -72,13 +73,12 @@ def test_tab_completion_with_categorical(self): Index(list("ab") * 5, dtype="category"), Index([str(i) for i in range(10)]), Index(["foo", "bar", "baz"] * 2), - tm.makeDateIndex(10), - tm.makePeriodIndex(10), + date_range("2020-01-01", periods=10), + period_range("2020-01-01", periods=10, freq="D"), timedelta_range("1 day", periods=10), - tm.makeIntIndex(10), Index(np.arange(10), dtype=np.uint64), - tm.makeIntIndex(10), - tm.makeFloatIndex(10), + Index(np.arange(10), dtype=np.int64), + Index(np.arange(10), dtype=np.float64), Index([True, False]), Index([f"a{i}" for i in range(101)]), pd.MultiIndex.from_tuples(zip("ABCD", "EFGH")), diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 972d403fff997..e08f8d0c15f39 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1337,7 +1337,7 @@ def test_constructor_dict(self): expected = Series([1, 2, np.nan, 0], index=["b", "c", "d", "a"]) tm.assert_series_equal(result, expected) - pidx = tm.makePeriodIndex(100) + pidx = period_range("2020-01-01", periods=10, freq="D") d = {pidx[0]: 0, pidx[1]: 1} result = Series(d, index=pidx) expected = Series(np.nan, pidx, dtype=np.float64) diff --git a/pandas/tests/util/test_hashing.py b/pandas/tests/util/test_hashing.py index 0417c7a631da2..4fa256a6b8630 100644 --- a/pandas/tests/util/test_hashing.py +++ b/pandas/tests/util/test_hashing.py @@ -148,7 +148,7 @@ def test_multiindex_objects(): ), tm.makeTimeDataFrame(), tm.makeTimeSeries(), - Series(tm.makePeriodIndex()), + Series(period_range("2020-01-01", periods=10, freq="D")), Series(pd.date_range("20130101", periods=3, tz="US/Eastern")), ], ) @@ -181,7 +181,7 @@ def test_hash_pandas_object(obj, index): ), tm.makeTimeDataFrame(), tm.makeTimeSeries(), - Series(tm.makePeriodIndex()), + Series(period_range("2020-01-01", periods=10, freq="D")), Series(pd.date_range("20130101", periods=3, tz="US/Eastern")), ], )
null
https://api.github.com/repos/pandas-dev/pandas/pulls/56229
2023-11-28T17:45:42Z
2023-11-29T17:51:55Z
2023-11-29T17:51:55Z
2023-11-29T17:51:59Z
BUG: DataFrame.update not operating in-place for datetime64[ns, UTC] dtype
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index dce776755ad7e..90566f62bfdaf 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -520,7 +520,7 @@ Indexing Missing ^^^^^^^ -- +- Bug in :meth:`DataFrame.update` wasn't updating in-place for tz-aware datetime64 dtypes (:issue:`56227`) - MultiIndex diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5d05983529fba..3931616d49baf 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8838,14 +8838,14 @@ def update( in the original dataframe. >>> df = pd.DataFrame({'A': [1, 2, 3], - ... 'B': [400, 500, 600]}) + ... 'B': [400., 500., 600.]}) >>> new_df = pd.DataFrame({'B': [4, np.nan, 6]}) >>> df.update(new_df) >>> df - A B - 0 1 4 - 1 2 500 - 2 3 6 + A B + 0 1 4.0 + 1 2 500.0 + 2 3 6.0 """ if not PYPY and using_copy_on_write(): if sys.getrefcount(self) <= REF_COUNT: @@ -8862,8 +8862,6 @@ def update( stacklevel=2, ) - from pandas.core.computation import expressions - # TODO: Support other joins if join != "left": # pragma: no cover raise NotImplementedError("Only left join is supported") @@ -8897,7 +8895,7 @@ def update( if mask.all(): continue - self.loc[:, col] = expressions.where(mask, this, that) + self.loc[:, col] = self[col].where(mask, that) # ---------------------------------------------------------------------- # Data reshaping diff --git a/pandas/tests/frame/methods/test_update.py b/pandas/tests/frame/methods/test_update.py index 0d32788b04b03..c79a37b5b30f0 100644 --- a/pandas/tests/frame/methods/test_update.py +++ b/pandas/tests/frame/methods/test_update.py @@ -140,6 +140,22 @@ def test_update_datetime_tz(self): expected = DataFrame([pd.Timestamp("2019", tz="UTC")]) tm.assert_frame_equal(result, expected) + def test_update_datetime_tz_in_place(self, using_copy_on_write, warn_copy_on_write): + # https://github.com/pandas-dev/pandas/issues/56227 + result = DataFrame([pd.Timestamp("2019", tz="UTC")]) + orig = result.copy() + view = result[:] + with tm.assert_produces_warning( + FutureWarning if warn_copy_on_write else None, match="Setting a value" + ): + result.update(result + pd.Timedelta(days=1)) + expected = DataFrame([pd.Timestamp("2019-01-02", tz="UTC")]) + tm.assert_frame_equal(result, expected) + if not using_copy_on_write: + tm.assert_frame_equal(view, expected) + else: + tm.assert_frame_equal(view, orig) + def test_update_with_different_dtype(self, using_copy_on_write): # GH#3217 df = DataFrame({"a": [1, 3], "b": [np.nan, 2]})
- [ ] closes #56227 (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/56228
2023-11-28T17:41:32Z
2023-11-29T18:00:48Z
2023-11-29T18:00:48Z
2023-12-01T12:01:27Z
Backport PR #56222 on branch 2.1.x (Add doc notes for deprecations)
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 3281d245dca56..564d572254f8d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9456,6 +9456,10 @@ def first(self, offset) -> Self: """ Select initial periods of time series data based on a date offset. + .. deprecated:: 2.1 + :meth:`.first` is deprecated and will be removed in a future version. + Please create a mask and filter using `.loc` instead. + For a DataFrame with a sorted DatetimeIndex, this function can select the first few rows based on a date offset. @@ -9535,6 +9539,10 @@ def last(self, offset) -> Self: """ Select final periods of time series data based on a date offset. + .. deprecated:: 2.1 + :meth:`.last` is deprecated and will be removed in a future version. + Please create a mask and filter using `.loc` instead. + For a DataFrame with a sorted DatetimeIndex, this function selects the last few rows based on a date offset.
Backport PR #56222: Add doc notes for deprecations
https://api.github.com/repos/pandas-dev/pandas/pulls/56225
2023-11-28T15:48:27Z
2023-11-28T17:07:52Z
2023-11-28T17:07:52Z
2023-11-28T17:07:53Z
Add doc notes for deprecations
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 56001fabfdc9d..579d66be994e6 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9661,6 +9661,10 @@ def first(self, offset) -> Self: """ Select initial periods of time series data based on a date offset. + .. deprecated:: 2.1 + :meth:`.first` is deprecated and will be removed in a future version. + Please create a mask and filter using `.loc` instead. + For a DataFrame with a sorted DatetimeIndex, this function can select the first few rows based on a date offset. @@ -9740,6 +9744,10 @@ def last(self, offset) -> Self: """ Select final periods of time series data based on a date offset. + .. deprecated:: 2.1 + :meth:`.last` is deprecated and will be removed in a future version. + Please create a mask and filter using `.loc` instead. + For a DataFrame with a sorted DatetimeIndex, this function selects the last few rows based on a date offset.
We should probably back port
https://api.github.com/repos/pandas-dev/pandas/pulls/56222
2023-11-28T14:05:17Z
2023-11-28T15:47:18Z
2023-11-28T15:47:18Z
2023-11-28T15:53:33Z
Switch arrow type for string array to large string
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index 70039cc697b8a..e0aa4d1306c95 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -236,6 +236,8 @@ Other enhancements - Implemented :meth:`Series.str.extract` for :class:`ArrowDtype` (:issue:`56268`) - Improved error message that appears in :meth:`DatetimeIndex.to_period` with frequencies which are not supported as period frequencies, such as "BMS" (:issue:`56243`) - Improved error message when constructing :class:`Period` with invalid offsets such as "QS" (:issue:`55785`) +- The dtypes ``string[pyarrow]`` and ``string[pyarrow_numpy]`` now both utilize the ``large_string`` type from PyArrow to avoid overflow for long columns (:issue:`56259`) + .. --------------------------------------------------------------------------- .. _whatsnew_220.notable_bug_fixes: diff --git a/pandas/core/arrays/arrow/array.py b/pandas/core/arrays/arrow/array.py index 633efe43fce1a..d7bec102c43ca 100644 --- a/pandas/core/arrays/arrow/array.py +++ b/pandas/core/arrays/arrow/array.py @@ -291,6 +291,7 @@ def _from_sequence_of_strings( pa_type is None or pa.types.is_binary(pa_type) or pa.types.is_string(pa_type) + or pa.types.is_large_string(pa_type) ): # pa_type is None: Let pa.array infer # pa_type is string/binary: scalars already correct type @@ -632,7 +633,9 @@ def __invert__(self) -> Self: # This is a bit wise op for integer types if pa.types.is_integer(self._pa_array.type): return type(self)(pc.bit_wise_not(self._pa_array)) - elif pa.types.is_string(self._pa_array.type): + elif pa.types.is_string(self._pa_array.type) or pa.types.is_large_string( + self._pa_array.type + ): # Raise TypeError instead of pa.ArrowNotImplementedError raise TypeError("__invert__ is not supported for string dtypes") else: @@ -692,7 +695,11 @@ def _evaluate_op_method(self, other, op, arrow_funcs): pa_type = self._pa_array.type other = self._box_pa(other) - if pa.types.is_string(pa_type) or pa.types.is_binary(pa_type): + if ( + pa.types.is_string(pa_type) + or pa.types.is_large_string(pa_type) + or pa.types.is_binary(pa_type) + ): if op in [operator.add, roperator.radd]: sep = pa.scalar("", type=pa_type) if op is operator.add: @@ -709,7 +716,9 @@ def _evaluate_op_method(self, other, op, arrow_funcs): result = pc.binary_repeat(binary, pa_integral) return type(self)(result) elif ( - pa.types.is_string(other.type) or pa.types.is_binary(other.type) + pa.types.is_string(other.type) + or pa.types.is_binary(other.type) + or pa.types.is_large_string(other.type) ) and op in [operator.mul, roperator.rmul]: binary = other integral = self._pa_array @@ -1471,7 +1480,7 @@ def _concat_same_type(cls, to_concat) -> Self: chunks = [array for ea in to_concat for array in ea._pa_array.iterchunks()] if to_concat[0].dtype == "string": # StringDtype has no attribute pyarrow_dtype - pa_dtype = pa.string() + pa_dtype = pa.large_string() else: pa_dtype = to_concat[0].dtype.pyarrow_dtype arr = pa.chunked_array(chunks, type=pa_dtype) @@ -2253,7 +2262,9 @@ def _str_find(self, sub: str, start: int = 0, end: int | None = None): return type(self)(result) def _str_join(self, sep: str): - if pa.types.is_string(self._pa_array.type): + if pa.types.is_string(self._pa_array.type) or pa.types.is_large_string( + self._pa_array.type + ): result = self._apply_elementwise(list) result = pa.chunked_array(result, type=pa.list_(pa.string())) else: diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index 32ab3054c0f51..56732619a2d29 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -126,17 +126,40 @@ class ArrowStringArray(ObjectStringArrayMixin, ArrowExtensionArray, BaseStringAr _storage = "pyarrow" def __init__(self, values) -> None: + _chk_pyarrow_available() + if isinstance(values, (pa.Array, pa.ChunkedArray)) and pa.types.is_string( + values.type + ): + values = pc.cast(values, pa.large_string()) + super().__init__(values) self._dtype = StringDtype(storage=self._storage) - if not pa.types.is_string(self._pa_array.type) and not ( + if not pa.types.is_large_string(self._pa_array.type) and not ( pa.types.is_dictionary(self._pa_array.type) - and pa.types.is_string(self._pa_array.type.value_type) + and pa.types.is_large_string(self._pa_array.type.value_type) ): raise ValueError( - "ArrowStringArray requires a PyArrow (chunked) array of string type" + "ArrowStringArray requires a PyArrow (chunked) array of " + "large_string type" ) + @classmethod + def _box_pa_scalar(cls, value, pa_type: pa.DataType | None = None) -> pa.Scalar: + pa_scalar = super()._box_pa_scalar(value, pa_type) + if pa.types.is_string(pa_scalar.type) and pa_type is None: + pa_scalar = pc.cast(pa_scalar, pa.large_string()) + return pa_scalar + + @classmethod + def _box_pa_array( + cls, value, pa_type: pa.DataType | None = None, copy: bool = False + ) -> pa.Array | pa.ChunkedArray: + pa_array = super()._box_pa_array(value, pa_type) + if pa.types.is_string(pa_array.type) and pa_type is None: + pa_array = pc.cast(pa_array, pa.large_string()) + return pa_array + def __len__(self) -> int: """ Length of this array. @@ -574,15 +597,6 @@ def _rank( class ArrowStringArrayNumpySemantics(ArrowStringArray): _storage = "pyarrow_numpy" - def __init__(self, values) -> None: - _chk_pyarrow_available() - - if isinstance(values, (pa.Array, pa.ChunkedArray)) and pa.types.is_large_string( - values.type - ): - values = pc.cast(values, pa.string()) - super().__init__(values) - @classmethod def _result_converter(cls, values, na=None): if not isna(na): diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 12118d1488932..b0fa6bc6e90c4 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -172,9 +172,17 @@ def _convert_arrays_to_dataframe( ) if dtype_backend == "pyarrow": pa = import_optional_dependency("pyarrow") - arrays = [ - ArrowExtensionArray(pa.array(arr, from_pandas=True)) for arr in arrays - ] + + result_arrays = [] + for arr in arrays: + pa_array = pa.array(arr, from_pandas=True) + if arr.dtype == "string": + # TODO: Arrow still infers strings arrays as regular strings instead + # of large_string, which is what we preserver everywhere else for + # dtype_backend="pyarrow". We may want to reconsider this + pa_array = pa_array.cast(pa.string()) + result_arrays.append(ArrowExtensionArray(pa_array)) + arrays = result_arrays # type: ignore[assignment] if arrays: df = DataFrame(dict(zip(list(range(len(columns))), arrays))) df.columns = columns diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py index 41255b2516e7e..320bdca60a932 100644 --- a/pandas/tests/arrays/string_/test_string.py +++ b/pandas/tests/arrays/string_/test_string.py @@ -487,13 +487,15 @@ def test_fillna_args(dtype, arrow_string_storage): def test_arrow_array(dtype): # protocol added in 0.15.0 pa = pytest.importorskip("pyarrow") + import pyarrow.compute as pc data = pd.array(["a", "b", "c"], dtype=dtype) arr = pa.array(data) - expected = pa.array(list(data), type=pa.string(), from_pandas=True) + expected = pa.array(list(data), type=pa.large_string(), from_pandas=True) if dtype.storage in ("pyarrow", "pyarrow_numpy") and pa_version_under12p0: expected = pa.chunked_array(expected) - + if dtype.storage == "python": + expected = pc.cast(expected, pa.string()) assert arr.equals(expected) @@ -512,7 +514,10 @@ def test_arrow_roundtrip(dtype, string_storage2, request, using_infer_string): data = pd.array(["a", "b", None], dtype=dtype) df = pd.DataFrame({"a": data}) table = pa.table(df) - assert table.field("a").type == "string" + if dtype.storage == "python": + assert table.field("a").type == "string" + else: + assert table.field("a").type == "large_string" with pd.option_context("string_storage", string_storage2): result = table.to_pandas() assert isinstance(result["a"].dtype, pd.StringDtype) @@ -539,7 +544,10 @@ def test_arrow_load_from_zero_chunks( data = pd.array([], dtype=dtype) df = pd.DataFrame({"a": data}) table = pa.table(df) - assert table.field("a").type == "string" + if dtype.storage == "python": + assert table.field("a").type == "string" + else: + assert table.field("a").type == "large_string" # Instantiate the same table with no chunks at all table = pa.table([pa.chunked_array([], type=pa.string())], schema=table.schema) with pd.option_context("string_storage", string_storage2): diff --git a/pandas/tests/arrays/string_/test_string_arrow.py b/pandas/tests/arrays/string_/test_string_arrow.py index 222b77cb4e94f..d7811b6fed883 100644 --- a/pandas/tests/arrays/string_/test_string_arrow.py +++ b/pandas/tests/arrays/string_/test_string_arrow.py @@ -61,7 +61,7 @@ def test_constructor_not_string_type_raises(array, chunked, arrow_string_storage msg = "Unsupported type '<class 'numpy.ndarray'>' for ArrowExtensionArray" else: msg = re.escape( - "ArrowStringArray requires a PyArrow (chunked) array of string type" + "ArrowStringArray requires a PyArrow (chunked) array of large_string type" ) with pytest.raises(ValueError, match=msg): ArrowStringArray(arr) @@ -76,17 +76,20 @@ def test_constructor_not_string_type_value_dictionary_raises(chunked): arr = pa.chunked_array(arr) msg = re.escape( - "ArrowStringArray requires a PyArrow (chunked) array of string type" + "ArrowStringArray requires a PyArrow (chunked) array of large_string type" ) with pytest.raises(ValueError, match=msg): ArrowStringArray(arr) +@pytest.mark.xfail( + reason="dict conversion does not seem to be implemented for large string in arrow" +) @pytest.mark.parametrize("chunked", [True, False]) def test_constructor_valid_string_type_value_dictionary(chunked): pa = pytest.importorskip("pyarrow") - arr = pa.array(["1", "2", "3"], pa.dictionary(pa.int32(), pa.utf8())) + arr = pa.array(["1", "2", "3"], pa.large_string()).dictionary_encode() if chunked: arr = pa.chunked_array(arr) diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 58a1e51d31b74..0eefb0b52c483 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -2054,6 +2054,13 @@ def test_read_json_dtype_backend( string_array = StringArray(np.array(["a", "b", "c"], dtype=np.object_)) string_array_na = StringArray(np.array(["a", "b", NA], dtype=np.object_)) + elif dtype_backend == "pyarrow": + pa = pytest.importorskip("pyarrow") + from pandas.arrays import ArrowExtensionArray + + string_array = ArrowExtensionArray(pa.array(["a", "b", "c"])) + string_array_na = ArrowExtensionArray(pa.array(["a", "b", None])) + else: string_array = ArrowStringArray(pa.array(["a", "b", "c"])) string_array_na = ArrowStringArray(pa.array(["a", "b", None])) diff --git a/pandas/tests/io/parser/test_read_fwf.py b/pandas/tests/io/parser/test_read_fwf.py index 8566b87ef4292..bed2b5e10a6f7 100644 --- a/pandas/tests/io/parser/test_read_fwf.py +++ b/pandas/tests/io/parser/test_read_fwf.py @@ -971,6 +971,12 @@ def test_dtype_backend(string_storage, dtype_backend): if string_storage == "python": arr = StringArray(np.array(["a", "b"], dtype=np.object_)) arr_na = StringArray(np.array([pd.NA, "a"], dtype=np.object_)) + elif dtype_backend == "pyarrow": + pa = pytest.importorskip("pyarrow") + from pandas.arrays import ArrowExtensionArray + + arr = ArrowExtensionArray(pa.array(["a", "b"])) + arr_na = ArrowExtensionArray(pa.array([None, "a"])) else: pa = pytest.importorskip("pyarrow") arr = ArrowStringArray(pa.array(["a", "b"])) diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py index 8564f09ef7ae9..3c0208fcc74ec 100644 --- a/pandas/tests/io/test_clipboard.py +++ b/pandas/tests/io/test_clipboard.py @@ -359,6 +359,13 @@ def test_read_clipboard_dtype_backend( string_array = StringArray(np.array(["x", "y"], dtype=np.object_)) string_array_na = StringArray(np.array(["x", NA], dtype=np.object_)) + elif dtype_backend == "pyarrow" and engine != "c": + pa = pytest.importorskip("pyarrow") + from pandas.arrays import ArrowExtensionArray + + string_array = ArrowExtensionArray(pa.array(["x", "y"])) + string_array_na = ArrowExtensionArray(pa.array(["x", None])) + else: string_array = ArrowStringArray(pa.array(["x", "y"])) string_array_na = ArrowStringArray(pa.array(["x", None])) diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index 15c5953e79bda..22a7d3b83a459 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -186,6 +186,12 @@ def test_read_feather_dtype_backend(self, string_storage, dtype_backend): string_array = StringArray(np.array(["a", "b", "c"], dtype=np.object_)) string_array_na = StringArray(np.array(["a", "b", pd.NA], dtype=np.object_)) + elif dtype_backend == "pyarrow": + from pandas.arrays import ArrowExtensionArray + + string_array = ArrowExtensionArray(pa.array(["a", "b", "c"])) + string_array_na = ArrowExtensionArray(pa.array(["a", "b", None])) + else: string_array = ArrowStringArray(pa.array(["a", "b", "c"])) string_array_na = ArrowStringArray(pa.array(["a", "b", None])) diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index f0256316e1689..607357e709b6e 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -183,7 +183,12 @@ def test_dtype_backend(self, string_storage, dtype_backend, flavor_read_html): if string_storage == "python": string_array = StringArray(np.array(["a", "b", "c"], dtype=np.object_)) string_array_na = StringArray(np.array(["a", "b", NA], dtype=np.object_)) + elif dtype_backend == "pyarrow": + pa = pytest.importorskip("pyarrow") + from pandas.arrays import ArrowExtensionArray + string_array = ArrowExtensionArray(pa.array(["a", "b", "c"])) + string_array_na = ArrowExtensionArray(pa.array(["a", "b", None])) else: pa = pytest.importorskip("pyarrow") string_array = ArrowStringArray(pa.array(["a", "b", "c"])) diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index e3272e5f5902d..6645aefd4f0a7 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -3647,6 +3647,13 @@ def func(storage, dtype_backend, conn_name) -> DataFrame: string_array = StringArray(np.array(["a", "b", "c"], dtype=np.object_)) string_array_na = StringArray(np.array(["a", "b", pd.NA], dtype=np.object_)) + elif dtype_backend == "pyarrow": + pa = pytest.importorskip("pyarrow") + from pandas.arrays import ArrowExtensionArray + + string_array = ArrowExtensionArray(pa.array(["a", "b", "c"])) # type: ignore[assignment] + string_array_na = ArrowExtensionArray(pa.array(["a", "b", None])) # type: ignore[assignment] + else: pa = pytest.importorskip("pyarrow") string_array = ArrowStringArray(pa.array(["a", "b", "c"])) diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py index e4456b0a78e06..6f429c1ecbf8a 100644 --- a/pandas/tests/io/xml/test_xml.py +++ b/pandas/tests/io/xml/test_xml.py @@ -2044,6 +2044,13 @@ def test_read_xml_nullable_dtypes( string_array = StringArray(np.array(["x", "y"], dtype=np.object_)) string_array_na = StringArray(np.array(["x", NA], dtype=np.object_)) + elif dtype_backend == "pyarrow": + pa = pytest.importorskip("pyarrow") + from pandas.arrays import ArrowExtensionArray + + string_array = ArrowExtensionArray(pa.array(["x", "y"])) + string_array_na = ArrowExtensionArray(pa.array(["x", None])) + else: pa = pytest.importorskip("pyarrow") string_array = ArrowStringArray(pa.array(["x", "y"]))
- [ ] closes #56259 - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. large string is a more sensible default (take concatenates the chunks in pyarrow which can cause overflows pretty quickly), large string should avoid this one todo for a follow up: - ensure interoperability with ``"string[pyarrow]"`` Let's see if CI likes this
https://api.github.com/repos/pandas-dev/pandas/pulls/56220
2023-11-28T11:48:41Z
2023-12-21T21:05:39Z
2023-12-21T21:05:39Z
2023-12-21T21:05:42Z
DOC: DataFrame.update doctests
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 6110f694a6700..b6493614e05a0 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8826,26 +8826,27 @@ def update( 1 b e 2 c f - For Series, its name attribute must be set. - >>> df = pd.DataFrame({'A': ['a', 'b', 'c'], ... 'B': ['x', 'y', 'z']}) - >>> new_column = pd.Series(['d', 'e'], name='B', index=[0, 2]) - >>> df.update(new_column) + >>> new_df = pd.DataFrame({'B': ['d', 'f']}, index=[0, 2]) + >>> df.update(new_df) >>> df A B 0 a d 1 b y - 2 c e + 2 c f + + For Series, its name attribute must be set. + >>> df = pd.DataFrame({'A': ['a', 'b', 'c'], ... 'B': ['x', 'y', 'z']}) - >>> new_df = pd.DataFrame({'B': ['d', 'e']}, index=[1, 2]) - >>> df.update(new_df) + >>> new_column = pd.Series(['d', 'e', 'f'], name='B') + >>> df.update(new_column) >>> df A B - 0 a x - 1 b d - 2 c e + 0 a d + 1 b e + 2 c f If `other` contains NaNs the corresponding values are not updated in the original dataframe.
I felt this original documentation was doing too much in this code block - the description doesn't match the second code example. <kbd><img width="762" alt="image" src="https://github.com/pandas-dev/pandas/assets/122238526/cd897229-5366-40d9-8034-5521b7ecd0e7"></kbd> So I broke it out into these two separate examples: <kbd><img width="974" alt="image" src="https://github.com/pandas-dev/pandas/assets/122238526/36585ddc-d14b-485e-917e-e53f5609c4c3"></kbd> --- I added this new example, which I would have found useful: <kbd><img width="935" alt="image" src="https://github.com/pandas-dev/pandas/assets/122238526/b82fffd1-c095-4784-a2ec-b764b9093a29"></kbd> - [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/56219
2023-11-28T06:53:02Z
2023-11-29T17:48:12Z
2023-11-29T17:48:12Z
2023-11-29T17:48:23Z
TST: specify dt64 units
diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 0d71fb0926df9..5456615f6f028 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -798,7 +798,7 @@ def test_std_timedelta64_skipna_false(self): "values", [["2022-01-01", "2022-01-02", pd.NaT, "2022-01-03"], 4 * [pd.NaT]] ) def test_std_datetime64_with_nat( - self, values, skipna, using_array_manager, request + self, values, skipna, using_array_manager, request, unit ): # GH#51335 if using_array_manager and ( @@ -808,13 +808,14 @@ def test_std_datetime64_with_nat( reason="GH#51446: Incorrect type inference on NaT in reduction result" ) request.applymarker(mark) - df = DataFrame({"a": to_datetime(values)}) + dti = to_datetime(values).as_unit(unit) + df = DataFrame({"a": dti}) result = df.std(skipna=skipna) if not skipna or all(value is pd.NaT for value in values): - expected = Series({"a": pd.NaT}, dtype="timedelta64[ns]") + expected = Series({"a": pd.NaT}, dtype=f"timedelta64[{unit}]") else: # 86400000000000ns == 1 day - expected = Series({"a": 86400000000000}, dtype="timedelta64[ns]") + expected = Series({"a": 86400000000000}, dtype=f"timedelta64[{unit}]") tm.assert_series_equal(result, expected) def test_sum_corner(self): diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py index b8b34d365d051..a5ac5b09bfd34 100644 --- a/pandas/tests/groupby/test_timegrouper.py +++ b/pandas/tests/groupby/test_timegrouper.py @@ -537,7 +537,9 @@ def test_groupby_groups_datetimeindex2(self): for date in dates: result = grouped.get_group(date) data = [[df.loc[date, "A"], df.loc[date, "B"]]] - expected_index = DatetimeIndex([date], name="date", freq="D") + expected_index = DatetimeIndex( + [date], name="date", freq="D", dtype=index.dtype + ) expected = DataFrame(data, columns=list("AB"), index=expected_index) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/methods/test_round.py b/pandas/tests/indexes/datetimes/methods/test_round.py index ad5dd37eacd7c..cde4a3a65804d 100644 --- a/pandas/tests/indexes/datetimes/methods/test_round.py +++ b/pandas/tests/indexes/datetimes/methods/test_round.py @@ -40,9 +40,9 @@ def test_round_invalid(self, freq, error_msg): with pytest.raises(ValueError, match=error_msg): dti.round(freq) - def test_round(self, tz_naive_fixture): + def test_round(self, tz_naive_fixture, unit): tz = tz_naive_fixture - rng = date_range(start="2016-01-01", periods=5, freq="30Min", tz=tz) + rng = date_range(start="2016-01-01", periods=5, freq="30Min", tz=tz, unit=unit) elt = rng[1] expected_rng = DatetimeIndex( @@ -53,10 +53,11 @@ def test_round(self, tz_naive_fixture): Timestamp("2016-01-01 02:00:00", tz=tz), Timestamp("2016-01-01 02:00:00", tz=tz), ] - ) + ).as_unit(unit) expected_elt = expected_rng[1] - tm.assert_index_equal(rng.round(freq="h"), expected_rng) + result = rng.round(freq="h") + tm.assert_index_equal(result, expected_rng) assert elt.round(freq="h") == expected_elt msg = INVALID_FREQ_ERR_MSG @@ -74,9 +75,9 @@ def test_round(self, tz_naive_fixture): def test_round2(self, tz_naive_fixture): tz = tz_naive_fixture # GH#14440 & GH#15578 - index = DatetimeIndex(["2016-10-17 12:00:00.0015"], tz=tz) + index = DatetimeIndex(["2016-10-17 12:00:00.0015"], tz=tz).as_unit("ns") result = index.round("ms") - expected = DatetimeIndex(["2016-10-17 12:00:00.002000"], tz=tz) + expected = DatetimeIndex(["2016-10-17 12:00:00.002000"], tz=tz).as_unit("ns") tm.assert_index_equal(result, expected) for freq in ["us", "ns"]: @@ -84,20 +85,21 @@ def test_round2(self, tz_naive_fixture): def test_round3(self, tz_naive_fixture): tz = tz_naive_fixture - index = DatetimeIndex(["2016-10-17 12:00:00.00149"], tz=tz) + index = DatetimeIndex(["2016-10-17 12:00:00.00149"], tz=tz).as_unit("ns") result = index.round("ms") - expected = DatetimeIndex(["2016-10-17 12:00:00.001000"], tz=tz) + expected = DatetimeIndex(["2016-10-17 12:00:00.001000"], tz=tz).as_unit("ns") tm.assert_index_equal(result, expected) def test_round4(self, tz_naive_fixture): - index = DatetimeIndex(["2016-10-17 12:00:00.001501031"]) + index = DatetimeIndex(["2016-10-17 12:00:00.001501031"], dtype="M8[ns]") result = index.round("10ns") - expected = DatetimeIndex(["2016-10-17 12:00:00.001501030"]) + expected = DatetimeIndex(["2016-10-17 12:00:00.001501030"], dtype="M8[ns]") tm.assert_index_equal(result, expected) + ts = "2016-10-17 12:00:00.001501031" + dti = DatetimeIndex([ts], dtype="M8[ns]") with tm.assert_produces_warning(False): - ts = "2016-10-17 12:00:00.001501031" - DatetimeIndex([ts]).round("1010ns") + dti.round("1010ns") def test_no_rounding_occurs(self, tz_naive_fixture): # GH 21262 @@ -112,9 +114,10 @@ def test_no_rounding_occurs(self, tz_naive_fixture): Timestamp("2016-01-01 00:06:00", tz=tz), Timestamp("2016-01-01 00:08:00", tz=tz), ] - ) + ).as_unit("ns") - tm.assert_index_equal(rng.round(freq="2min"), expected_rng) + result = rng.round(freq="2min") + tm.assert_index_equal(result, expected_rng) @pytest.mark.parametrize( "test_input, rounder, freq, expected", diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index 35c3604de3d63..4a0b192244dc8 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -707,10 +707,14 @@ def test_constructor_dtype(self): idx = DatetimeIndex( ["2013-01-01", "2013-01-02"], dtype="datetime64[ns, US/Eastern]" ) - expected = DatetimeIndex(["2013-01-01", "2013-01-02"]).tz_localize("US/Eastern") + expected = ( + DatetimeIndex(["2013-01-01", "2013-01-02"]) + .as_unit("ns") + .tz_localize("US/Eastern") + ) tm.assert_index_equal(idx, expected) - idx = DatetimeIndex(["2013-01-01", "2013-01-02"], tz="US/Eastern") + idx = DatetimeIndex(["2013-01-01", "2013-01-02"], tz="US/Eastern").as_unit("ns") tm.assert_index_equal(idx, expected) def test_constructor_dtype_tz_mismatch_raises(self): @@ -774,7 +778,7 @@ def test_constructor_start_end_with_tz(self, tz): result = date_range(freq="D", start=start, end=end, tz=tz) expected = DatetimeIndex( ["2013-01-01 06:00:00", "2013-01-02 06:00:00"], - tz="America/Los_Angeles", + dtype="M8[ns, America/Los_Angeles]", freq="D", ) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index b7932715c3ac7..bfbcdcff51ee6 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -226,58 +226,54 @@ def test_take_nan_first_datetime(self): expected = DatetimeIndex([index[-1], index[0], index[1]]) tm.assert_index_equal(result, expected) - def test_take(self): + @pytest.mark.parametrize("tz", [None, "Asia/Tokyo"]) + def test_take(self, tz): # GH#10295 - idx1 = date_range("2011-01-01", "2011-01-31", freq="D", name="idx") - idx2 = date_range( - "2011-01-01", "2011-01-31", freq="D", tz="Asia/Tokyo", name="idx" + idx = date_range("2011-01-01", "2011-01-31", freq="D", name="idx", tz=tz) + + result = idx.take([0]) + assert result == Timestamp("2011-01-01", tz=idx.tz) + + result = idx.take([0, 1, 2]) + expected = date_range( + "2011-01-01", "2011-01-03", freq="D", tz=idx.tz, name="idx" ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq - for idx in [idx1, idx2]: - result = idx.take([0]) - assert result == Timestamp("2011-01-01", tz=idx.tz) + result = idx.take([0, 2, 4]) + expected = date_range( + "2011-01-01", "2011-01-05", freq="2D", tz=idx.tz, name="idx" + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq - result = idx.take([0, 1, 2]) - expected = date_range( - "2011-01-01", "2011-01-03", freq="D", tz=idx.tz, name="idx" - ) - tm.assert_index_equal(result, expected) - assert result.freq == expected.freq + result = idx.take([7, 4, 1]) + expected = date_range( + "2011-01-08", "2011-01-02", freq="-3D", tz=idx.tz, name="idx" + ) + tm.assert_index_equal(result, expected) + assert result.freq == expected.freq - result = idx.take([0, 2, 4]) - expected = date_range( - "2011-01-01", "2011-01-05", freq="2D", tz=idx.tz, name="idx" - ) - tm.assert_index_equal(result, expected) - assert result.freq == expected.freq + result = idx.take([3, 2, 5]) + expected = DatetimeIndex( + ["2011-01-04", "2011-01-03", "2011-01-06"], + dtype=idx.dtype, + freq=None, + name="idx", + ) + tm.assert_index_equal(result, expected) + assert result.freq is None - result = idx.take([7, 4, 1]) - expected = date_range( - "2011-01-08", "2011-01-02", freq="-3D", tz=idx.tz, name="idx" - ) - tm.assert_index_equal(result, expected) - assert result.freq == expected.freq - - result = idx.take([3, 2, 5]) - expected = DatetimeIndex( - ["2011-01-04", "2011-01-03", "2011-01-06"], - dtype=idx.dtype, - freq=None, - name="idx", - ) - tm.assert_index_equal(result, expected) - assert result.freq is None - - result = idx.take([-3, 2, 5]) - expected = DatetimeIndex( - ["2011-01-29", "2011-01-03", "2011-01-06"], - dtype=idx.dtype, - freq=None, - tz=idx.tz, - name="idx", - ) - tm.assert_index_equal(result, expected) - assert result.freq is None + result = idx.take([-3, 2, 5]) + expected = DatetimeIndex( + ["2011-01-29", "2011-01-03", "2011-01-06"], + dtype=idx.dtype, + freq=None, + name="idx", + ) + tm.assert_index_equal(result, expected) + assert result.freq is None def test_take_invalid_kwargs(self): idx = date_range("2011-01-01", "2011-01-31", freq="D", name="idx") diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 03691ca318037..45a9c207f0acc 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -256,13 +256,13 @@ def test_insert_float_index( def test_insert_index_datetimes(self, fill_val, exp_dtype, insert_value): obj = pd.DatetimeIndex( ["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"], tz=fill_val.tz - ) + ).as_unit("ns") assert obj.dtype == exp_dtype exp = pd.DatetimeIndex( ["2011-01-01", fill_val.date(), "2011-01-02", "2011-01-03", "2011-01-04"], tz=fill_val.tz, - ) + ).as_unit("ns") self._assert_insert_conversion(obj, fill_val, exp, exp_dtype) if fill_val.tz: diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py index 6510612ba6f87..af7533399ea74 100644 --- a/pandas/tests/indexing/test_datetime.py +++ b/pandas/tests/indexing/test_datetime.py @@ -57,7 +57,10 @@ def test_indexing_fast_xs(self): df = DataFrame({"a": date_range("2014-01-01", periods=10, tz="UTC")}) result = df.iloc[5] expected = Series( - [Timestamp("2014-01-06 00:00:00+0000", tz="UTC")], index=["a"], name=5 + [Timestamp("2014-01-06 00:00:00+0000", tz="UTC")], + index=["a"], + name=5, + dtype="M8[ns, UTC]", ) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/reshape/concat/test_datetimes.py b/pandas/tests/reshape/concat/test_datetimes.py index c061a393bb1a6..c00a2dc92a52b 100644 --- a/pandas/tests/reshape/concat/test_datetimes.py +++ b/pandas/tests/reshape/concat/test_datetimes.py @@ -52,18 +52,14 @@ def test_concat_datetime_timezone(self): df2 = DataFrame({"b": [1, 2, 3]}, index=idx2) result = concat([df1, df2], axis=1) - exp_idx = ( - DatetimeIndex( - [ - "2011-01-01 00:00:00+01:00", - "2011-01-01 01:00:00+01:00", - "2011-01-01 02:00:00+01:00", - ], - freq="h", - ) - .tz_convert("UTC") - .tz_convert("Europe/Paris") - .as_unit("ns") + exp_idx = DatetimeIndex( + [ + "2011-01-01 00:00:00+01:00", + "2011-01-01 01:00:00+01:00", + "2011-01-01 02:00:00+01:00", + ], + dtype="M8[ns, Europe/Paris]", + freq="h", ) expected = DataFrame( @@ -431,21 +427,25 @@ def test_concat_multiindex_with_tz(self): # GH 6606 df = DataFrame( { - "dt": [ - datetime(2014, 1, 1), - datetime(2014, 1, 2), - datetime(2014, 1, 3), - ], + "dt": DatetimeIndex( + [ + datetime(2014, 1, 1), + datetime(2014, 1, 2), + datetime(2014, 1, 3), + ], + dtype="M8[ns, US/Pacific]", + ), "b": ["A", "B", "C"], "c": [1, 2, 3], "d": [4, 5, 6], } ) - df["dt"] = df["dt"].apply(lambda d: Timestamp(d, tz="US/Pacific")) df = df.set_index(["dt", "b"]) exp_idx1 = DatetimeIndex( - ["2014-01-01", "2014-01-02", "2014-01-03"] * 2, tz="US/Pacific", name="dt" + ["2014-01-01", "2014-01-02", "2014-01-03"] * 2, + dtype="M8[ns, US/Pacific]", + name="dt", ) exp_idx2 = Index(["A", "B", "C"] * 2, name="b") exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2]) diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 168be838ec768..0f3577a214186 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -126,7 +126,8 @@ def test_setitem_with_tz_dst(self, indexer_sli): Timestamp("2016-11-06 00:00-04:00", tz=tz), Timestamp("2011-01-01 00:00-05:00", tz=tz), Timestamp("2016-11-06 01:00-05:00", tz=tz), - ] + ], + dtype=orig.dtype, ) # scalar @@ -138,6 +139,7 @@ def test_setitem_with_tz_dst(self, indexer_sli): vals = Series( [Timestamp("2011-01-01", tz=tz), Timestamp("2012-01-01", tz=tz)], index=[1, 2], + dtype=orig.dtype, ) assert vals.dtype == f"datetime64[ns, {tz}]" @@ -146,7 +148,8 @@ def test_setitem_with_tz_dst(self, indexer_sli): Timestamp("2016-11-06 00:00", tz=tz), Timestamp("2011-01-01 00:00", tz=tz), Timestamp("2012-01-01 00:00", tz=tz), - ] + ], + dtype=orig.dtype, ) ser = orig.copy() diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index f77bff049124b..972d403fff997 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1154,24 +1154,24 @@ def test_constructor_with_datetime_tz5(self): def test_constructor_with_datetime_tz4(self): # inference - s = Series( + ser = Series( [ Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"), Timestamp("2013-01-02 14:00:00-0800", tz="US/Pacific"), ] ) - assert s.dtype == "datetime64[ns, US/Pacific]" - assert lib.infer_dtype(s, skipna=True) == "datetime64" + assert ser.dtype == "datetime64[ns, US/Pacific]" + assert lib.infer_dtype(ser, skipna=True) == "datetime64" def test_constructor_with_datetime_tz3(self): - s = Series( + ser = Series( [ Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"), Timestamp("2013-01-02 14:00:00-0800", tz="US/Eastern"), ] ) - assert s.dtype == "object" - assert lib.infer_dtype(s, skipna=True) == "datetime" + assert ser.dtype == "object" + assert lib.infer_dtype(ser, skipna=True) == "datetime" def test_constructor_with_datetime_tz2(self): # with all NaT @@ -1587,7 +1587,7 @@ def test_NaT_scalar(self): def test_NaT_cast(self): # GH10747 result = Series([np.nan]).astype("M8[ns]") - expected = Series([NaT]) + expected = Series([NaT], dtype="M8[ns]") tm.assert_series_equal(result, expected) def test_constructor_name_hashable(self): diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 508e03f617376..8139fe52c7037 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -625,7 +625,7 @@ def test_to_datetime_mixed_date_and_string(self, format): # https://github.com/pandas-dev/pandas/issues/50108 d1 = date(2020, 1, 2) res = to_datetime(["2020-01-01", d1], format=format) - expected = DatetimeIndex(["2020-01-01", "2020-01-02"]) + expected = DatetimeIndex(["2020-01-01", "2020-01-02"], dtype="M8[ns]") tm.assert_index_equal(res, expected) @pytest.mark.parametrize( @@ -1348,7 +1348,9 @@ def test_to_datetime_utc_true_with_series_tzaware_string(self, cache): ], ) def test_to_datetime_utc_true_with_series_datetime_ns(self, cache, date, dtype): - expected = Series([Timestamp("2013-01-01 01:00:00", tz="UTC")]) + expected = Series( + [Timestamp("2013-01-01 01:00:00", tz="UTC")], dtype="M8[ns, UTC]" + ) result = to_datetime(Series([date], dtype=dtype), utc=True, cache=cache) tm.assert_series_equal(result, expected) @@ -1853,7 +1855,7 @@ class TestToDatetimeUnit: def test_to_datetime_month_or_year_unit_int(self, cache, unit, item, request): # GH#50870 Note we have separate tests that pd.Timestamp gets these right ts = Timestamp(item, unit=unit) - expected = DatetimeIndex([ts]) + expected = DatetimeIndex([ts], dtype="M8[ns]") result = to_datetime([item], unit=unit, cache=cache) tm.assert_index_equal(result, expected) @@ -1929,7 +1931,8 @@ def test_unit_array_mixed_nans(self, cache): result = to_datetime(values, unit="D", errors="coerce", cache=cache) expected = DatetimeIndex( - ["NaT", "1970-01-02", "1970-01-02", "NaT", "NaT", "NaT", "NaT", "NaT"] + ["NaT", "1970-01-02", "1970-01-02", "NaT", "NaT", "NaT", "NaT", "NaT"], + dtype="M8[ns]", ) tm.assert_index_equal(result, expected) @@ -1972,7 +1975,9 @@ def test_unit_consistency(self, cache, error): def test_unit_with_numeric(self, cache, errors, dtype): # GH 13180 # coercions from floats/ints are ok - expected = DatetimeIndex(["2015-06-19 05:33:20", "2015-05-27 22:33:20"]) + expected = DatetimeIndex( + ["2015-06-19 05:33:20", "2015-05-27 22:33:20"], dtype="M8[ns]" + ) arr = np.array([1.434692e18, 1.432766e18]).astype(dtype) result = to_datetime(arr, errors=errors, cache=cache) tm.assert_index_equal(result, expected) @@ -1995,7 +2000,7 @@ def test_unit_with_numeric(self, cache, errors, dtype): def test_unit_with_numeric_coerce(self, cache, exp, arr, warning): # but we want to make sure that we are coercing # if we have ints/strings - expected = DatetimeIndex(exp) + expected = DatetimeIndex(exp, dtype="M8[ns]") with tm.assert_produces_warning(warning, match="Could not infer format"): result = to_datetime(arr, errors="coerce", cache=cache) tm.assert_index_equal(result, expected) @@ -2044,7 +2049,7 @@ def test_unit_ignore_keeps_name(self, cache): def test_to_datetime_errors_ignore_utc_true(self): # GH#23758 result = to_datetime([1], unit="s", utc=True, errors="ignore") - expected = DatetimeIndex(["1970-01-01 00:00:01"], tz="UTC") + expected = DatetimeIndex(["1970-01-01 00:00:01"], dtype="M8[ns, UTC]") tm.assert_index_equal(result, expected) @pytest.mark.parametrize("dtype", [int, float]) @@ -2064,7 +2069,8 @@ def test_to_datetime_unit_with_nulls(self, null): result = to_datetime(ser, unit="s") expected = Series( [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] - + [NaT] + + [NaT], + dtype="M8[ns]", ) tm.assert_series_equal(result, expected) @@ -2078,7 +2084,8 @@ def test_to_datetime_unit_fractional_seconds(self): Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in np.arange(0, 2, 0.25) ] - + [NaT] + + [NaT], + dtype="M8[ns]", ) # GH20455 argument will incur floating point errors but no premature rounding result = result.round("ms") @@ -2087,7 +2094,8 @@ def test_to_datetime_unit_fractional_seconds(self): def test_to_datetime_unit_na_values(self): result = to_datetime([1, 2, "NaT", NaT, np.nan], unit="D") expected = DatetimeIndex( - [Timestamp("1970-01-02"), Timestamp("1970-01-03")] + ["NaT"] * 3 + [Timestamp("1970-01-02"), Timestamp("1970-01-03")] + ["NaT"] * 3, + dtype="M8[ns]", ) tm.assert_index_equal(result, expected) @@ -2101,7 +2109,8 @@ def test_to_datetime_unit_invalid(self, bad_val): def test_to_timestamp_unit_coerce(self, bad_val): # coerce we can process expected = DatetimeIndex( - [Timestamp("1970-01-02"), Timestamp("1970-01-03")] + ["NaT"] * 1 + [Timestamp("1970-01-02"), Timestamp("1970-01-03")] + ["NaT"] * 1, + dtype="M8[ns]", ) result = to_datetime([1, 2, bad_val], unit="D", errors="coerce") tm.assert_index_equal(result, expected) diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 97566750a5225..ddf56e68b1611 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -504,7 +504,7 @@ def test_add_empty_datetimeindex(self, offset_types, tz_naive_fixture): # GH#12724, GH#30336 offset_s = _create_offset(offset_types) - dti = DatetimeIndex([], tz=tz_naive_fixture) + dti = DatetimeIndex([], tz=tz_naive_fixture).as_unit("ns") warn = None if isinstance(
Aimed at trimming the diff in #55901
https://api.github.com/repos/pandas-dev/pandas/pulls/56217
2023-11-28T00:28:35Z
2023-11-28T15:43:47Z
2023-11-28T15:43:47Z
2023-11-28T16:04:49Z
CoW: Avoid warning for ArrowDtypes when setting inplace
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 843441e4865c7..8fce2be8e4e44 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -54,7 +54,11 @@ ) import pandas.core.algorithms as algos -from pandas.core.arrays import DatetimeArray +from pandas.core.arrays import ( + ArrowExtensionArray, + ArrowStringArray, + DatetimeArray, +) from pandas.core.arrays._mixins import NDArrayBackedExtensionArray from pandas.core.construction import ( ensure_wrapped_if_datetimelike, @@ -1343,11 +1347,15 @@ def column_setitem( intermediate Series at the DataFrame level (`s = df[loc]; s[idx] = value`) """ if warn_copy_on_write() and not self._has_no_reference(loc): - warnings.warn( - COW_WARNING_GENERAL_MSG, - FutureWarning, - stacklevel=find_stack_level(), - ) + if not isinstance( + self.blocks[self.blknos[loc]].values, + (ArrowExtensionArray, ArrowStringArray), + ): + warnings.warn( + COW_WARNING_GENERAL_MSG, + FutureWarning, + stacklevel=find_stack_level(), + ) elif using_copy_on_write() and not self._has_no_reference(loc): blkno = self.blknos[loc] # Split blocks to only copy the column we want to modify diff --git a/pandas/tests/copy_view/test_interp_fillna.py b/pandas/tests/copy_view/test_interp_fillna.py index cdb06de90a568..c2482645b072e 100644 --- a/pandas/tests/copy_view/test_interp_fillna.py +++ b/pandas/tests/copy_view/test_interp_fillna.py @@ -344,8 +344,9 @@ def test_fillna_inplace_ea_noop_shares_memory( assert not df._mgr._has_no_reference(1) assert not view._mgr._has_no_reference(1) - # TODO(CoW-warn) should this warn for ArrowDtype? - with tm.assert_cow_warning(warn_copy_on_write): + with tm.assert_cow_warning( + warn_copy_on_write and "pyarrow" not in any_numeric_ea_and_arrow_dtype + ): df.iloc[0, 1] = 100 if isinstance(df["a"].dtype, ArrowDtype) or using_copy_on_write: tm.assert_frame_equal(df_orig, view)
xref https://github.com/pandas-dev/pandas/issues/56019 We shouldn't warn if we know that we are not actually inplace
https://api.github.com/repos/pandas-dev/pandas/pulls/56215
2023-11-28T00:00:02Z
2023-12-04T11:17:24Z
2023-12-04T11:17:24Z
2023-12-04T11:17:31Z
CoW: Add warning for slicing a Series with a MultiIndex
diff --git a/pandas/core/series.py b/pandas/core/series.py index ff03b5071e3b1..b1ac6225cb71e 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1175,7 +1175,7 @@ def _get_values_tuple(self, key: tuple): # If key is contained, would have returned by now indexer, new_index = self.index.get_loc_level(key) new_ser = self._constructor(self._values[indexer], index=new_index, copy=False) - if using_copy_on_write() and isinstance(indexer, slice): + if isinstance(indexer, slice): new_ser._mgr.add_references(self._mgr) # type: ignore[arg-type] return new_ser.__finalize__(self) @@ -1217,7 +1217,7 @@ def _get_value(self, label, takeable: bool = False): new_ser = self._constructor( new_values, index=new_index, name=self.name, copy=False ) - if using_copy_on_write() and isinstance(loc, slice): + if isinstance(loc, slice): new_ser._mgr.add_references(self._mgr) # type: ignore[arg-type] return new_ser.__finalize__(self) diff --git a/pandas/tests/copy_view/test_indexing.py b/pandas/tests/copy_view/test_indexing.py index 355eb2db0ef09..205e80088d8f4 100644 --- a/pandas/tests/copy_view/test_indexing.py +++ b/pandas/tests/copy_view/test_indexing.py @@ -1141,16 +1141,18 @@ def test_set_value_copy_only_necessary_column( assert np.shares_memory(get_array(df, "a"), get_array(view, "a")) -def test_series_midx_slice(using_copy_on_write): +def test_series_midx_slice(using_copy_on_write, warn_copy_on_write): ser = Series([1, 2, 3], index=pd.MultiIndex.from_arrays([[1, 1, 2], [3, 4, 5]])) + ser_orig = ser.copy() result = ser[1] assert np.shares_memory(get_array(ser), get_array(result)) - # TODO(CoW-warn) should warn -> reference is only tracked in CoW mode, so - # warning is not triggered - result.iloc[0] = 100 + with tm.assert_cow_warning(warn_copy_on_write): + result.iloc[0] = 100 if using_copy_on_write: + tm.assert_series_equal(ser, ser_orig) + else: expected = Series( - [1, 2, 3], index=pd.MultiIndex.from_arrays([[1, 1, 2], [3, 4, 5]]) + [100, 2, 3], index=pd.MultiIndex.from_arrays([[1, 1, 2], [3, 4, 5]]) ) tm.assert_series_equal(ser, expected) @@ -1181,16 +1183,15 @@ def test_getitem_midx_slice( assert df.iloc[0, 0] == 100 -def test_series_midx_tuples_slice(using_copy_on_write): +def test_series_midx_tuples_slice(using_copy_on_write, warn_copy_on_write): ser = Series( [1, 2, 3], index=pd.MultiIndex.from_tuples([((1, 2), 3), ((1, 2), 4), ((2, 3), 4)]), ) result = ser[(1, 2)] assert np.shares_memory(get_array(ser), get_array(result)) - # TODO(CoW-warn) should warn -> reference is only tracked in CoW mode, so - # warning is not triggered - result.iloc[0] = 100 + with tm.assert_cow_warning(warn_copy_on_write): + result.iloc[0] = 100 if using_copy_on_write: expected = Series( [1, 2, 3],
xref https://github.com/pandas-dev/pandas/issues/56019 Fixing one more todo
https://api.github.com/repos/pandas-dev/pandas/pulls/56214
2023-11-27T23:29:08Z
2023-12-04T12:26:35Z
2023-12-04T12:26:35Z
2023-12-04T12:41:20Z
CoW: Avoid warning in apply for mixed dtype frame
diff --git a/pandas/core/apply.py b/pandas/core/apply.py index bb3cc3a03760f..169a44accf066 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -20,6 +20,7 @@ from pandas._config import option_context from pandas._libs import lib +from pandas._libs.internals import BlockValuesRefs from pandas._typing import ( AggFuncType, AggFuncTypeBase, @@ -1254,6 +1255,8 @@ def series_generator(self) -> Generator[Series, None, None]: ser = self.obj._ixs(0, axis=0) mgr = ser._mgr + is_view = mgr.blocks[0].refs.has_reference() # type: ignore[union-attr] + if isinstance(ser.dtype, ExtensionDtype): # values will be incorrect for this block # TODO(EA2D): special case would be unnecessary with 2D EAs @@ -1267,6 +1270,14 @@ def series_generator(self) -> Generator[Series, None, None]: ser._mgr = mgr mgr.set_values(arr) object.__setattr__(ser, "_name", name) + if not is_view: + # In apply_series_generator we store the a shallow copy of the + # result, which potentially increases the ref count of this reused + # `ser` object (depending on the result of the applied function) + # -> if that happened and `ser` is already a copy, then we reset + # the refs here to avoid triggering a unnecessary CoW inside the + # applied function (https://github.com/pandas-dev/pandas/pull/56212) + mgr.blocks[0].refs = BlockValuesRefs(mgr.blocks[0]) # type: ignore[union-attr] yield ser @staticmethod diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index a02f31d4483b2..9d2a1e634eea2 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -2071,11 +2071,11 @@ def set_values(self, values: ArrayLike) -> None: Set the values of the single block in place. Use at your own risk! This does not check if the passed values are - valid for the current Block/SingleBlockManager (length, dtype, etc). + valid for the current Block/SingleBlockManager (length, dtype, etc), + and this does not properly keep track of references. """ - # TODO(CoW) do we need to handle copy on write here? Currently this is - # only used for FrameColumnApply.series_generator (what if apply is - # mutating inplace?) + # NOTE(CoW) Currently this is only used for FrameColumnApply.series_generator + # which handles CoW by setting the refs manually if necessary self.blocks[0].values = values self.blocks[0]._mgr_locs = BlockPlacement(slice(len(values))) diff --git a/pandas/tests/apply/test_invalid_arg.py b/pandas/tests/apply/test_invalid_arg.py index 48dde6d42f743..b5ad1094f5bf5 100644 --- a/pandas/tests/apply/test_invalid_arg.py +++ b/pandas/tests/apply/test_invalid_arg.py @@ -18,7 +18,6 @@ DataFrame, Series, date_range, - notna, ) import pandas._testing as tm @@ -150,9 +149,7 @@ def test_transform_axis_1_raises(): Series([1]).transform("sum", axis=1) -# TODO(CoW-warn) should not need to warn -@pytest.mark.filterwarnings("ignore:Setting a value on a view:FutureWarning") -def test_apply_modify_traceback(warn_copy_on_write): +def test_apply_modify_traceback(): data = DataFrame( { "A": [ @@ -207,15 +204,9 @@ def transform(row): row["D"] = 7 return row - def transform2(row): - if notna(row["C"]) and row["C"].startswith("shin") and row["A"] == "foo": - row["D"] = 7 - return row - msg = "'float' object has no attribute 'startswith'" with pytest.raises(AttributeError, match=msg): - with tm.assert_cow_warning(warn_copy_on_write): - data.apply(transform, axis=1) + data.apply(transform, axis=1) @pytest.mark.parametrize( diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index ba8e4bd684198..84b2c59bda5d9 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -2013,3 +2013,31 @@ def test_eval_inplace(using_copy_on_write, warn_copy_on_write): df.iloc[0, 0] = 100 if using_copy_on_write: tm.assert_frame_equal(df_view, df_orig) + + +def test_apply_modify_row(using_copy_on_write, warn_copy_on_write): + # Case: applying a function on each row as a Series object, where the + # function mutates the row object (which needs to trigger CoW if row is a view) + df = DataFrame({"A": [1, 2], "B": [3, 4]}) + df_orig = df.copy() + + def transform(row): + row["B"] = 100 + return row + + with tm.assert_cow_warning(warn_copy_on_write): + df.apply(transform, axis=1) + + if using_copy_on_write: + tm.assert_frame_equal(df, df_orig) + else: + assert df.loc[0, "B"] == 100 + + # row Series is a copy + df = DataFrame({"A": [1, 2], "B": ["b", "c"]}) + df_orig = df.copy() + + with tm.assert_produces_warning(None): + df.apply(transform, axis=1) + + tm.assert_frame_equal(df, df_orig)
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature. Yikes this is ugly xref https://github.com/pandas-dev/pandas/issues/56019
https://api.github.com/repos/pandas-dev/pandas/pulls/56212
2023-11-27T21:58:44Z
2023-12-04T19:37:18Z
2023-12-04T19:37:18Z
2023-12-05T08:37:12Z
CoW: Avoid warning if temporary object is a copy
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 847f514451add..c9da273b99ce9 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8903,7 +8903,7 @@ def update( ChainedAssignmentError, stacklevel=2, ) - elif not PYPY and not using_copy_on_write(): + elif not PYPY and not using_copy_on_write() and self._is_view_after_cow_rules(): if sys.getrefcount(self) <= REF_COUNT: warnings.warn( _chained_assignment_warning_method_msg, diff --git a/pandas/core/generic.py b/pandas/core/generic.py index fb9f987a29bbf..44954e3781f5d 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -668,6 +668,14 @@ def _get_cleaned_column_resolvers(self) -> dict[Hashable, Series]: def _info_axis(self) -> Index: return getattr(self, self._info_axis_name) + def _is_view_after_cow_rules(self): + # Only to be used in cases of chained assignment checks, this is a + # simplified check that assumes that either the whole object is a view + # or a copy + if len(self._mgr.blocks) == 0: # type: ignore[union-attr] + return False + return self._mgr.blocks[0].refs.has_reference() # type: ignore[union-attr] + @property def shape(self) -> tuple[int, ...]: """ @@ -7268,7 +7276,11 @@ def fillna( ChainedAssignmentError, stacklevel=2, ) - elif not PYPY and not using_copy_on_write(): + elif ( + not PYPY + and not using_copy_on_write() + and self._is_view_after_cow_rules() + ): ctr = sys.getrefcount(self) ref_count = REF_COUNT if isinstance(self, ABCSeries) and _check_cacher(self): @@ -7550,7 +7562,11 @@ def ffill( ChainedAssignmentError, stacklevel=2, ) - elif not PYPY and not using_copy_on_write(): + elif ( + not PYPY + and not using_copy_on_write() + and self._is_view_after_cow_rules() + ): ctr = sys.getrefcount(self) ref_count = REF_COUNT if isinstance(self, ABCSeries) and _check_cacher(self): @@ -7733,7 +7749,11 @@ def bfill( ChainedAssignmentError, stacklevel=2, ) - elif not PYPY and not using_copy_on_write(): + elif ( + not PYPY + and not using_copy_on_write() + and self._is_view_after_cow_rules() + ): ctr = sys.getrefcount(self) ref_count = REF_COUNT if isinstance(self, ABCSeries) and _check_cacher(self): @@ -7899,7 +7919,11 @@ def replace( ChainedAssignmentError, stacklevel=2, ) - elif not PYPY and not using_copy_on_write(): + elif ( + not PYPY + and not using_copy_on_write() + and self._is_view_after_cow_rules() + ): ctr = sys.getrefcount(self) ref_count = REF_COUNT if isinstance(self, ABCSeries) and _check_cacher(self): @@ -8340,7 +8364,11 @@ def interpolate( ChainedAssignmentError, stacklevel=2, ) - elif not PYPY and not using_copy_on_write(): + elif ( + not PYPY + and not using_copy_on_write() + and self._is_view_after_cow_rules() + ): ctr = sys.getrefcount(self) ref_count = REF_COUNT if isinstance(self, ABCSeries) and _check_cacher(self): @@ -8978,7 +9006,11 @@ def clip( ChainedAssignmentError, stacklevel=2, ) - elif not PYPY and not using_copy_on_write(): + elif ( + not PYPY + and not using_copy_on_write() + and self._is_view_after_cow_rules() + ): ctr = sys.getrefcount(self) ref_count = REF_COUNT if isinstance(self, ABCSeries) and hasattr(self, "_cacher"): @@ -10926,7 +10958,11 @@ def where( ChainedAssignmentError, stacklevel=2, ) - elif not PYPY and not using_copy_on_write(): + elif ( + not PYPY + and not using_copy_on_write() + and self._is_view_after_cow_rules() + ): ctr = sys.getrefcount(self) ref_count = REF_COUNT if isinstance(self, ABCSeries) and hasattr(self, "_cacher"): @@ -11005,7 +11041,11 @@ def mask( ChainedAssignmentError, stacklevel=2, ) - elif not PYPY and not using_copy_on_write(): + elif ( + not PYPY + and not using_copy_on_write() + and self._is_view_after_cow_rules() + ): ctr = sys.getrefcount(self) ref_count = REF_COUNT if isinstance(self, ABCSeries) and hasattr(self, "_cacher"): diff --git a/pandas/core/series.py b/pandas/core/series.py index ff03b5071e3b1..207f30b68fde2 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3580,7 +3580,7 @@ def update(self, other: Series | Sequence | Mapping) -> None: ChainedAssignmentError, stacklevel=2, ) - elif not PYPY and not using_copy_on_write(): + elif not PYPY and not using_copy_on_write() and self._is_view_after_cow_rules(): ctr = sys.getrefcount(self) ref_count = REF_COUNT if _check_cacher(self): diff --git a/pandas/tests/copy_view/test_clip.py b/pandas/tests/copy_view/test_clip.py index 7ed6a1f803ead..7c87646424e2f 100644 --- a/pandas/tests/copy_view/test_clip.py +++ b/pandas/tests/copy_view/test_clip.py @@ -92,10 +92,10 @@ def test_clip_chained_inplace(using_copy_on_write): with tm.assert_produces_warning(FutureWarning, match="inplace method"): df["a"].clip(1, 2, inplace=True) - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): with option_context("mode.chained_assignment", None): df[["a"]].clip(1, 2, inplace=True) - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): with option_context("mode.chained_assignment", None): df[df["a"] > 1].clip(1, 2, inplace=True) diff --git a/pandas/tests/copy_view/test_interp_fillna.py b/pandas/tests/copy_view/test_interp_fillna.py index cdb06de90a568..5091fd9aed8a4 100644 --- a/pandas/tests/copy_view/test_interp_fillna.py +++ b/pandas/tests/copy_view/test_interp_fillna.py @@ -366,11 +366,11 @@ def test_fillna_chained_assignment(using_copy_on_write): df[["a"]].fillna(100, inplace=True) tm.assert_frame_equal(df, df_orig) else: - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): with option_context("mode.chained_assignment", None): df[["a"]].fillna(100, inplace=True) - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): with option_context("mode.chained_assignment", None): df[df.a > 5].fillna(100, inplace=True) @@ -394,10 +394,10 @@ def test_interpolate_chained_assignment(using_copy_on_write, func): with tm.assert_produces_warning(FutureWarning, match="inplace method"): getattr(df["a"], func)(inplace=True) - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): with option_context("mode.chained_assignment", None): getattr(df[["a"]], func)(inplace=True) - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): with option_context("mode.chained_assignment", None): getattr(df[df["a"] > 1], func)(inplace=True) diff --git a/pandas/tests/copy_view/test_methods.py b/pandas/tests/copy_view/test_methods.py index ba8e4bd684198..62214293df912 100644 --- a/pandas/tests/copy_view/test_methods.py +++ b/pandas/tests/copy_view/test_methods.py @@ -1562,11 +1562,11 @@ def test_chained_where_mask(using_copy_on_write, func): with tm.assert_produces_warning(FutureWarning, match="inplace method"): getattr(df["a"], func)(df["a"] > 2, 5, inplace=True) - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): with option_context("mode.chained_assignment", None): getattr(df[["a"]], func)(df["a"] > 2, 5, inplace=True) - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): with option_context("mode.chained_assignment", None): getattr(df[df["a"] > 1], func)(df["a"] > 2, 5, inplace=True) @@ -1840,11 +1840,11 @@ def test_update_chained_assignment(using_copy_on_write): with tm.assert_produces_warning(FutureWarning, match="inplace method"): df["a"].update(ser2) - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): with option_context("mode.chained_assignment", None): df[["a"]].update(ser2.to_frame()) - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): with option_context("mode.chained_assignment", None): df[df["a"] > 1].update(ser2.to_frame()) diff --git a/pandas/tests/copy_view/test_replace.py b/pandas/tests/copy_view/test_replace.py index 3d8559a1905fc..eb3b1a5ef68e8 100644 --- a/pandas/tests/copy_view/test_replace.py +++ b/pandas/tests/copy_view/test_replace.py @@ -401,11 +401,11 @@ def test_replace_chained_assignment(using_copy_on_write): df[["a"]].replace(1, 100, inplace=True) tm.assert_frame_equal(df, df_orig) else: - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): with option_context("mode.chained_assignment", None): df[["a"]].replace(1, 100, inplace=True) - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): with option_context("mode.chained_assignment", None): df[df.a > 5].replace(1, 100, inplace=True) diff --git a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py index 01e5db87ce456..0dd1a56890fee 100644 --- a/pandas/tests/indexing/multiindex/test_chaining_and_caching.py +++ b/pandas/tests/indexing/multiindex/test_chaining_and_caching.py @@ -34,12 +34,12 @@ def test_detect_chained_assignment(using_copy_on_write, warn_copy_on_write): with tm.raises_chained_assignment_error(): zed["eyes"]["right"].fillna(value=555, inplace=True) elif warn_copy_on_write: - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): zed["eyes"]["right"].fillna(value=555, inplace=True) else: msg = "A value is trying to be set on a copy of a slice from a DataFrame" with pytest.raises(SettingWithCopyError, match=msg): - with tm.assert_produces_warning(FutureWarning, match="inplace method"): + with tm.assert_produces_warning(None): zed["eyes"]["right"].fillna(value=555, inplace=True)
xref https://github.com/pandas-dev/pandas/issues/56019 That's the stricter check we talked about today. The cases we exclude here are no-ops without CoW as well, so no need to warn
https://api.github.com/repos/pandas-dev/pandas/pulls/56211
2023-11-27T21:40:28Z
2023-12-04T12:27:15Z
2023-12-04T12:27:15Z
2023-12-04T12:40:42Z
TST/CLN: Remove makeDataFrame
diff --git a/pandas/tests/frame/methods/test_set_index.py b/pandas/tests/frame/methods/test_set_index.py index 98113b6c41821..d958c80fbcdef 100644 --- a/pandas/tests/frame/methods/test_set_index.py +++ b/pandas/tests/frame/methods/test_set_index.py @@ -155,7 +155,11 @@ def test_set_index(self, float_string_frame): df.set_index(idx[::2]) def test_set_index_names(self): - df = tm.makeDataFrame() + df = DataFrame( + np.ones((10, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(10)], dtype=object), + ) df.index.name = "name" assert df.set_index(df.index).index.names == ["name"] diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 8083795a69413..7fd795dc84cca 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -1566,7 +1566,10 @@ def test_strings_to_numbers_comparisons_raises(self, compare_operators_no_eq_ne) f(df, 0) def test_comparison_protected_from_errstate(self): - missing_df = tm.makeDataFrame() + missing_df = DataFrame( + np.ones((10, 4), dtype=np.float64), + columns=Index(list("ABCD"), dtype=object), + ) missing_df.loc[missing_df.index[0], "A"] = np.nan with np.errstate(invalid="ignore"): expected = missing_df.values < 0 diff --git a/pandas/tests/indexing/test_chaining_and_caching.py b/pandas/tests/indexing/test_chaining_and_caching.py index bf0975a803dce..73ac9a3bb1a44 100644 --- a/pandas/tests/indexing/test_chaining_and_caching.py +++ b/pandas/tests/indexing/test_chaining_and_caching.py @@ -12,6 +12,7 @@ import pandas as pd from pandas import ( DataFrame, + Index, Series, Timestamp, date_range, @@ -627,7 +628,10 @@ def test_chained_getitem_with_lists(self): def test_cache_updating(self): # GH 4939, make sure to update the cache on setitem - df = tm.makeDataFrame() + df = DataFrame( + np.zeros((10, 4)), + columns=Index(list("ABCD"), dtype=object), + ) df["A"] # cache series df.loc["Hello Friend"] = df.iloc[0] assert "Hello Friend" in df["A"].index diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 507d7ed4bf9d0..9aeac58de50bb 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -1234,7 +1234,11 @@ def test_freeze_panes(self, path): tm.assert_frame_equal(result, expected) def test_path_path_lib(self, engine, ext): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) writer = partial(df.to_excel, engine=engine) reader = partial(pd.read_excel, index_col=0) @@ -1242,7 +1246,11 @@ def test_path_path_lib(self, engine, ext): tm.assert_frame_equal(result, df) def test_path_local_path(self, engine, ext): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) writer = partial(df.to_excel, engine=engine) reader = partial(pd.read_excel, index_col=0) diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index 613f609320f31..33b9fe9b665f3 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -10,6 +10,7 @@ import pandas as pd from pandas import ( DataFrame, + Index, compat, ) import pandas._testing as tm @@ -665,7 +666,7 @@ def test_na_rep_truncated(self): def test_to_csv_errors(self, errors): # GH 22610 data = ["\ud800foo"] - ser = pd.Series(data, index=pd.Index(data)) + ser = pd.Series(data, index=Index(data)) with tm.ensure_clean("test.csv") as path: ser.to_csv(path, errors=errors) # No use in reading back the data as it is not the same anymore @@ -679,7 +680,11 @@ def test_to_csv_binary_handle(self, mode): GH 35058 and GH 19827 """ - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) with tm.ensure_clean() as path: with open(path, mode="w+b") as handle: df.to_csv(handle, mode=mode) @@ -713,7 +718,11 @@ def test_to_csv_encoding_binary_handle(self, mode): def test_to_csv_iterative_compression_name(compression): # GH 38714 - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) with tm.ensure_clean() as path: df.to_csv(path, compression=compression, chunksize=1) tm.assert_frame_equal( @@ -723,7 +732,11 @@ def test_to_csv_iterative_compression_name(compression): def test_to_csv_iterative_compression_buffer(compression): # GH 38714 - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) with io.BytesIO() as buffer: df.to_csv(buffer, compression=compression, chunksize=1) buffer.seek(0) diff --git a/pandas/tests/io/parser/common/test_file_buffer_url.py b/pandas/tests/io/parser/common/test_file_buffer_url.py index c374795019ff4..a7a8d031da215 100644 --- a/pandas/tests/io/parser/common/test_file_buffer_url.py +++ b/pandas/tests/io/parser/common/test_file_buffer_url.py @@ -11,6 +11,7 @@ from urllib.error import URLError import uuid +import numpy as np import pytest from pandas.errors import ( @@ -19,7 +20,10 @@ ) import pandas.util._test_decorators as td -from pandas import DataFrame +from pandas import ( + DataFrame, + Index, +) import pandas._testing as tm pytestmark = pytest.mark.filterwarnings( @@ -66,7 +70,11 @@ def test_local_file(all_parsers, csv_dir_path): @xfail_pyarrow # AssertionError: DataFrame.index are different def test_path_path_lib(all_parsers): parser = all_parsers - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) result = tm.round_trip_pathlib(df.to_csv, lambda p: parser.read_csv(p, index_col=0)) tm.assert_frame_equal(df, result) @@ -74,7 +82,11 @@ def test_path_path_lib(all_parsers): @xfail_pyarrow # AssertionError: DataFrame.index are different def test_path_local_path(all_parsers): parser = all_parsers - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) result = tm.round_trip_localpath( df.to_csv, lambda p: parser.read_csv(p, index_col=0) ) diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py index 89a0162af1c54..9eb9ffa53dd22 100644 --- a/pandas/tests/io/pytables/test_append.py +++ b/pandas/tests/io/pytables/test_append.py @@ -11,6 +11,7 @@ import pandas as pd from pandas import ( DataFrame, + Index, Series, _testing as tm, concat, @@ -401,7 +402,7 @@ def check_col(key, name, size): { "A": [0.0, 1.0, 2.0, 3.0, 4.0], "B": [0.0, 1.0, 0.0, 1.0, 0.0], - "C": pd.Index(["foo1", "foo2", "foo3", "foo4", "foo5"], dtype=object), + "C": Index(["foo1", "foo2", "foo3", "foo4", "foo5"], dtype=object), "D": date_range("20130101", periods=5), } ).set_index("C") @@ -658,7 +659,11 @@ def test_append_hierarchical(tmp_path, setup_path, multiindex_dataframe_random_d def test_append_misc(setup_path): with ensure_clean_store(setup_path) as store: - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) store.append("df", df, chunksize=1) result = store.select("df") tm.assert_frame_equal(result, df) @@ -671,7 +676,11 @@ def test_append_misc(setup_path): @pytest.mark.parametrize("chunksize", [10, 200, 1000]) def test_append_misc_chunksize(setup_path, chunksize): # more chunksize in append tests - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df["string"] = "foo" df["float322"] = 1.0 df["float322"] = df["float322"].astype("float32") @@ -715,7 +724,11 @@ def test_append_raise(setup_path): # test append with invalid input to get good error messages # list in column - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df["invalid"] = [["a"]] * len(df) assert df.dtypes["invalid"] == np.object_ msg = re.escape( @@ -732,7 +745,11 @@ def test_append_raise(setup_path): store.append("df", df) # datetime with embedded nans as object - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) s = Series(datetime.datetime(2001, 1, 2), index=df.index) s = s.astype(object) s[0:5] = np.nan @@ -756,7 +773,11 @@ def test_append_raise(setup_path): store.append("df", Series(np.arange(10))) # appending an incompatible table - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) store.append("df", df) df["foo"] = "foo" diff --git a/pandas/tests/io/pytables/test_errors.py b/pandas/tests/io/pytables/test_errors.py index adf42cc7e8d39..d956e4f5775eb 100644 --- a/pandas/tests/io/pytables/test_errors.py +++ b/pandas/tests/io/pytables/test_errors.py @@ -9,6 +9,7 @@ CategoricalIndex, DataFrame, HDFStore, + Index, MultiIndex, _testing as tm, date_range, @@ -25,7 +26,11 @@ def test_pass_spec_to_storer(setup_path): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) with ensure_clean_store(setup_path) as store: store.put("df", df) @@ -60,14 +65,22 @@ def test_unimplemented_dtypes_table_columns(setup_path): # currently not supported dtypes #### for n, f in dtypes: - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df[n] = f msg = re.escape(f"[{n}] is not implemented as a table column") with pytest.raises(TypeError, match=msg): store.append(f"df1_{n}", df) # frame - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df["obj1"] = "foo" df["obj2"] = "bar" df["datetime1"] = datetime.date(2001, 1, 2) diff --git a/pandas/tests/io/pytables/test_file_handling.py b/pandas/tests/io/pytables/test_file_handling.py index cb44512d4506c..2920f0b07b31e 100644 --- a/pandas/tests/io/pytables/test_file_handling.py +++ b/pandas/tests/io/pytables/test_file_handling.py @@ -17,6 +17,7 @@ from pandas import ( DataFrame, HDFStore, + Index, Series, _testing as tm, read_hdf, @@ -145,7 +146,11 @@ def test_reopen_handle(tmp_path, setup_path): def test_open_args(setup_path): with tm.ensure_clean(setup_path) as path: - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) # create an in memory store store = HDFStore( @@ -172,7 +177,11 @@ def test_flush(setup_path): def test_complibs_default_settings(tmp_path, setup_path): # GH15943 - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) # Set complevel and check if complib is automatically set to # default value @@ -211,7 +220,11 @@ def test_complibs_default_settings(tmp_path, setup_path): def test_complibs_default_settings_override(tmp_path, setup_path): # Check if file-defaults can be overridden on a per table basis - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) tmpfile = tmp_path / setup_path store = HDFStore(tmpfile) store.append("dfc", df, complevel=9, complib="blosc") @@ -325,7 +338,11 @@ def test_multiple_open_close(tmp_path, setup_path): path = tmp_path / setup_path - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.to_hdf(path, key="df", mode="w", format="table") # single @@ -402,7 +419,11 @@ def test_multiple_open_close(tmp_path, setup_path): # ops on a closed store path = tmp_path / setup_path - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.to_hdf(path, key="df", mode="w", format="table") store = HDFStore(path) diff --git a/pandas/tests/io/pytables/test_keys.py b/pandas/tests/io/pytables/test_keys.py index fd7df29595090..c0f2c34ff37ed 100644 --- a/pandas/tests/io/pytables/test_keys.py +++ b/pandas/tests/io/pytables/test_keys.py @@ -1,8 +1,10 @@ +import numpy as np import pytest from pandas import ( DataFrame, HDFStore, + Index, Series, _testing as tm, ) @@ -20,7 +22,11 @@ def test_keys(setup_path): store["b"] = Series( range(10), dtype="float64", index=[f"i_{i}" for i in range(10)] ) - store["c"] = tm.makeDataFrame() + store["c"] = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) assert len(store) == 3 expected = {"/a", "/b", "/c"} diff --git a/pandas/tests/io/pytables/test_put.py b/pandas/tests/io/pytables/test_put.py index 59a05dc9ea546..8a6e3c9006439 100644 --- a/pandas/tests/io/pytables/test_put.py +++ b/pandas/tests/io/pytables/test_put.py @@ -47,7 +47,11 @@ def test_format_kwarg_in_constructor(tmp_path, setup_path): def test_api_default_format(tmp_path, setup_path): # default_format option with ensure_clean_store(setup_path) as store: - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) with pd.option_context("io.hdf.default_format", "fixed"): _maybe_remove(store, "df") @@ -68,7 +72,11 @@ def test_api_default_format(tmp_path, setup_path): assert store.get_storer("df").is_table path = tmp_path / setup_path - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) with pd.option_context("io.hdf.default_format", "fixed"): df.to_hdf(path, key="df") diff --git a/pandas/tests/io/pytables/test_round_trip.py b/pandas/tests/io/pytables/test_round_trip.py index e05e1e96eb11f..693f10172a99e 100644 --- a/pandas/tests/io/pytables/test_round_trip.py +++ b/pandas/tests/io/pytables/test_round_trip.py @@ -39,7 +39,11 @@ def roundtrip(key, obj, **kwargs): o = Series(range(10), dtype="float64", index=[f"i_{i}" for i in range(10)]) tm.assert_series_equal(o, roundtrip("string_series", o)) - o = tm.makeDataFrame() + o = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) tm.assert_frame_equal(o, roundtrip("frame", o)) # table @@ -136,7 +140,11 @@ def test_api_2(tmp_path, setup_path): def test_api_invalid(tmp_path, setup_path): path = tmp_path / setup_path # Invalid. - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) msg = "Can only append to Tables" @@ -347,7 +355,11 @@ def test_timeseries_preepoch(setup_path, request): "compression", [False, pytest.param(True, marks=td.skip_if_windows)] ) def test_frame(compression, setup_path): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) # put in some random NAs df.iloc[0, 0] = np.nan @@ -424,7 +436,11 @@ def test_store_hierarchical(setup_path, multiindex_dataframe_random_data): ) def test_store_mixed(compression, setup_path): def _make_one(): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df["obj1"] = "foo" df["obj2"] = "bar" df["bool1"] = df["A"] > 0 diff --git a/pandas/tests/io/pytables/test_select.py b/pandas/tests/io/pytables/test_select.py index e387b1b607f63..3eaa1e86dbf6d 100644 --- a/pandas/tests/io/pytables/test_select.py +++ b/pandas/tests/io/pytables/test_select.py @@ -266,7 +266,11 @@ def test_select_dtypes(setup_path): # test selection with comparison against numpy scalar # GH 11283 with ensure_clean_store(setup_path) as store: - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) expected = df[df["A"] > 0] diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 7e8365a8f9ffa..98257f1765d53 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -45,7 +45,11 @@ def test_context(setup_path): pass with tm.ensure_clean(setup_path) as path: with HDFStore(path) as tbl: - tbl["a"] = tm.makeDataFrame() + tbl["a"] = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) assert len(tbl) == 1 assert type(tbl["a"]) == DataFrame @@ -107,9 +111,17 @@ def test_repr(setup_path): store["b"] = Series( range(10), dtype="float64", index=[f"i_{i}" for i in range(10)] ) - store["c"] = tm.makeDataFrame() + store["c"] = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df["obj1"] = "foo" df["obj2"] = "bar" df["bool1"] = df["A"] > 0 @@ -136,7 +148,11 @@ def test_repr(setup_path): # storers with ensure_clean_store(setup_path) as store: - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) store.append("df", df) s = store.get_storer("df") @@ -147,8 +163,16 @@ def test_repr(setup_path): def test_contains(setup_path): with ensure_clean_store(setup_path) as store: store["a"] = tm.makeTimeSeries() - store["b"] = tm.makeDataFrame() - store["foo/bar"] = tm.makeDataFrame() + store["b"] = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) + store["foo/bar"] = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) assert "a" in store assert "b" in store assert "c" not in store @@ -161,14 +185,22 @@ def test_contains(setup_path): with tm.assert_produces_warning( tables.NaturalNameWarning, check_stacklevel=False ): - store["node())"] = tm.makeDataFrame() + store["node())"] = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) assert "node())" in store def test_versioning(setup_path): with ensure_clean_store(setup_path) as store: store["a"] = tm.makeTimeSeries() - store["b"] = tm.makeDataFrame() + store["b"] = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df = tm.makeTimeDataFrame() _maybe_remove(store, "df1") store.append("df1", df[:10]) @@ -432,7 +464,11 @@ def test_mi_data_columns(setup_path): def test_table_mixed_dtypes(setup_path): # frame - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df["obj1"] = "foo" df["obj2"] = "bar" df["bool1"] = df["A"] > 0 @@ -482,7 +518,11 @@ def test_calendar_roundtrip_issue(setup_path): def test_remove(setup_path): with ensure_clean_store(setup_path) as store: ts = tm.makeTimeSeries() - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) store["a"] = ts store["b"] = df _maybe_remove(store, "a") @@ -542,7 +582,11 @@ def test_same_name_scoping(setup_path): def test_store_index_name(setup_path): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.index.name = "foo" with ensure_clean_store(setup_path) as store: @@ -581,7 +625,11 @@ def test_store_index_name_numpy_str(tmp_path, table_format, setup_path, unit, tz def test_store_series_name(setup_path): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) series = df["A"] with ensure_clean_store(setup_path) as store: @@ -783,7 +831,11 @@ def test_start_stop_fixed(setup_path): tm.assert_series_equal(result, expected) # sparse; not implemented - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.iloc[3:5, 1:3] = np.nan df.iloc[8:10, -2] = np.nan @@ -806,7 +858,11 @@ def test_select_filter_corner(setup_path): def test_path_pathlib(): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) result = tm.round_trip_pathlib( lambda p: df.to_hdf(p, key="df"), lambda p: read_hdf(p, "df") @@ -832,7 +888,11 @@ def test_contiguous_mixed_data_table(start, stop, setup_path): def test_path_pathlib_hdfstore(): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) def writer(path): with HDFStore(path) as store: @@ -847,7 +907,11 @@ def reader(path): def test_pickle_path_localpath(): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) result = tm.round_trip_pathlib( lambda p: df.to_hdf(p, key="df"), lambda p: read_hdf(p, "df") ) @@ -855,7 +919,11 @@ def test_pickle_path_localpath(): def test_path_localpath_hdfstore(): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) def writer(path): with HDFStore(path) as store: @@ -871,7 +939,11 @@ def reader(path): @pytest.mark.parametrize("propindexes", [True, False]) def test_copy(propindexes): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) with tm.ensure_clean() as path: with HDFStore(path) as st: diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index 26035d1af7f90..718f967f2f3d8 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -15,6 +15,7 @@ import pickle import tempfile +import numpy as np import pytest from pandas.compat import is_platform_windows @@ -442,7 +443,11 @@ def test_next(self, mmap_file): def test_unknown_engine(self): with tm.ensure_clean() as path: - df = tm.makeDataFrame() + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.to_csv(path) with pytest.raises(ValueError, match="Unknown engine"): pd.read_csv(path, engine="pyt") @@ -454,7 +459,11 @@ def test_binary_mode(self): GH 35058 """ with tm.ensure_clean() as path: - df = tm.makeDataFrame() + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.to_csv(path, mode="w+b") tm.assert_frame_equal(df, pd.read_csv(path, index_col=0)) @@ -468,7 +477,11 @@ def test_warning_missing_utf_bom(self, encoding, compression_): GH 35681 """ - df = tm.makeDataFrame() + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) with tm.ensure_clean() as path: with tm.assert_produces_warning(UnicodeWarning): df.to_csv(path, compression=compression_, encoding=encoding) @@ -498,7 +511,11 @@ def test_is_fsspec_url(): @pytest.mark.parametrize("format", ["csv", "json"]) def test_codecs_encoding(encoding, format): # GH39247 - expected = tm.makeDataFrame() + expected = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) with tm.ensure_clean() as path: with codecs.open(path, mode="w", encoding=encoding) as handle: getattr(expected, f"to_{format}")(handle) @@ -512,7 +529,11 @@ def test_codecs_encoding(encoding, format): def test_codecs_get_writer_reader(): # GH39247 - expected = tm.makeDataFrame() + expected = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) with tm.ensure_clean() as path: with open(path, "wb") as handle: with codecs.getwriter("utf-8")(handle) as encoded: @@ -534,7 +555,11 @@ def test_explicit_encoding(io_class, mode, msg): # GH39247; this test makes sure that if a user provides mode="*t" or "*b", # it is used. In the case of this test it leads to an error as intentionally the # wrong mode is requested - expected = tm.makeDataFrame() + expected = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) with io_class() as buffer: with pytest.raises(TypeError, match=msg): expected.to_csv(buffer, mode=f"w{mode}") diff --git a/pandas/tests/io/test_compression.py b/pandas/tests/io/test_compression.py index af83ec4a55fa5..3a58dda9e8dc4 100644 --- a/pandas/tests/io/test_compression.py +++ b/pandas/tests/io/test_compression.py @@ -9,6 +9,7 @@ import time import zipfile +import numpy as np import pytest from pandas.compat import is_platform_windows @@ -142,7 +143,11 @@ def test_compression_binary(compression_only): GH22555 """ - df = tm.makeDataFrame() + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) # with a file with tm.ensure_clean() as path: @@ -170,7 +175,11 @@ def test_gzip_reproducibility_file_name(): GH 28103 """ - df = tm.makeDataFrame() + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) compression_options = {"method": "gzip", "mtime": 1} # test for filename @@ -189,7 +198,11 @@ def test_gzip_reproducibility_file_object(): GH 28103 """ - df = tm.makeDataFrame() + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) compression_options = {"method": "gzip", "mtime": 1} # test for file object diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index 5ec8705251d95..572abbf7c48f7 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -132,17 +132,29 @@ def test_rw_use_threads(self): self.check_round_trip(df, use_threads=False) def test_path_pathlib(self): - df = tm.makeDataFrame().reset_index() + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ).reset_index() result = tm.round_trip_pathlib(df.to_feather, read_feather) tm.assert_frame_equal(df, result) def test_path_localpath(self): - df = tm.makeDataFrame().reset_index() + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ).reset_index() result = tm.round_trip_localpath(df.to_feather, read_feather) tm.assert_frame_equal(df, result) def test_passthrough_keywords(self): - df = tm.makeDataFrame().reset_index() + df = pd.DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ).reset_index() self.check_round_trip(df, write_kwargs={"version": 1}) @pytest.mark.network diff --git a/pandas/tests/io/test_gcs.py b/pandas/tests/io/test_gcs.py index 6e55cde12f2f9..0ce6a8bf82cd8 100644 --- a/pandas/tests/io/test_gcs.py +++ b/pandas/tests/io/test_gcs.py @@ -9,6 +9,7 @@ from pandas import ( DataFrame, + Index, date_range, read_csv, read_excel, @@ -145,7 +146,11 @@ def test_to_csv_compression_encoding_gcs( GH 35677 (to_csv, compression), GH 26124 (to_csv, encoding), and GH 32392 (read_csv, encoding) """ - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) # reference of compressed and encoded file compression = {"method": compression_only} diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index 780b25fd0f346..e1fac21094139 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -41,6 +41,7 @@ import pandas as pd from pandas import ( + DataFrame, Index, Series, period_range, @@ -220,13 +221,21 @@ def test_round_trip_current(typ, expected, pickle_writer, writer): def test_pickle_path_pathlib(): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) result = tm.round_trip_pathlib(df.to_pickle, pd.read_pickle) tm.assert_frame_equal(df, result) def test_pickle_path_localpath(): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) result = tm.round_trip_localpath(df.to_pickle, pd.read_pickle) tm.assert_frame_equal(df, result) @@ -280,7 +289,11 @@ def test_write_explicit(self, compression, get_random_path): path2 = base + ".raw" with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2: - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) # write to compressed file df.to_pickle(p1, compression=compression) @@ -299,7 +312,11 @@ def test_write_explicit(self, compression, get_random_path): def test_write_explicit_bad(self, compression, get_random_path): with pytest.raises(ValueError, match="Unrecognized compression type"): with tm.ensure_clean(get_random_path) as path: - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.to_pickle(path, compression=compression) def test_write_infer(self, compression_ext, get_random_path): @@ -309,7 +326,11 @@ def test_write_infer(self, compression_ext, get_random_path): compression = self._extension_to_compression.get(compression_ext.lower()) with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2: - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) # write to compressed file by inferred compression method df.to_pickle(p1) @@ -330,7 +351,11 @@ def test_read_explicit(self, compression, get_random_path): path2 = base + ".compressed" with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2: - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) # write to uncompressed file df.to_pickle(p1, compression=None) @@ -349,7 +374,11 @@ def test_read_infer(self, compression_ext, get_random_path): compression = self._extension_to_compression.get(compression_ext.lower()) with tm.ensure_clean(path1) as p1, tm.ensure_clean(path2) as p2: - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) # write to uncompressed file df.to_pickle(p1, compression=None) @@ -371,7 +400,11 @@ class TestProtocol: @pytest.mark.parametrize("protocol", [-1, 0, 1, 2]) def test_read(self, protocol, get_random_path): with tm.ensure_clean(get_random_path) as path: - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.to_pickle(path, protocol=protocol) df2 = pd.read_pickle(path) tm.assert_frame_equal(df, df2) @@ -404,7 +437,11 @@ def test_unicode_decode_error(datapath, pickle_file, excols): def test_pickle_buffer_roundtrip(): with tm.ensure_clean() as path: - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) with open(path, "wb") as fh: df.to_pickle(fh) with open(path, "rb") as fh: @@ -450,7 +487,11 @@ def close(self): def mock_urlopen_read(*args, **kwargs): return MockReadResponse(path) - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) python_pickler(df, path) monkeypatch.setattr("urllib.request.urlopen", mock_urlopen_read) result = pd.read_pickle(mockurl) @@ -461,7 +502,11 @@ def test_pickle_fsspec_roundtrip(): pytest.importorskip("fsspec") with tm.ensure_clean(): mockurl = "memory://mockfile" - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.to_pickle(mockurl) result = pd.read_pickle(mockurl) tm.assert_frame_equal(df, result) @@ -487,7 +532,11 @@ def test_pickle_binary_object_compression(compression): GH 26237, GH 29054, and GH 29570 """ - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) # reference for compression with tm.ensure_clean() as path: @@ -567,7 +616,7 @@ def test_pickle_preserves_block_ndim(): @pytest.mark.parametrize("protocol", [pickle.DEFAULT_PROTOCOL, pickle.HIGHEST_PROTOCOL]) def test_pickle_big_dataframe_compression(protocol, compression): # GH#39002 - df = pd.DataFrame(range(100000)) + df = DataFrame(range(100000)) result = tm.round_trip_pathlib( partial(df.to_pickle, protocol=protocol, compression=compression), partial(pd.read_pickle, compression=compression), @@ -587,13 +636,13 @@ def test_pickle_frame_v124_unpickle_130(datapath): with open(path, "rb") as fd: df = pickle.load(fd) - expected = pd.DataFrame(index=[], columns=[]) + expected = DataFrame(index=[], columns=[]) tm.assert_frame_equal(df, expected) def test_pickle_pos_args_deprecation(): # GH-54229 - df = pd.DataFrame({"a": [1, 2, 3]}) + df = DataFrame({"a": [1, 2, 3]}) msg = ( r"Starting with pandas version 3.0 all arguments of to_pickle except for the " r"argument 'path' will be keyword-only." diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 82e6c2964b8c5..19d81d50f5774 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -1549,14 +1549,22 @@ def test_inf(self, infval): df.to_stata(path) def test_path_pathlib(self): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.index.name = "index" reader = lambda x: read_stata(x).set_index("index") result = tm.round_trip_pathlib(df.to_stata, reader) tm.assert_frame_equal(df, result) def test_pickle_path_localpath(self): - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.index.name = "index" reader = lambda x: read_stata(x).set_index("index") result = tm.round_trip_localpath(df.to_stata, reader) @@ -1577,7 +1585,11 @@ def test_value_labels_iterator(self, write_index): def test_set_index(self): # GH 17328 - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.index.name = "index" with tm.ensure_clean() as path: df.to_stata(path) @@ -1714,7 +1726,11 @@ def test_invalid_date_conversion(self): def test_nonfile_writing(self, version): # GH 21041 bio = io.BytesIO() - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.index.name = "index" with tm.ensure_clean() as path: df.to_stata(bio, version=version) @@ -1726,7 +1742,11 @@ def test_nonfile_writing(self, version): def test_gzip_writing(self): # writing version 117 requires seek and cannot be used with gzip - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=pd.Index(list("ABCD"), dtype=object), + index=pd.Index([f"i-{i}" for i in range(30)], dtype=object), + ) df.index.name = "index" with tm.ensure_clean() as path: with gzip.GzipFile(path, "wb") as gz: diff --git a/pandas/tests/plotting/test_datetimelike.py b/pandas/tests/plotting/test_datetimelike.py index bfb9a5a9a1647..3195b7637ee3c 100644 --- a/pandas/tests/plotting/test_datetimelike.py +++ b/pandas/tests/plotting/test_datetimelike.py @@ -1314,7 +1314,11 @@ def test_secondary_legend_multi_col(self): def test_secondary_legend_nonts(self): # non-ts - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) fig = mpl.pyplot.figure() ax = fig.add_subplot(211) ax = df.plot(secondary_y=["A", "B"], ax=ax) @@ -1331,7 +1335,11 @@ def test_secondary_legend_nonts(self): def test_secondary_legend_nonts_multi_col(self): # non-ts - df = tm.makeDataFrame() + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + ) fig = mpl.pyplot.figure() ax = fig.add_subplot(211) ax = df.plot(secondary_y=["C", "D"], ax=ax) diff --git a/pandas/tests/series/methods/test_reset_index.py b/pandas/tests/series/methods/test_reset_index.py index 9e6b4ce0df1d6..634b8699a89e6 100644 --- a/pandas/tests/series/methods/test_reset_index.py +++ b/pandas/tests/series/methods/test_reset_index.py @@ -33,7 +33,11 @@ def test_reset_index_dti_round_trip(self): assert df.reset_index()["Date"].iloc[0] == stamp def test_reset_index(self): - df = tm.makeDataFrame()[:5] + df = DataFrame( + 1.1 * np.arange(120).reshape((30, 4)), + columns=Index(list("ABCD"), dtype=object), + index=Index([f"i-{i}" for i in range(30)], dtype=object), + )[:5] ser = df.stack(future_stack=True) ser.index.names = ["hash", "category"]
null
https://api.github.com/repos/pandas-dev/pandas/pulls/56210
2023-11-27T20:13:13Z
2023-11-28T17:08:38Z
2023-11-28T17:08:38Z
2024-01-22T18:38:11Z
Update indexing unpacking logic for single block case
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 8bc30cb5f0ddc..e3928621a4e48 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -2140,6 +2140,12 @@ def _setitem_single_block(self, indexer, value, name: str) -> None: """ from pandas import Series + if (isinstance(value, ABCSeries) and name != "iloc") or isinstance(value, dict): + # TODO(EA): ExtensionBlock.setitem this causes issues with + # setting for extensionarrays that store dicts. Need to decide + # if it's worth supporting that. + value = self._align_series(indexer, Series(value)) + info_axis = self.obj._info_axis_number item_labels = self.obj._get_axis(info_axis) if isinstance(indexer, tuple): @@ -2160,13 +2166,7 @@ def _setitem_single_block(self, indexer, value, name: str) -> None: indexer = maybe_convert_ix(*indexer) # e.g. test_setitem_frame_align - if (isinstance(value, ABCSeries) and name != "iloc") or isinstance(value, dict): - # TODO(EA): ExtensionBlock.setitem this causes issues with - # setting for extensionarrays that store dicts. Need to decide - # if it's worth supporting that. - value = self._align_series(indexer, Series(value)) - - elif isinstance(value, ABCDataFrame) and name != "iloc": + if isinstance(value, ABCDataFrame) and name != "iloc": value = self._align_frame(indexer, value)._values # check for chained assignment
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/56209
2023-11-27T20:12:43Z
2023-11-29T18:02:02Z
2023-11-29T18:02:02Z
2023-11-29T18:06:02Z
BUG: inferred resolution with ISO8601 and tzoffset
diff --git a/doc/source/whatsnew/v2.2.0.rst b/doc/source/whatsnew/v2.2.0.rst index fbff38aeefc51..70d43b852945d 100644 --- a/doc/source/whatsnew/v2.2.0.rst +++ b/doc/source/whatsnew/v2.2.0.rst @@ -457,6 +457,7 @@ Datetimelike - Bug in :meth:`Index.view` to a datetime64 dtype with non-supported resolution incorrectly raising (:issue:`55710`) - Bug in :meth:`Series.dt.round` with non-nanosecond resolution and ``NaT`` entries incorrectly raising ``OverflowError`` (:issue:`56158`) - Bug in :meth:`Tick.delta` with very large ticks raising ``OverflowError`` instead of ``OutOfBoundsTimedelta`` (:issue:`55503`) +- Bug in :meth:`Timestamp.unit` being inferred incorrectly from an ISO8601 format string with minute or hour resolution and a timezone offset (:issue:`56208`) - Bug in ``.astype`` converting from a higher-resolution ``datetime64`` dtype to a lower-resolution ``datetime64`` dtype (e.g. ``datetime64[us]->datetim64[ms]``) silently overflowing with values near the lower implementation bound (:issue:`55979`) - Bug in adding or subtracting a :class:`Week` offset to a ``datetime64`` :class:`Series`, :class:`Index`, or :class:`DataFrame` column with non-nanosecond resolution returning incorrect results (:issue:`55583`) - Bug in addition or subtraction of :class:`BusinessDay` offset with ``offset`` attribute to non-nanosecond :class:`Index`, :class:`Series`, or :class:`DataFrame` column giving incorrect results (:issue:`55608`) diff --git a/pandas/_libs/src/vendored/numpy/datetime/np_datetime_strings.c b/pandas/_libs/src/vendored/numpy/datetime/np_datetime_strings.c index a0d56efc14bd9..3a9a805a9ec45 100644 --- a/pandas/_libs/src/vendored/numpy/datetime/np_datetime_strings.c +++ b/pandas/_libs/src/vendored/numpy/datetime/np_datetime_strings.c @@ -364,6 +364,7 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, goto parse_error; } out->hour = (*substr - '0'); + bestunit = NPY_FR_h; ++substr; --sublen; /* Second digit optional */ @@ -425,6 +426,7 @@ int parse_iso_8601_datetime(const char *str, int len, int want_exc, } /* First digit required */ out->min = (*substr - '0'); + bestunit = NPY_FR_m; ++substr; --sublen; /* Second digit optional if there was a separator */ diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py index 0201e5d9af2ee..91314a497b1fb 100644 --- a/pandas/tests/scalar/timestamp/test_constructors.py +++ b/pandas/tests/scalar/timestamp/test_constructors.py @@ -457,6 +457,13 @@ def test_constructor_str_infer_reso(self): assert ts == Timestamp("01-01-2013T00:00:00.000000002+0000") assert ts.unit == "ns" + # GH#56208 minute reso through the ISO8601 path with tz offset + ts = Timestamp("2020-01-01 00:00+00:00") + assert ts.unit == "s" + + ts = Timestamp("2020-01-01 00+00:00") + assert ts.unit == "s" + class TestTimestampConstructors: def test_weekday_but_no_day_raises(self):
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/56208
2023-11-27T17:54:04Z
2023-11-27T21:17:14Z
2023-11-27T21:17:14Z
2023-11-27T22:03:04Z
WEB: Better management of releases
diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml index af452363666b5..4e88bfff69327 100644 --- a/.github/workflows/docbuild-and-upload.yml +++ b/.github/workflows/docbuild-and-upload.yml @@ -46,6 +46,9 @@ jobs: - name: Build Pandas uses: ./.github/actions/build_pandas + - name: Test website + run: python -m pytest web/ + - name: Build website run: python web/pandas_web.py web/pandas --target-path=web/build diff --git a/web/pandas_web.py b/web/pandas_web.py index 1cd3be456bfe0..58b5c287791c1 100755 --- a/web/pandas_web.py +++ b/web/pandas_web.py @@ -27,6 +27,7 @@ import collections import datetime import importlib +import itertools import json import operator import os @@ -40,6 +41,7 @@ import feedparser import jinja2 import markdown +from packaging import version import requests import yaml @@ -240,6 +242,7 @@ def home_add_releases(context): context["releases"].append( { "name": release["tag_name"].lstrip("v"), + "parsed_version": version.parse(release["tag_name"].lstrip("v")), "tag": release["tag_name"], "published": published, "url": ( @@ -249,7 +252,17 @@ def home_add_releases(context): ), } ) - + # sorting out obsolete versions + grouped_releases = itertools.groupby( + context["releases"], + key=lambda r: (r["parsed_version"].major, r["parsed_version"].minor), + ) + context["releases"] = [ + max(release_group, key=lambda r: r["parsed_version"].minor) + for _, release_group in grouped_releases + ] + # sorting releases by version number + context["releases"].sort(key=lambda r: r["parsed_version"], reverse=True) return context @staticmethod diff --git a/web/tests/test_pandas_web.py b/web/tests/test_pandas_web.py new file mode 100644 index 0000000000000..827c1d4dbea40 --- /dev/null +++ b/web/tests/test_pandas_web.py @@ -0,0 +1,88 @@ +from unittest.mock import ( + mock_open, + patch, +) + +import pytest +import requests + +from web.pandas_web import Preprocessors + + +class MockResponse: + def __init__(self, status_code: int, response: dict): + self.status_code = status_code + self._resp = response + + def json(self): + return self._resp + + @staticmethod + def raise_for_status(): + return + + +@pytest.fixture +def context() -> dict: + return { + "main": {"github_repo_url": "pandas-dev/pandas"}, + "target_path": "test_target_path", + } + + +@pytest.fixture(scope="function") +def mock_response(monkeypatch, request): + def mocked_resp(*args, **kwargs): + status_code, response = request.param + return MockResponse(status_code, response) + + monkeypatch.setattr(requests, "get", mocked_resp) + + +_releases_list = [ + { + "prerelease": False, + "published_at": "2024-01-19T03:34:05Z", + "tag_name": "v1.5.6", + "assets": None, + }, + { + "prerelease": False, + "published_at": "2023-11-10T19:07:37Z", + "tag_name": "v2.1.3", + "assets": None, + }, + { + "prerelease": False, + "published_at": "2023-08-30T13:24:32Z", + "tag_name": "v2.1.0", + "assets": None, + }, + { + "prerelease": False, + "published_at": "2023-04-30T13:24:32Z", + "tag_name": "v2.0.0", + "assets": None, + }, + { + "prerelease": True, + "published_at": "2023-01-19T03:34:05Z", + "tag_name": "v1.5.3xd", + "assets": None, + }, + { + "prerelease": False, + "published_at": "2027-01-19T03:34:05Z", + "tag_name": "v10.0.1", + "assets": None, + }, +] + + +@pytest.mark.parametrize("mock_response", [(200, _releases_list)], indirect=True) +def test_web_preprocessor_creates_releases(mock_response, context): + m = mock_open() + with patch("builtins.open", m): + context = Preprocessors.home_add_releases(context) + release_versions = [release["name"] for release in context["releases"]] + assert release_versions == ["10.0.1", "2.1.3", "2.0.0", "1.5.6"]
Added releases sorting by version number and sorting out obsolete releases in web/pandas_web.py - [ ] closes #50885 - [x] Tests added and passed - [x] All code checks passed
https://api.github.com/repos/pandas-dev/pandas/pulls/56207
2023-11-27T17:47:50Z
2023-12-13T05:22:55Z
2023-12-13T05:22:55Z
2023-12-13T05:23:24Z
CI: Fix ci
diff --git a/pandas/tests/copy_view/test_chained_assignment_deprecation.py b/pandas/tests/copy_view/test_chained_assignment_deprecation.py index 37431f39bdaa0..55781370a5a59 100644 --- a/pandas/tests/copy_view/test_chained_assignment_deprecation.py +++ b/pandas/tests/copy_view/test_chained_assignment_deprecation.py @@ -36,7 +36,7 @@ def test_methods_iloc_warn(using_copy_on_write): def test_methods_iloc_getitem_item_cache(func, args, using_copy_on_write): df = DataFrame({"a": [1, 2, 3], "b": 1}) ser = df.iloc[:, 0] - TODO(CoW-warn) should warn about updating a view + # TODO(CoW-warn) should warn about updating a view getattr(ser, func)(*args, inplace=True) # parent that holds item_cache is dead, so don't increase ref count
cc @jorisvandenbossche merging this to get ci green again
https://api.github.com/repos/pandas-dev/pandas/pulls/56205
2023-11-27T14:25:44Z
2023-11-27T14:26:05Z
2023-11-27T14:26:05Z
2023-11-27T14:34:52Z
TST/CLN: Remove makeMixedDataFrame and getMixedTypeDict
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index c73d869b6c39c..14ee29d24800e 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -482,23 +482,6 @@ def makeDataFrame() -> DataFrame: return DataFrame(data) -def getMixedTypeDict(): - index = Index(["a", "b", "c", "d", "e"]) - - data = { - "A": [0.0, 1.0, 2.0, 3.0, 4.0], - "B": [0.0, 1.0, 0.0, 1.0, 0.0], - "C": ["foo1", "foo2", "foo3", "foo4", "foo5"], - "D": bdate_range("1/1/2009", periods=5), - } - - return index, data - - -def makeMixedDataFrame() -> DataFrame: - return DataFrame(getMixedTypeDict()[1]) - - def makeCustomIndex( nentries, nlevels, @@ -1026,7 +1009,6 @@ def shares_memory(left, right) -> bool: "get_dtype", "getitem", "get_locales", - "getMixedTypeDict", "get_finest_unit", "get_obj", "get_op_from_name", @@ -1042,7 +1024,6 @@ def shares_memory(left, right) -> bool: "makeDateIndex", "makeFloatIndex", "makeIntIndex", - "makeMixedDataFrame", "makeNumericIndex", "makeObjectSeries", "makePeriodIndex", diff --git a/pandas/tests/frame/methods/test_transpose.py b/pandas/tests/frame/methods/test_transpose.py index 93a2f8d80019c..d0caa071fae1c 100644 --- a/pandas/tests/frame/methods/test_transpose.py +++ b/pandas/tests/frame/methods/test_transpose.py @@ -6,9 +6,11 @@ from pandas import ( DataFrame, DatetimeIndex, + Index, IntervalIndex, Series, Timestamp, + bdate_range, date_range, timedelta_range, ) @@ -108,9 +110,17 @@ def test_transpose_float(self, float_frame): else: assert value == frame[col][idx] + def test_transpose_mixed(self): # mixed type - index, data = tm.getMixedTypeDict() - mixed = DataFrame(data, index=index) + mixed = DataFrame( + { + "A": [0.0, 1.0, 2.0, 3.0, 4.0], + "B": [0.0, 1.0, 0.0, 1.0, 0.0], + "C": ["foo1", "foo2", "foo3", "foo4", "foo5"], + "D": bdate_range("1/1/2009", periods=5), + }, + index=Index(["a", "b", "c", "d", "e"], dtype=object), + ) mixed_T = mixed.T for col, s in mixed_T.items(): diff --git a/pandas/tests/io/pytables/test_append.py b/pandas/tests/io/pytables/test_append.py index 50cf7d737eb99..89a0162af1c54 100644 --- a/pandas/tests/io/pytables/test_append.py +++ b/pandas/tests/io/pytables/test_append.py @@ -397,7 +397,14 @@ def check_col(key, name, size): store.append("df_new", df_new) # min_itemsize on Series index (GH 11412) - df = tm.makeMixedDataFrame().set_index("C") + df = DataFrame( + { + "A": [0.0, 1.0, 2.0, 3.0, 4.0], + "B": [0.0, 1.0, 0.0, 1.0, 0.0], + "C": pd.Index(["foo1", "foo2", "foo3", "foo4", "foo5"], dtype=object), + "D": date_range("20130101", periods=5), + } + ).set_index("C") store.append("ss", df["B"], min_itemsize={"index": 4}) tm.assert_series_equal(store.select("ss"), df["B"]) diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index df8a1e3cb7470..5b16ea9ee6b09 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -323,7 +323,14 @@ def test_to_hdf_with_min_itemsize(tmp_path, setup_path): path = tmp_path / setup_path # min_itemsize in index with to_hdf (GH 10381) - df = tm.makeMixedDataFrame().set_index("C") + df = DataFrame( + { + "A": [0.0, 1.0, 2.0, 3.0, 4.0], + "B": [0.0, 1.0, 0.0, 1.0, 0.0], + "C": Index(["foo1", "foo2", "foo3", "foo4", "foo5"], dtype=object), + "D": date_range("20130101", periods=5), + } + ).set_index("C") df.to_hdf(path, key="ss3", format="table", min_itemsize={"index": 6}) # just make sure there is a longer string: df2 = df.copy().reset_index().assign(C="longer").set_index("C") diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index c4c83e2046b76..f07c223bf0de2 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -11,6 +11,7 @@ MultiIndex, Series, Timestamp, + bdate_range, concat, merge, ) @@ -57,8 +58,13 @@ def df2(self): @pytest.fixture def target_source(self): - index, data = tm.getMixedTypeDict() - target = DataFrame(data, index=index) + data = { + "A": [0.0, 1.0, 2.0, 3.0, 4.0], + "B": [0.0, 1.0, 0.0, 1.0, 0.0], + "C": ["foo1", "foo2", "foo3", "foo4", "foo5"], + "D": bdate_range("1/1/2009", periods=5), + } + target = DataFrame(data, index=Index(["a", "b", "c", "d", "e"], dtype=object)) # Join on string value diff --git a/pandas/tests/series/methods/test_map.py b/pandas/tests/series/methods/test_map.py index f86f6069a2ef3..7b14e1289abf0 100644 --- a/pandas/tests/series/methods/test_map.py +++ b/pandas/tests/series/methods/test_map.py @@ -14,6 +14,7 @@ Index, MultiIndex, Series, + bdate_range, isna, timedelta_range, ) @@ -154,8 +155,13 @@ def test_list_raises(string_series): string_series.map([lambda x: x]) -def test_map(datetime_series): - index, data = tm.getMixedTypeDict() +def test_map(): + data = { + "A": [0.0, 1.0, 2.0, 3.0, 4.0], + "B": [0.0, 1.0, 0.0, 1.0, 0.0], + "C": ["foo1", "foo2", "foo3", "foo4", "foo5"], + "D": bdate_range("1/1/2009", periods=5), + } source = Series(data["B"], index=data["C"]) target = Series(data["C"][:4], index=data["D"][:4]) @@ -171,10 +177,14 @@ def test_map(datetime_series): for k, v in merged.items(): assert v == source[target[k]] + +def test_map_datetime(datetime_series): # function result = datetime_series.map(lambda x: x * 2) tm.assert_series_equal(result, datetime_series * 2) + +def test_map_category(): # GH 10324 a = Series([1, 2, 3, 4]) b = Series(["even", "odd", "even", "odd"], dtype="category") @@ -185,6 +195,8 @@ def test_map(datetime_series): exp = Series(["odd", "even", "odd", np.nan]) tm.assert_series_equal(a.map(c), exp) + +def test_map_category_numeric(): a = Series(["a", "b", "c", "d"]) b = Series([1, 2, 3, 4], index=pd.CategoricalIndex(["b", "c", "d", "e"])) c = Series([1, 2, 3, 4], index=Index(["b", "c", "d", "e"])) @@ -194,6 +206,8 @@ def test_map(datetime_series): exp = Series([np.nan, 1, 2, 3]) tm.assert_series_equal(a.map(c), exp) + +def test_map_category_string(): a = Series(["a", "b", "c", "d"]) b = Series( ["B", "C", "D", "E"], diff --git a/pandas/tests/util/test_hashing.py b/pandas/tests/util/test_hashing.py index e7c4c27714d5f..5f1d905aa4a46 100644 --- a/pandas/tests/util/test_hashing.py +++ b/pandas/tests/util/test_hashing.py @@ -136,7 +136,14 @@ def test_multiindex_objects(): DataFrame({"x": ["a", "b", "c"], "y": [1, 2, 3]}), DataFrame(), DataFrame(np.full((10, 4), np.nan)), - tm.makeMixedDataFrame(), + DataFrame( + { + "A": [0.0, 1.0, 2.0, 3.0, 4.0], + "B": [0.0, 1.0, 0.0, 1.0, 0.0], + "C": Index(["foo1", "foo2", "foo3", "foo4", "foo5"], dtype=object), + "D": pd.date_range("20130101", periods=5), + } + ), tm.makeTimeDataFrame(), tm.makeTimeSeries(), Series(tm.makePeriodIndex()), @@ -162,7 +169,14 @@ def test_hash_pandas_object(obj, index): Series([True, False, True]), DataFrame({"x": ["a", "b", "c"], "y": [1, 2, 3]}), DataFrame(np.full((10, 4), np.nan)), - tm.makeMixedDataFrame(), + DataFrame( + { + "A": [0.0, 1.0, 2.0, 3.0, 4.0], + "B": [0.0, 1.0, 0.0, 1.0, 0.0], + "C": Index(["foo1", "foo2", "foo3", "foo4", "foo5"], dtype=object), + "D": pd.date_range("20130101", periods=5), + } + ), tm.makeTimeDataFrame(), tm.makeTimeSeries(), Series(tm.makePeriodIndex()),
null
https://api.github.com/repos/pandas-dev/pandas/pulls/56202
2023-11-27T03:42:20Z
2023-11-27T11:15:40Z
2023-11-27T11:15:40Z
2024-01-30T21:09:31Z
DOC: Add clarifications to docs for setting up a development environment
diff --git a/doc/source/development/contributing_environment.rst b/doc/source/development/contributing_environment.rst index 7fc42f6021f00..325c902dd4f9e 100644 --- a/doc/source/development/contributing_environment.rst +++ b/doc/source/development/contributing_environment.rst @@ -44,8 +44,9 @@ and consult the ``Linux`` instructions below. **macOS** To use the :ref:`mamba <contributing.mamba>`-based compilers, you will need to install the -Developer Tools using ``xcode-select --install``. Otherwise -information about compiler installation can be found here: +Developer Tools using ``xcode-select --install``. + +If you prefer to use a different compiler, general information can be found here: https://devguide.python.org/setup/#macos **Linux** @@ -86,12 +87,12 @@ Before we begin, please: Option 1: using mamba (recommended) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -* Install `mamba <https://mamba.readthedocs.io/en/latest/installation/mamba-installation.html>`_ +* Install miniforge to get `mamba <https://mamba.readthedocs.io/en/latest/installation/mamba-installation.html>`_ * Make sure your mamba is up to date (``mamba update mamba``) +* Create and activate the ``pandas-dev`` mamba environment using the following commands: .. code-block:: none - # Create and activate the build environment mamba env create --file environment.yml mamba activate pandas-dev @@ -273,6 +274,8 @@ uses to import the extension from the build folder, which may cause errors such You will need to repeat this step each time the C extensions change, for example if you modified any file in ``pandas/_libs`` or if you did a fetch and merge from ``upstream/main``. +**Checking the build** + At this point you should be able to import pandas from your locally built version:: $ python @@ -280,6 +283,12 @@ At this point you should be able to import pandas from your locally built versio >>> print(pandas.__version__) # note: the exact output may differ 2.0.0.dev0+880.g2b9e661fbb.dirty + +At this point you may want to try +`running the test suite <https://pandas.pydata.org/docs/dev/development/contributing_codebase.html#running-the-test-suite>`_. + +**Keeping up to date with the latest build** + When building pandas with meson, importing pandas will automatically trigger a rebuild, even when C/Cython files are modified. By default, no output will be produced by this rebuild (the import will just take longer). If you would like to see meson's output when importing pandas, you can set the environment variable ``MESONPY_EDTIABLE_VERBOSE``. For example, this would be::
Hi all - having just been through the setup process (Mac, mamba) and as a non-expert I thought I'd feed back some things that would have made my experience faster and smoother. --- **Change 1** - It wasn't 100% clear to me that I did **_not_** need to use any information from the link `https://devguide.python.org/setup/#macos` (it is clear with hindsight, but it's the initial impression that I'm trying to improve here): Before this change: <kbd><img width="750" alt="image" src="https://github.com/pandas-dev/pandas/assets/122238526/c72c8c93-4b70-4918-bdfe-557c859d40a7"></kbd> After: <kbd><img width="683" alt="image" src="https://github.com/pandas-dev/pandas/assets/122238526/8025886f-4d85-4987-b29b-398897662035"></kbd> --- **Change 2** - I got confused by `mamba` vs `conda`, and that you actually need to install is called `miniforge` - I had a moment of doubt here that I was on the wrong track. Before this change: <kbd><img width="617" alt="image" src="https://github.com/pandas-dev/pandas/assets/122238526/bd87599c-30a0-4f88-8a11-087cb8824dbf"></kbd> <kbd><img width="729" alt="image" src="https://github.com/pandas-dev/pandas/assets/122238526/123675ee-e30e-4385-99b3-5c085613de99"></kbd> --- **Change 3** - I found that I had some old packages that were used in my mamba environment (probably from a previous install of mamba - last I played with this was about a year ago). Looking into them, they were packages like `sphinx` that did not have a version pinned in `environment.yml`. This feels like it could be a source of errors for people getting set up. After: <kbd><img width="769" alt="image" src="https://github.com/pandas-dev/pandas/assets/122238526/395165e2-3b39-4a5a-9f7f-d377319a2453"></kbd> --- **Change 4** - Sounds strange, but I wasn't sure when I was actually 'done' with getting set up. - I tend to like to run unit tests when I get set up with a new repo. - I didn't realize that with this setup some of the unit tests (the ones with external dependencies) were expected to fail, as helpfully documented [here](https://pandas.pydata.org/docs/dev/development/contributing_codebase.html#running-the-test-suite). I feel this is really important - I lost a lot of time because I assumed there must be something wrong with my install because unit tests were failing. By adding the link here hopefully others see this information sooner. Before this change: <kbd><img width="776" alt="image" src="https://github.com/pandas-dev/pandas/assets/122238526/7e689a9d-86db-4a28-96f5-46322f33c417"></kbd> After: <kbd><img width="791" alt="image" src="https://github.com/pandas-dev/pandas/assets/122238526/079ce0c7-bc8b-4359-a03e-fa4e0f35c71e"></kbd> --- - [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/56201
2023-11-27T03:29:52Z
2023-11-28T15:34:39Z
2023-11-28T15:34:39Z
2023-11-28T15:34:47Z
TST/CLN: Remove makeUInt/Timedelta/RangeIndex
diff --git a/pandas/_testing/__init__.py b/pandas/_testing/__init__.py index 14ee29d24800e..d30929d07245b 100644 --- a/pandas/_testing/__init__.py +++ b/pandas/_testing/__init__.py @@ -47,6 +47,7 @@ RangeIndex, Series, bdate_range, + timedelta_range, ) from pandas._testing._io import ( round_trip_localpath, @@ -111,10 +112,7 @@ NpDtype, ) - from pandas import ( - PeriodIndex, - TimedeltaIndex, - ) + from pandas import PeriodIndex from pandas.core.arrays import ArrowExtensionArray _N = 30 @@ -405,17 +403,6 @@ def makeIntIndex(k: int = 10, *, name=None, dtype: Dtype = "int64") -> Index: return makeNumericIndex(k, name=name, dtype=dtype) -def makeUIntIndex(k: int = 10, *, name=None, dtype: Dtype = "uint64") -> Index: - dtype = pandas_dtype(dtype) - if not is_unsigned_integer_dtype(dtype): - raise TypeError(f"Wrong dtype {dtype}") - return makeNumericIndex(k, name=name, dtype=dtype) - - -def makeRangeIndex(k: int = 10, name=None, **kwargs) -> RangeIndex: - return RangeIndex(0, k, 1, name=name, **kwargs) - - def makeFloatIndex(k: int = 10, *, name=None, dtype: Dtype = "float64") -> Index: dtype = pandas_dtype(dtype) if not is_float_dtype(dtype): @@ -431,12 +418,6 @@ def makeDateIndex( return DatetimeIndex(dr, name=name, **kwargs) -def makeTimedeltaIndex( - k: int = 10, freq: Frequency = "D", name=None, **kwargs -) -> TimedeltaIndex: - return pd.timedelta_range(start="1 day", periods=k, freq=freq, name=name, **kwargs) - - def makePeriodIndex(k: int = 10, name=None, **kwargs) -> PeriodIndex: dt = datetime(2000, 1, 1) pi = pd.period_range(start=dt, periods=k, freq="D", name=name, **kwargs) @@ -537,7 +518,7 @@ def makeCustomIndex( "f": makeFloatIndex, "s": lambda n: Index([f"{i}_{chr(i)}" for i in range(97, 97 + n)]), "dt": makeDateIndex, - "td": makeTimedeltaIndex, + "td": lambda n: timedelta_range("1 day", periods=n), "p": makePeriodIndex, } idx_func = idx_func_dict.get(idx_type) @@ -1027,11 +1008,8 @@ def shares_memory(left, right) -> bool: "makeNumericIndex", "makeObjectSeries", "makePeriodIndex", - "makeRangeIndex", "makeTimeDataFrame", - "makeTimedeltaIndex", "makeTimeSeries", - "makeUIntIndex", "maybe_produces_warning", "NARROW_NP_DTYPES", "NP_NAT_OBJECTS", diff --git a/pandas/conftest.py b/pandas/conftest.py index 3205b6657439f..a7e05d3ebddc5 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -63,9 +63,11 @@ Interval, IntervalIndex, Period, + RangeIndex, Series, Timedelta, Timestamp, + timedelta_range, ) import pandas._testing as tm from pandas.core import ops @@ -614,16 +616,16 @@ def _create_mi_with_dt64tz_level(): "datetime": tm.makeDateIndex(100), "datetime-tz": tm.makeDateIndex(100, tz="US/Pacific"), "period": tm.makePeriodIndex(100), - "timedelta": tm.makeTimedeltaIndex(100), - "range": tm.makeRangeIndex(100), + "timedelta": timedelta_range(start="1 day", periods=100, freq="D"), + "range": RangeIndex(100), "int8": tm.makeIntIndex(100, dtype="int8"), "int16": tm.makeIntIndex(100, dtype="int16"), "int32": tm.makeIntIndex(100, dtype="int32"), "int64": tm.makeIntIndex(100, dtype="int64"), - "uint8": tm.makeUIntIndex(100, dtype="uint8"), - "uint16": tm.makeUIntIndex(100, dtype="uint16"), - "uint32": tm.makeUIntIndex(100, dtype="uint32"), - "uint64": tm.makeUIntIndex(100, dtype="uint64"), + "uint8": Index(np.arange(100), dtype="uint8"), + "uint16": Index(np.arange(100), dtype="uint16"), + "uint32": Index(np.arange(100), dtype="uint32"), + "uint64": Index(np.arange(100), dtype="uint64"), "float32": tm.makeFloatIndex(100, dtype="float32"), "float64": tm.makeFloatIndex(100, dtype="float64"), "bool-object": Index([True, False] * 5, dtype=object), diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 0d71fb0926df9..17d42506aaded 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -18,7 +18,10 @@ Categorical, CategoricalDtype, DataFrame, + DatetimeIndex, Index, + PeriodIndex, + RangeIndex, Series, Timestamp, date_range, @@ -598,7 +601,7 @@ def test_sem(self, datetime_frame): "C": [1.0], "D": ["a"], "E": Categorical(["a"], categories=["a"]), - "F": pd.DatetimeIndex(["2000-01-02"], dtype="M8[ns]"), + "F": DatetimeIndex(["2000-01-02"], dtype="M8[ns]"), "G": to_timedelta(["1 days"]), }, ), @@ -610,7 +613,7 @@ def test_sem(self, datetime_frame): "C": [np.nan], "D": np.array([np.nan], dtype=object), "E": Categorical([np.nan], categories=["a"]), - "F": pd.DatetimeIndex([pd.NaT], dtype="M8[ns]"), + "F": DatetimeIndex([pd.NaT], dtype="M8[ns]"), "G": to_timedelta([pd.NaT]), }, ), @@ -621,7 +624,7 @@ def test_sem(self, datetime_frame): "I": [8, 9, np.nan, np.nan], "J": [1, np.nan, np.nan, np.nan], "K": Categorical(["a", np.nan, np.nan, np.nan], categories=["a"]), - "L": pd.DatetimeIndex( + "L": DatetimeIndex( ["2000-01-02", "NaT", "NaT", "NaT"], dtype="M8[ns]" ), "M": to_timedelta(["1 days", "nan", "nan", "nan"]), @@ -635,7 +638,7 @@ def test_sem(self, datetime_frame): "I": [8, 9, np.nan, np.nan], "J": [1, np.nan, np.nan, np.nan], "K": Categorical([np.nan, "a", np.nan, np.nan], categories=["a"]), - "L": pd.DatetimeIndex( + "L": DatetimeIndex( ["NaT", "2000-01-02", "NaT", "NaT"], dtype="M8[ns]" ), "M": to_timedelta(["nan", "1 days", "nan", "nan"]), @@ -652,15 +655,13 @@ def test_mode_dropna(self, dropna, expected): "C": [1, np.nan, np.nan, np.nan], "D": [np.nan, np.nan, "a", np.nan], "E": Categorical([np.nan, np.nan, "a", np.nan]), - "F": pd.DatetimeIndex( - ["NaT", "2000-01-02", "NaT", "NaT"], dtype="M8[ns]" - ), + "F": DatetimeIndex(["NaT", "2000-01-02", "NaT", "NaT"], dtype="M8[ns]"), "G": to_timedelta(["1 days", "nan", "nan", "nan"]), "H": [8, 8, 9, 9], "I": [9, 9, 8, 8], "J": [1, 1, np.nan, np.nan], "K": Categorical(["a", np.nan, "a", np.nan]), - "L": pd.DatetimeIndex( + "L": DatetimeIndex( ["2000-01-02", "2000-01-02", "NaT", "NaT"], dtype="M8[ns]" ), "M": to_timedelta(["1 days", "nan", "1 days", "nan"]), @@ -830,15 +831,15 @@ def test_sum_corner(self): @pytest.mark.parametrize( "index", [ - tm.makeRangeIndex(0), - tm.makeDateIndex(0), - tm.makeNumericIndex(0, dtype=int), - tm.makeNumericIndex(0, dtype=float), - tm.makeDateIndex(0, freq="ME"), - tm.makePeriodIndex(0), + RangeIndex(0), + DatetimeIndex([]), + Index([], dtype=np.int64), + Index([], dtype=np.float64), + DatetimeIndex([], freq="ME"), + PeriodIndex([], freq="D"), ], ) - def test_axis_1_empty(self, all_reductions, index, using_array_manager): + def test_axis_1_empty(self, all_reductions, index): df = DataFrame(columns=["a"], index=index) result = getattr(df, all_reductions)(axis=1) if all_reductions in ("any", "all"): diff --git a/pandas/tests/indexes/datetimelike_/test_equals.py b/pandas/tests/indexes/datetimelike_/test_equals.py index 7845d99614d34..fc9fbd33d0d28 100644 --- a/pandas/tests/indexes/datetimelike_/test_equals.py +++ b/pandas/tests/indexes/datetimelike_/test_equals.py @@ -18,6 +18,7 @@ TimedeltaIndex, date_range, period_range, + timedelta_range, ) import pandas._testing as tm @@ -141,7 +142,7 @@ def test_not_equals_bday(self, freq): class TestTimedeltaIndexEquals(EqualsTests): @pytest.fixture def index(self): - return tm.makeTimedeltaIndex(10) + return timedelta_range("1 day", periods=10) def test_equals2(self): # GH#13107 diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 8e11fc28cc387..662f31cc3560e 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -30,6 +30,7 @@ TimedeltaIndex, date_range, period_range, + timedelta_range, ) import pandas._testing as tm from pandas.core.indexes.api import ( @@ -92,7 +93,7 @@ def test_constructor_copy(self, index): name="Green Eggs & Ham", ), # DTI with tz date_range("2015-01-01 10:00", freq="D", periods=3), # DTI no tz - pd.timedelta_range("1 days", freq="D", periods=3), # td + timedelta_range("1 days", freq="D", periods=3), # td period_range("2015-01-01", freq="D", periods=3), # period ], ) @@ -122,7 +123,7 @@ def test_constructor_from_index_dtlike(self, cast_as_obj, index): date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern"), True, ), # datetimetz - (pd.timedelta_range("1 days", freq="D", periods=3), False), # td + (timedelta_range("1 days", freq="D", periods=3), False), # td (period_range("2015-01-01", freq="D", periods=3), False), # period ], ) @@ -267,7 +268,7 @@ def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass): @pytest.mark.parametrize("attr", ["values", "asi8"]) @pytest.mark.parametrize("klass", [Index, TimedeltaIndex]) def test_constructor_dtypes_timedelta(self, attr, klass): - index = pd.timedelta_range("1 days", periods=5) + index = timedelta_range("1 days", periods=5) index = index._with_freq(None) # won't be preserved by constructors dtype = index.dtype @@ -526,10 +527,14 @@ def test_map_with_tuples_mi(self): tm.assert_index_equal(reduced_index, Index(first_level)) @pytest.mark.parametrize( - "attr", ["makeDateIndex", "makePeriodIndex", "makeTimedeltaIndex"] + "index", + [ + date_range("2020-01-01", freq="D", periods=10), + period_range("2020-01-01", freq="D", periods=10), + timedelta_range("1 day", periods=10), + ], ) - def test_map_tseries_indices_return_index(self, attr): - index = getattr(tm, attr)(10) + def test_map_tseries_indices_return_index(self, index): expected = Index([1] * 10) result = index.map(lambda x: 1) tm.assert_index_equal(expected, result) diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py index dab2475240267..a489c51a808fd 100644 --- a/pandas/tests/indexes/test_setops.py +++ b/pandas/tests/indexes/test_setops.py @@ -139,19 +139,16 @@ def test_union_different_types(index_flat, index_flat2, request): @pytest.mark.parametrize( - "idx_fact1,idx_fact2", + "idx1,idx2", [ - (tm.makeIntIndex, tm.makeRangeIndex), - (tm.makeFloatIndex, tm.makeIntIndex), - (tm.makeFloatIndex, tm.makeRangeIndex), - (tm.makeFloatIndex, tm.makeUIntIndex), + (Index(np.arange(5), dtype=np.int64), RangeIndex(5)), + (Index(np.arange(5), dtype=np.float64), Index(np.arange(5), dtype=np.int64)), + (Index(np.arange(5), dtype=np.float64), RangeIndex(5)), + (Index(np.arange(5), dtype=np.float64), Index(np.arange(5), dtype=np.uint64)), ], ) -def test_compatible_inconsistent_pairs(idx_fact1, idx_fact2): +def test_compatible_inconsistent_pairs(idx1, idx2): # GH 23525 - idx1 = idx_fact1(10) - idx2 = idx_fact2(20) - res1 = idx1.union(idx2) res2 = idx2.union(idx1) diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py index cf9966145afce..1fe431e12f2a1 100644 --- a/pandas/tests/indexing/test_floats.py +++ b/pandas/tests/indexing/test_floats.py @@ -132,14 +132,16 @@ def test_scalar_with_mixed(self, indexer_sl): expected = 3 assert result == expected - @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex]) - def test_scalar_integer(self, index_func, frame_or_series, indexer_sl): + @pytest.mark.parametrize( + "index", [Index(np.arange(5), dtype=np.int64), RangeIndex(5)] + ) + def test_scalar_integer(self, index, frame_or_series, indexer_sl): getitem = indexer_sl is not tm.loc # test how scalar float indexers work on int indexes # integer index - i = index_func(5) + i = index obj = gen_obj(frame_or_series, i) # coerce to equal int @@ -169,11 +171,12 @@ def compare(x, y): result = indexer_sl(s2)[3] compare(result, expected) - @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex]) - def test_scalar_integer_contains_float(self, index_func, frame_or_series): + @pytest.mark.parametrize( + "index", [Index(np.arange(5), dtype=np.int64), RangeIndex(5)] + ) + def test_scalar_integer_contains_float(self, index, frame_or_series): # contains # integer index - index = index_func(5) obj = gen_obj(frame_or_series, index) # coerce to equal int @@ -348,11 +351,11 @@ def test_integer_positional_indexing(self, idx): with pytest.raises(TypeError, match=msg): s.iloc[idx] - @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex]) - def test_slice_integer_frame_getitem(self, index_func): + @pytest.mark.parametrize( + "index", [Index(np.arange(5), dtype=np.int64), RangeIndex(5)] + ) + def test_slice_integer_frame_getitem(self, index): # similar to above, but on the getitem dim (of a DataFrame) - index = index_func(5) - s = DataFrame(np.random.default_rng(2).standard_normal((5, 2)), index=index) # getitem @@ -403,11 +406,11 @@ def test_slice_integer_frame_getitem(self, index_func): s[idx] @pytest.mark.parametrize("idx", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)]) - @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex]) - def test_float_slice_getitem_with_integer_index_raises(self, idx, index_func): + @pytest.mark.parametrize( + "index", [Index(np.arange(5), dtype=np.int64), RangeIndex(5)] + ) + def test_float_slice_getitem_with_integer_index_raises(self, idx, index): # similar to above, but on the getitem dim (of a DataFrame) - index = index_func(5) - s = DataFrame(np.random.default_rng(2).standard_normal((5, 2)), index=index) # setitem diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 5b16ea9ee6b09..7e8365a8f9ffa 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -17,6 +17,7 @@ Timestamp, concat, date_range, + period_range, timedelta_range, ) import pandas._testing as tm @@ -953,25 +954,23 @@ def test_columns_multiindex_modified(tmp_path, setup_path): @pytest.mark.filterwarnings(r"ignore:PeriodDtype\[B\] is deprecated:FutureWarning") -def test_to_hdf_with_object_column_names(tmp_path, setup_path): +@pytest.mark.parametrize( + "columns", + [ + Index([0, 1], dtype=np.int64), + Index([0.0, 1.0], dtype=np.float64), + date_range("2020-01-01", periods=2), + timedelta_range("1 day", periods=2), + period_range("2020-01-01", periods=2, freq="D"), + ], +) +def test_to_hdf_with_object_column_names_should_fail(tmp_path, setup_path, columns): # GH9057 - - types_should_fail = [ - tm.makeIntIndex, - tm.makeFloatIndex, - tm.makeDateIndex, - tm.makeTimedeltaIndex, - tm.makePeriodIndex, - ] - - for index in types_should_fail: - df = DataFrame( - np.random.default_rng(2).standard_normal((10, 2)), columns=index(2) - ) - path = tmp_path / setup_path - msg = "cannot have non-object label DataIndexableCol" - with pytest.raises(ValueError, match=msg): - df.to_hdf(path, key="df", format="table", data_columns=True) + df = DataFrame(np.random.default_rng(2).standard_normal((10, 2)), columns=columns) + path = tmp_path / setup_path + msg = "cannot have non-object label DataIndexableCol" + with pytest.raises(ValueError, match=msg): + df.to_hdf(path, key="df", format="table", data_columns=True) @pytest.mark.parametrize("dtype", [None, "category"]) diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 9d69321ff7dbb..3349b886bbef6 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -10,6 +10,7 @@ Index, Series, date_range, + timedelta_range, ) import pandas._testing as tm @@ -73,9 +74,9 @@ def test_tab_completion_with_categorical(self): Index(["foo", "bar", "baz"] * 2), tm.makeDateIndex(10), tm.makePeriodIndex(10), - tm.makeTimedeltaIndex(10), + timedelta_range("1 day", periods=10), tm.makeIntIndex(10), - tm.makeUIntIndex(10), + Index(np.arange(10), dtype=np.uint64), tm.makeIntIndex(10), tm.makeFloatIndex(10), Index([True, False]), @@ -178,7 +179,7 @@ def test_inspect_getmembers(self): def test_unknown_attribute(self): # GH#9680 - tdi = pd.timedelta_range(start=0, periods=10, freq="1s") + tdi = timedelta_range(start=0, periods=10, freq="1s") ser = Series(np.random.default_rng(2).normal(size=10), index=tdi) assert "foo" not in ser.__dict__ msg = "'Series' object has no attribute 'foo'" diff --git a/pandas/tests/tseries/frequencies/test_inference.py b/pandas/tests/tseries/frequencies/test_inference.py index 5d22896d9d055..45741e852fef7 100644 --- a/pandas/tests/tseries/frequencies/test_inference.py +++ b/pandas/tests/tseries/frequencies/test_inference.py @@ -17,12 +17,12 @@ from pandas import ( DatetimeIndex, Index, + RangeIndex, Series, Timestamp, date_range, period_range, ) -import pandas._testing as tm from pandas.core.arrays import ( DatetimeArray, TimedeltaArray, @@ -374,10 +374,10 @@ def test_non_datetime_index2(): @pytest.mark.parametrize( "idx", [ - tm.makeIntIndex(10), - tm.makeFloatIndex(10), - tm.makePeriodIndex(10), - tm.makeRangeIndex(10), + Index(np.arange(5), dtype=np.int64), + Index(np.arange(5), dtype=np.float64), + period_range("2020-01-01", periods=5), + RangeIndex(5), ], ) def test_invalid_index_types(idx): diff --git a/pandas/tests/util/test_hashing.py b/pandas/tests/util/test_hashing.py index 5f1d905aa4a46..0417c7a631da2 100644 --- a/pandas/tests/util/test_hashing.py +++ b/pandas/tests/util/test_hashing.py @@ -7,6 +7,8 @@ Index, MultiIndex, Series, + period_range, + timedelta_range, ) import pandas._testing as tm from pandas.core.util.hashing import hash_tuples @@ -25,7 +27,7 @@ Series([True, False, True] * 3), Series(pd.date_range("20130101", periods=9)), Series(pd.date_range("20130101", periods=9, tz="US/Eastern")), - Series(pd.timedelta_range("2000", periods=9)), + Series(timedelta_range("2000", periods=9)), ] ) def series(request): @@ -194,8 +196,8 @@ def test_hash_pandas_object_diff_index_non_empty(obj): [ Index([1, 2, 3]), Index([True, False, True]), - tm.makeTimedeltaIndex(), - tm.makePeriodIndex(), + timedelta_range("1 day", periods=2), + period_range("2020-01-01", freq="D", periods=2), MultiIndex.from_product( [range(5), ["foo", "bar", "baz"], pd.date_range("20130101", periods=2)] ),
null
https://api.github.com/repos/pandas-dev/pandas/pulls/56200
2023-11-27T03:03:05Z
2023-11-28T15:54:17Z
2023-11-28T15:54:17Z
2023-11-28T15:54:21Z
Backport PR #56194 on branch 2.1.x (BUG: hdf can't deal with ea dtype columns)
diff --git a/doc/source/whatsnew/v2.1.4.rst b/doc/source/whatsnew/v2.1.4.rst index eb28e42d303a1..684b68baa123c 100644 --- a/doc/source/whatsnew/v2.1.4.rst +++ b/doc/source/whatsnew/v2.1.4.rst @@ -24,6 +24,7 @@ Bug fixes - Bug in :meth:`DataFrame.apply` where passing ``raw=True`` ignored ``args`` passed to the applied function (:issue:`55753`) - Bug in :meth:`Index.__getitem__` returning wrong result for Arrow dtypes and negative stepsize (:issue:`55832`) - Fixed bug in :meth:`DataFrame.__setitem__` casting :class:`Index` with object-dtype to PyArrow backed strings when ``infer_string`` option is set (:issue:`55638`) +- Fixed bug in :meth:`DataFrame.to_hdf` raising when columns have ``StringDtype`` (:issue:`55088`) - Fixed bug in :meth:`Index.insert` casting object-dtype to PyArrow backed strings when ``infer_string`` option is set (:issue:`55638`) - Fixed bug in :meth:`Series.str.translate` losing object dtype when string option is set (:issue:`56152`) diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index d3055f0ad2a38..2a72f7d32b1e7 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -56,7 +56,6 @@ is_bool_dtype, is_complex_dtype, is_list_like, - is_object_dtype, is_string_dtype, needs_i8_conversion, ) @@ -2645,7 +2644,7 @@ class DataIndexableCol(DataCol): is_data_indexable = True def validate_names(self) -> None: - if not is_object_dtype(Index(self.values).dtype): + if not is_string_dtype(Index(self.values).dtype): # TODO: should the message here be more specifically non-str? raise ValueError("cannot have non-object label DataIndexableCol") diff --git a/pandas/tests/io/pytables/test_round_trip.py b/pandas/tests/io/pytables/test_round_trip.py index 085db5f521a9f..3bc8c0c4f8e30 100644 --- a/pandas/tests/io/pytables/test_round_trip.py +++ b/pandas/tests/io/pytables/test_round_trip.py @@ -526,3 +526,18 @@ def test_round_trip_equals(tmp_path, setup_path): tm.assert_frame_equal(df, other) assert df.equals(other) assert other.equals(df) + + +def test_infer_string_columns(tmp_path, setup_path): + # GH# + pytest.importorskip("pyarrow") + path = tmp_path / setup_path + with pd.option_context("future.infer_string", True): + df = DataFrame(1, columns=list("ABCD"), index=list(range(10))).set_index( + ["A", "B"] + ) + expected = df.copy() + df.to_hdf(path, key="df", format="table") + + result = read_hdf(path, "df") + tm.assert_frame_equal(result, expected)
Backport PR #56194: BUG: hdf can't deal with ea dtype columns
https://api.github.com/repos/pandas-dev/pandas/pulls/56199
2023-11-27T02:43:13Z
2023-11-27T11:09:55Z
2023-11-27T11:09:55Z
2023-11-27T11:09:56Z
Adjust tests in xml folder for new string option
diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py index 88655483800ee..e4456b0a78e06 100644 --- a/pandas/tests/io/xml/test_xml.py +++ b/pandas/tests/io/xml/test_xml.py @@ -32,6 +32,7 @@ ArrowStringArray, StringArray, ) +from pandas.core.arrays.string_arrow import ArrowStringArrayNumpySemantics from pandas.io.common import get_handle from pandas.io.xml import read_xml @@ -2004,7 +2005,9 @@ def test_s3_parser_consistency(s3_public_bucket_with_data, s3so): tm.assert_frame_equal(df_lxml, df_etree) -def test_read_xml_nullable_dtypes(parser, string_storage, dtype_backend): +def test_read_xml_nullable_dtypes( + parser, string_storage, dtype_backend, using_infer_string +): # GH#50500 data = """<?xml version='1.0' encoding='utf-8'?> <data xmlns="http://example.com"> @@ -2032,7 +2035,12 @@ def test_read_xml_nullable_dtypes(parser, string_storage, dtype_backend): </row> </data>""" - if string_storage == "python": + if using_infer_string: + pa = pytest.importorskip("pyarrow") + string_array = ArrowStringArrayNumpySemantics(pa.array(["x", "y"])) + string_array_na = ArrowStringArrayNumpySemantics(pa.array(["x", None])) + + elif string_storage == "python": string_array = StringArray(np.array(["x", "y"], dtype=np.object_)) string_array_na = StringArray(np.array(["x", NA], dtype=np.object_))
- [ ] closes #xxxx (Replace xxxx with the GitHub issue number) - [ ] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature - [ ] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit). - [ ] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions. - [ ] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.
https://api.github.com/repos/pandas-dev/pandas/pulls/56198
2023-11-26T23:40:07Z
2023-11-27T02:31:24Z
2023-11-27T02:31:24Z
2023-11-27T11:10:22Z
Adjust tests in json folder for new string option
diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index 79dbe448e9cbe..7569a74752bf2 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -56,7 +56,7 @@ def df_table(): class TestBuildSchema: - def test_build_table_schema(self, df_schema): + def test_build_table_schema(self, df_schema, using_infer_string): result = build_table_schema(df_schema, version=False) expected = { "fields": [ @@ -68,6 +68,8 @@ def test_build_table_schema(self, df_schema): ], "primaryKey": ["idx"], } + if using_infer_string: + expected["fields"][2] = {"name": "B", "type": "any", "extDtype": "string"} assert result == expected result = build_table_schema(df_schema) assert "pandas_version" in result @@ -97,7 +99,7 @@ def test_series_unnamed(self): } assert result == expected - def test_multiindex(self, df_schema): + def test_multiindex(self, df_schema, using_infer_string): df = df_schema idx = pd.MultiIndex.from_product([("a", "b"), (1, 2)]) df.index = idx @@ -114,6 +116,13 @@ def test_multiindex(self, df_schema): ], "primaryKey": ["level_0", "level_1"], } + if using_infer_string: + expected["fields"][0] = { + "name": "level_0", + "type": "any", + "extDtype": "string", + } + expected["fields"][3] = {"name": "B", "type": "any", "extDtype": "string"} assert result == expected df.index.names = ["idx0", None] @@ -156,7 +165,10 @@ def test_as_json_table_type_bool_data(self, bool_type): def test_as_json_table_type_date_data(self, date_data): assert as_json_table_type(date_data.dtype) == "datetime" - @pytest.mark.parametrize("str_data", [pd.Series(["a", "b"]), pd.Index(["a", "b"])]) + @pytest.mark.parametrize( + "str_data", + [pd.Series(["a", "b"], dtype=object), pd.Index(["a", "b"], dtype=object)], + ) def test_as_json_table_type_string_data(self, str_data): assert as_json_table_type(str_data.dtype) == "string" @@ -261,7 +273,7 @@ def test_read_json_from_to_json_results(self): tm.assert_frame_equal(result1, df) tm.assert_frame_equal(result2, df) - def test_to_json(self, df_table): + def test_to_json(self, df_table, using_infer_string): df = df_table df.index.name = "idx" result = df.to_json(orient="table", date_format="iso") @@ -292,6 +304,9 @@ def test_to_json(self, df_table): {"name": "H", "type": "datetime", "tz": "US/Central"}, ] + if using_infer_string: + fields[2] = {"name": "B", "type": "any", "extDtype": "string"} + schema = {"fields": fields, "primaryKey": ["idx"]} data = [ OrderedDict( diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 5275050391ca3..052356fdc96ed 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -13,6 +13,8 @@ import numpy as np import pytest +from pandas._config import using_pyarrow_string_dtype + from pandas.compat import IS64 import pandas.util._test_decorators as td @@ -30,6 +32,7 @@ ArrowStringArray, StringArray, ) +from pandas.core.arrays.string_arrow import ArrowStringArrayNumpySemantics from pandas.io.json import ujson_dumps @@ -238,7 +241,7 @@ def test_roundtrip_str_axes(self, orient, convert_axes, dtype): @pytest.mark.parametrize("convert_axes", [True, False]) def test_roundtrip_categorical( - self, request, orient, categorical_frame, convert_axes + self, request, orient, categorical_frame, convert_axes, using_infer_string ): # TODO: create a better frame to test with and improve coverage if orient in ("index", "columns"): @@ -252,7 +255,9 @@ def test_roundtrip_categorical( result = read_json(data, orient=orient, convert_axes=convert_axes) expected = categorical_frame.copy() - expected.index = expected.index.astype(str) # Categorical not preserved + expected.index = expected.index.astype( + str if not using_infer_string else "string[pyarrow_numpy]" + ) # Categorical not preserved expected.index.name = None # index names aren't preserved in JSON assert_json_roundtrip_equal(result, expected, orient) @@ -518,9 +523,9 @@ def test_v12_compat(self, datapath): df_iso = df.drop(["modified"], axis=1) v12_iso_json = os.path.join(dirpath, "tsframe_iso_v012.json") df_unser_iso = read_json(v12_iso_json) - tm.assert_frame_equal(df_iso, df_unser_iso) + tm.assert_frame_equal(df_iso, df_unser_iso, check_column_type=False) - def test_blocks_compat_GH9037(self): + def test_blocks_compat_GH9037(self, using_infer_string): index = pd.date_range("20000101", periods=10, freq="h") # freq doesn't round-trip index = DatetimeIndex(list(index), freq=None) @@ -604,7 +609,9 @@ def test_blocks_compat_GH9037(self): ) # JSON deserialisation always creates unicode strings - df_mixed.columns = df_mixed.columns.astype(np.str_) + df_mixed.columns = df_mixed.columns.astype( + np.str_ if not using_infer_string else "string[pyarrow_numpy]" + ) data = StringIO(df_mixed.to_json(orient="split")) df_roundtrip = read_json(data, orient="split") tm.assert_frame_equal( @@ -676,16 +683,19 @@ def test_series_non_unique_index(self): unserialized = read_json( StringIO(s.to_json(orient="records")), orient="records", typ="series" ) - tm.assert_numpy_array_equal(s.values, unserialized.values) + tm.assert_equal(s.values, unserialized.values) def test_series_default_orient(self, string_series): assert string_series.to_json() == string_series.to_json(orient="index") - def test_series_roundtrip_simple(self, orient, string_series): + def test_series_roundtrip_simple(self, orient, string_series, using_infer_string): data = StringIO(string_series.to_json(orient=orient)) result = read_json(data, typ="series", orient=orient) expected = string_series + if using_infer_string and orient in ("split", "index", "columns"): + # These schemas don't contain dtypes, so we infer string + expected.index = expected.index.astype("string[pyarrow_numpy]") if orient in ("values", "records"): expected = expected.reset_index(drop=True) if orient != "split": @@ -1459,6 +1469,9 @@ def test_from_json_to_json_table_dtypes(self): result = read_json(StringIO(dfjson), orient="table") tm.assert_frame_equal(result, expected) + # TODO: We are casting to string which coerces None to NaN before casting back + # to object, ending up with incorrect na values + @pytest.mark.xfail(using_pyarrow_string_dtype(), reason="incorrect na conversion") @pytest.mark.parametrize("orient", ["split", "records", "index", "columns"]) def test_to_json_from_json_columns_dtypes(self, orient): # GH21892 GH33205 @@ -1716,6 +1729,11 @@ def test_to_json_indent(self, indent): assert result == expected + @pytest.mark.skipif( + using_pyarrow_string_dtype(), + reason="Adjust expected when infer_string is default, no bug here, " + "just a complicated parametrization", + ) @pytest.mark.parametrize( "orient,expected", [ @@ -1991,7 +2009,9 @@ def test_json_uint64(self): @pytest.mark.parametrize( "orient", ["split", "records", "values", "index", "columns"] ) - def test_read_json_dtype_backend(self, string_storage, dtype_backend, orient): + def test_read_json_dtype_backend( + self, string_storage, dtype_backend, orient, using_infer_string + ): # GH#50750 pa = pytest.importorskip("pyarrow") df = DataFrame( @@ -2007,7 +2027,10 @@ def test_read_json_dtype_backend(self, string_storage, dtype_backend, orient): } ) - if string_storage == "python": + if using_infer_string: + string_array = ArrowStringArrayNumpySemantics(pa.array(["a", "b", "c"])) + string_array_na = ArrowStringArrayNumpySemantics(pa.array(["a", "b", None])) + elif string_storage == "python": string_array = StringArray(np.array(["a", "b", "c"], dtype=np.object_)) string_array_na = StringArray(np.array(["a", "b", NA], dtype=np.object_))
sits on #56195
https://api.github.com/repos/pandas-dev/pandas/pulls/56197
2023-11-26T23:37:34Z
2023-11-30T17:41:24Z
2023-11-30T17:41:24Z
2023-11-30T17:42:00Z