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
Backport PR #27932 on branch 0.25.x (BUG: Ensure that fill_na in Categorical only replaces null values)
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 102ecb9cb0f4e..245aa42b0de14 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -25,7 +25,7 @@ Bug fixes Categorical ^^^^^^^^^^^ -- +- Bug in :meth:`Categorical.fillna` would replace all values, not just those that are ``NaN`` (:issue:`26215`) - - diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index df5cd12a479f0..86a22d03440dd 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1864,8 +1864,8 @@ def fillna(self, value=None, method=None, limit=None): raise ValueError("fill value must be in categories") values_codes = _get_codes_for_values(value, self.categories) - indexer = np.where(values_codes != -1) - codes[indexer] = values_codes[values_codes != -1] + indexer = np.where(codes == -1) + codes[indexer] = values_codes[indexer] # If value is not a dict or Series it should be a scalar elif is_hashable(value): diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index 10375719be8d2..f847a39541558 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -578,6 +578,28 @@ def test_fillna_categorical(self, fill_value, expected_output): exp = Series(Categorical(expected_output, categories=["a", "b"])) tm.assert_series_equal(s.fillna(fill_value), exp) + @pytest.mark.parametrize( + "fill_value, expected_output", + [ + (Series(["a", "b", "c", "d", "e"]), ["a", "b", "b", "d", "e"]), + (Series(["b", "d", "a", "d", "a"]), ["a", "d", "b", "d", "a"]), + ( + Series( + Categorical( + ["b", "d", "a", "d", "a"], categories=["b", "c", "d", "e", "a"] + ) + ), + ["a", "d", "b", "d", "a"], + ), + ], + ) + def test_fillna_categorical_with_new_categories(self, fill_value, expected_output): + # GH 26215 + data = ["a", np.nan, "b", np.nan, np.nan] + s = Series(Categorical(data, categories=["a", "b", "c", "d", "e"])) + exp = Series(Categorical(expected_output, categories=["a", "b", "c", "d", "e"])) + tm.assert_series_equal(s.fillna(fill_value), exp) + def test_fillna_categorical_raise(self): data = ["a", np.nan, "b", np.nan, np.nan] s = Series(Categorical(data, categories=["a", "b"]))
Backport PR #27932: BUG: Ensure that fill_na in Categorical only replaces null values
https://api.github.com/repos/pandas-dev/pandas/pulls/27947
2019-08-16T11:22:41Z
2019-08-16T12:07:42Z
2019-08-16T12:07:42Z
2019-08-16T12:07:42Z
BUG: Merge with readonly arrays
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index f4308684e286a..ee250d62b7a74 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -127,9 +127,9 @@ 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`) +- 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`) Sparse ^^^^^^ diff --git a/pandas/_libs/hashtable.pyx b/pandas/_libs/hashtable.pyx index 3e620f5934d5e..b8df78e600a46 100644 --- a/pandas/_libs/hashtable.pyx +++ b/pandas/_libs/hashtable.pyx @@ -108,7 +108,7 @@ cdef class Int64Factorizer: def get_count(self): return self.count - def factorize(self, int64_t[:] values, sort=False, + def factorize(self, const int64_t[:] values, sort=False, na_sentinel=-1, na_value=None): """ Factorize values with nans replaced by na_sentinel diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index b6c6f967333a8..a04f093ee7818 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -1340,6 +1340,18 @@ def test_merge_take_missing_values_from_index_of_other_dtype(self): expected = expected.reindex(columns=["a", "key", "b"]) tm.assert_frame_equal(result, expected) + def test_merge_readonly(self): + # https://github.com/pandas-dev/pandas/issues/27943 + data1 = pd.DataFrame( + np.arange(20).reshape((4, 5)) + 1, columns=["a", "b", "c", "d", "e"] + ) + data2 = pd.DataFrame( + np.arange(20).reshape((5, 4)) + 1, columns=["a", "b", "x", "y"] + ) + + data1._data.blocks[0].values.flags.writeable = False + data1.merge(data2) # no error + def _check_merge(x, y): for how in ["inner", "left", "outer"]:
Closes #27943
https://api.github.com/repos/pandas-dev/pandas/pulls/27946
2019-08-16T11:17:20Z
2019-08-16T12:08:17Z
2019-08-16T12:08:16Z
2019-08-16T13:24:02Z
ENH:Return new Series when missing data in group keys is
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index f4308684e286a..cd0a4d0c4c3c7 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -85,7 +85,7 @@ Indexing - Bug in partial-string indexing returning a NumPy array rather than a ``Series`` when indexing with a scalar like ``.loc['2015']`` (:issue:`27516`) - Break reference cycle involving :class:`Index` and other index classes to allow garbage collection of index objects without running the GC. (:issue:`27585`, :issue:`27840`) - Fix regression in assigning values to a single column of a DataFrame with a ``MultiIndex`` columns (:issue:`27841`). -- +- `IndexError` would not raised if group keys are nan value (:issue:`20519`) Missing ^^^^^^^ diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 5f17dde01d2c4..1e2796562f29f 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -873,7 +873,13 @@ def _assert_take_fillable( values, indices, allow_fill=allow_fill, fill_value=na_value ) else: - taken = values.take(indices) + try: + taken = values.take(indices) + except IndexError: + if not values.tolist(): + return [] + else: + raise return taken _index_shared_docs[ diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index d1ed79118d2fa..1848c7e791f73 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2240,6 +2240,25 @@ def test_groupby(self): tm.assert_dict_equal(result, expected) + def test_groupby_nan_index_value(self): + df = pd.DataFrame([["x", np.nan, 1]], columns=["A", "B", "C"]).set_index( + ["A", "B"] + ) + result = df.groupby(level=["A", "B"]).C.sum() + s = Series([]) + s.name = "C" + expected = s.astype("int64") + tm.assert_series_equal(result, expected) + + df = pd.DataFrame( + [["x", np.nan, 1, 2], [None, "y", 3, 4]], columns=["A", "B", "C", "D"] + ).set_index(["A", "B", "C"]) + result = df.groupby(level=["A", "B"]).D.sum() + s = Series([]) + s.name = "D" + expected = s.astype("int64") + tm.assert_series_equal(result, expected) + @pytest.mark.parametrize( "mi,expected", [
ENH: missing data in index would not raise exception - [x] closes #20519 - [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/27945
2019-08-16T07:00:32Z
2019-08-22T14:19:18Z
null
2019-08-22T14:19:19Z
Upgrade groupby feature
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 21f1fa7ddec1f..24cc7121e7edc 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -85,7 +85,7 @@ Indexing - Bug in partial-string indexing returning a NumPy array rather than a ``Series`` when indexing with a scalar like ``.loc['2015']`` (:issue:`27516`) - Break reference cycle involving :class:`Index` and other index classes to allow garbage collection of index objects without running the GC. (:issue:`27585`, :issue:`27840`) - Fix regression in assigning values to a single column of a DataFrame with a ``MultiIndex`` columns (:issue:`27841`). -- +- `IndexError` would not raised if group keys are nan value (:issue:`20519`) Missing ^^^^^^^ diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 4e098b2f8be9b..92be441e9ba8b 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -874,7 +874,13 @@ def _assert_take_fillable( values, indices, allow_fill=allow_fill, fill_value=na_value ) else: - taken = values.take(indices) + try: + taken = values.take(indices) + except IndexError: + if not values.tolist(): + return [] + else: + raise return taken _index_shared_docs[ diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index d1ed79118d2fa..1848c7e791f73 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2240,6 +2240,25 @@ def test_groupby(self): tm.assert_dict_equal(result, expected) + def test_groupby_nan_index_value(self): + df = pd.DataFrame([["x", np.nan, 1]], columns=["A", "B", "C"]).set_index( + ["A", "B"] + ) + result = df.groupby(level=["A", "B"]).C.sum() + s = Series([]) + s.name = "C" + expected = s.astype("int64") + tm.assert_series_equal(result, expected) + + df = pd.DataFrame( + [["x", np.nan, 1, 2], [None, "y", 3, 4]], columns=["A", "B", "C", "D"] + ).set_index(["A", "B", "C"]) + result = df.groupby(level=["A", "B"]).D.sum() + s = Series([]) + s.name = "D" + expected = s.astype("int64") + tm.assert_series_equal(result, expected) + @pytest.mark.parametrize( "mi,expected", [
- [ ] 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/27944
2019-08-16T05:06:32Z
2019-08-16T06:23:40Z
null
2019-08-16T06:42:26Z
CLN: docstring cleanups
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 20398069847b1..603a615c1f8cb 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1190,7 +1190,7 @@ def to_numpy(self, dtype=None, copy=False): Parameters ---------- dtype : str or numpy.dtype, optional - The dtype to pass to :meth:`numpy.asarray` + The dtype to pass to :meth:`numpy.asarray`. copy : bool, default False Whether to ensure that the returned value is a not a view on another array. Note that ``copy=False`` does not *ensure* that diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 71d5068e2e0fc..ba1c516b9b444 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -131,7 +131,7 @@ class NDFrame(PandasObject, SelectionMixin): ---------- data : BlockManager axes : list - copy : boolean, default False + copy : bool, default False """ _internal_names = [ @@ -280,7 +280,8 @@ def _setup_axes( ns=None, docs=None, ): - """Provide axes setup for the major PandasObjects. + """ + Provide axes setup for the major PandasObjects. Parameters ---------- @@ -288,8 +289,8 @@ def _setup_axes( info_axis_num : the axis of the selector dimension (int) stat_axis_num : the number of axis for the default stats (int) aliases : other names for a single axis (dict) - axes_are_reversed : boolean whether to treat passed axes as - reversed (DataFrame) + axes_are_reversed : bool + Whether to treat passed axes as reversed (DataFrame). build_axes : setup the axis properties (default True) """ @@ -676,7 +677,7 @@ def transpose(self, *args, **kwargs): Parameters ---------- args : %(args_transpose)s - copy : boolean, default False + copy : bool, default False Make a copy of the underlying data. Mixed-dtype data will always result in a copy **kwargs @@ -2257,10 +2258,10 @@ def to_json( Parameters ---------- - path_or_buf : string or file handle, optional + path_or_buf : str or file handle, optional File path or object. If not specified, the result is returned as a string. - orient : string + orient : str Indication of expected JSON string format. * Series @@ -2539,7 +2540,7 @@ def to_msgpack(self, path_or_buf=None, encoding="utf-8", **kwargs): def to_sql( self, - name, + name: str, con, schema=None, if_exists="fail", @@ -2557,12 +2558,12 @@ def to_sql( Parameters ---------- - name : string + name : str Name of SQL table. con : sqlalchemy.engine.Engine or sqlite3.Connection Using SQLAlchemy makes it possible to use any DB supported by that library. Legacy support is provided for sqlite3.Connection objects. - schema : string, optional + schema : str, optional Specify the schema (if database flavor supports this). If None, use default schema. if_exists : {'fail', 'replace', 'append'}, default 'fail' @@ -2575,7 +2576,7 @@ def to_sql( index : bool, default True Write DataFrame index as a column. Uses `index_label` as the column name in the table. - index_label : string or sequence, default None + index_label : str or sequence, default None Column label for index column(s). If None is given (default) and `index` is True, then the index names are used. A sequence should be given if the DataFrame uses MultiIndex. @@ -3251,11 +3252,10 @@ def _maybe_update_cacher(self, clear=False, verify_is_copy=True): Parameters ---------- - clear : boolean, default False - clear the item cache - verify_is_copy : boolean, default True - provide is_copy checks - + clear : bool, default False + Clear the item cache. + verify_is_copy : bool, default True + Provide is_copy checks. """ cacher = getattr(self, "_cacher", None) @@ -3621,11 +3621,11 @@ def _check_setitem_copy(self, stacklevel=4, t="setting", force=False): Parameters ---------- - stacklevel : integer, default 4 + stacklevel : int, default 4 the level to show of the stack when the error is output - t : string, the type of setting error - force : boolean, default False - if True, then force showing an error + t : str, the type of setting error + force : bool, default False + If True, then force showing an error. validate if we are doing a setitem on a chained copy. @@ -3954,9 +3954,8 @@ def _update_inplace(self, result, verify_is_copy=True): Parameters ---------- - verify_is_copy : boolean, default True - provide is_copy checks - + verify_is_copy : bool, default True + Provide is_copy checks. """ # NOTE: This does *not* call __finalize__ and that's an explicit # decision that we may revisit in the future. @@ -4571,9 +4570,9 @@ def filter(self, items=None, like=None, regex=None, axis=None): ---------- items : list-like Keep labels from axis which are in items. - like : string + like : str Keep labels from axis for which "like in label == True". - regex : string (regular expression) + regex : str (regular expression) Keep labels from axis for which re.search(regex, label) == True. axis : int or string axis name The axis to filter on. By default this is the info axis, @@ -5233,8 +5232,8 @@ def _consolidate(self, inplace=False): Parameters ---------- - inplace : boolean, default False - If False return new object, otherwise modify existing object + inplace : bool, default False + If False return new object, otherwise modify existing object. Returns ------- @@ -5680,11 +5679,12 @@ def as_blocks(self, copy=True): Parameters ---------- - copy : boolean, default True + copy : bool, default True Returns ------- - values : a dict of dtype -> Constructor Types + dict + Mapping dtype -> Constructor Types. """ warnings.warn( "as_blocks is deprecated and will be removed in a future version", @@ -5993,17 +5993,17 @@ def _convert( Parameters ---------- - datetime : boolean, default False + datetime : bool, default False If True, convert to date where possible. - numeric : boolean, default False + numeric : bool, default False If True, attempt to convert to numbers (including strings), with unconvertible values becoming NaN. - timedelta : boolean, default False + timedelta : bool, default False If True, convert to timedelta where possible. - coerce : boolean, default False + coerce : bool, default False If True, force conversion with unconvertible values converted to - nulls (NaN or NaT) - copy : boolean, default True + nulls (NaN or NaT). + copy : bool, default True If True, return a copy even if no copy is necessary (e.g. no conversion was done). Note: This is meant for internal use, and should not be confused with inplace. @@ -7870,7 +7870,7 @@ def asfreq(self, freq, method=None, how=None, normalize=False, fill_value=None): Parameters ---------- - freq : DateOffset object, or string + freq : DateOffset or str method : {'backfill'/'bfill', 'pad'/'ffill'}, default None Method to use for filling holes in reindexed Series (note this does not fill NaNs that already were present): @@ -8671,7 +8671,7 @@ def ranker(data): level : int or level name, default None Broadcast across a level, matching Index values on the passed MultiIndex level - copy : boolean, default True + copy : bool, default True Always returns new objects. If copy=False and no reindexing is required then original objects are returned. fill_value : scalar, default np.NaN @@ -9463,7 +9463,7 @@ def truncate(self, before=None, after=None, axis=None, copy=True): Truncate all rows after this index value. axis : {0 or 'index', 1 or 'columns'}, optional Axis to truncate. Truncates the index (rows) by default. - copy : boolean, default is True, + copy : bool, default is True, Return a copy of the truncated section. Returns @@ -9607,13 +9607,13 @@ def tz_convert(self, tz, axis=0, level=None, copy=True): Parameters ---------- - tz : string or pytz.timezone object + tz : str or tzinfo object axis : the axis to convert level : int, str, default None - If axis ia a MultiIndex, convert a specific level. Otherwise - must be None - copy : boolean, default True - Also make a copy of the underlying data + If axis is a MultiIndex, convert a specific level. Otherwise + must be None. + copy : bool, default True + Also make a copy of the underlying data. Returns ------- @@ -9667,12 +9667,12 @@ def tz_localize( Parameters ---------- - tz : string or pytz.timezone object + tz : str or tzinfo axis : the axis to localize level : int, str, default None If axis ia a MultiIndex, localize a specific level. Otherwise must be None - copy : boolean, default True + copy : bool, default True Also make a copy of the underlying data ambiguous : 'infer', bool-ndarray, 'NaT', default 'raise' When clocks moved backward due to DST, ambiguous times may arise. @@ -11009,7 +11009,7 @@ def _doc_parms(cls): ---------- axis : {0 or 'index', 1 or 'columns'}, default 0 The index or the name of the axis. 0 is equivalent to None or 'index'. -skipna : boolean, default True +skipna : bool, default True Exclude NA/null values. If an entire row/column is NA, the result will be NA. *args, **kwargs : diff --git a/pandas/core/series.py b/pandas/core/series.py index c891298d6e499..3f04970ee4e58 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -675,8 +675,8 @@ def nonzero(self): 3 4 dtype: int64 - >>> s = pd.Series([0, 3, 0, 4], index=['a', 'b', 'c', 'd']) # same return although index of s is different + >>> s = pd.Series([0, 3, 0, 4], index=['a', 'b', 'c', 'd']) >>> s.nonzero() (array([1, 3]),) >>> s.iloc[s.nonzero()[0]] diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index ec5c609c1b267..2e6a401b49efc 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -53,7 +53,7 @@ def hist_series( rotation of y axis labels figsize : tuple, default None figure size in inches by default - bins : integer or sequence, default 10 + bins : int or sequence, default 10 Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last @@ -116,7 +116,7 @@ def hist_frame( ---------- data : DataFrame The pandas object holding the data. - column : string or sequence + column : str or sequence If passed, will be used to limit data to a subset of columns. by : object, optional If passed, then used to form histograms for separate groups. @@ -148,7 +148,7 @@ def hist_frame( `matplotlib.rcParams` by default. layout : tuple, optional Tuple of (rows, columns) for the layout of the histograms. - bins : integer or sequence, default 10 + bins : int or sequence, default 10 Number of histogram bins to be used. If an integer is given, bins + 1 bin edges are calculated and returned. If bins is a sequence, gives bin edges, including left edge of first bin and right edge of last @@ -177,7 +177,7 @@ def hist_frame( >>> df = pd.DataFrame({ ... 'length': [1.5, 0.5, 1.2, 0.9, 3], ... 'width': [0.7, 0.2, 0.15, 0.2, 1.1] - ... }, index= ['pig', 'rabbit', 'duck', 'chicken', 'horse']) + ... }, index=['pig', 'rabbit', 'duck', 'chicken', 'horse']) >>> hist = df.hist(bins=3) """ plot_backend = _get_plot_backend() @@ -370,8 +370,8 @@ def boxplot( If ``return_type`` is `None`, a NumPy array of axes with the same shape as ``layout`` is returned: - >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X', - ... return_type=None) + >>> boxplot = df.boxplot(column=['Col1', 'Col2'], by='X', + ... return_type=None) >>> type(boxplot) <class 'numpy.ndarray'> """ @@ -446,7 +446,7 @@ def boxplot_frame_groupby( * ``True`` - create a subplot for each group column : column name or list of names, or vector Can be any valid input to groupby - fontsize : int or string + fontsize : int or str rot : label rotation angle grid : Setting this to True will show the grid ax : Matplotlib axis object, default None @@ -530,7 +530,7 @@ class PlotAccessor(PandasObject): figsize : a tuple (width, height) in inches use_index : bool, default True Use index as ticks for x axis - title : string or list + title : str or list Title to use for the plot. If a string is passed, print the string at the top of the figure. If a list is passed and `subplots` is True, print each item in the list above the corresponding subplot. @@ -553,16 +553,16 @@ class PlotAccessor(PandasObject): .. versionchanged:: 0.25.0 xticks : sequence - Values to use for the xticks + Values to use for the xticks. yticks : sequence - Values to use for the yticks + Values to use for the yticks. xlim : 2-tuple/list ylim : 2-tuple/list rot : int, default None Rotation for ticks (xticks for vertical, yticks for horizontal plots) fontsize : int, default None - Font size for xticks and yticks + Font size for xticks and yticks. colormap : str or matplotlib colormap object, default None Colormap to select colors from. If string, load colormap with that name from matplotlib. @@ -587,9 +587,9 @@ class PlotAccessor(PandasObject): 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 + If True, boolean values can be plotted. `**kwds` : keywords - Options to pass to matplotlib plotting method + Options to pass to matplotlib plotting method. Returns ------- @@ -985,7 +985,7 @@ def barh(self, x=None, y=None, **kwargs): .. plot:: :context: close-figs - >>> df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]}) + >>> df = pd.DataFrame({'lab': ['A', 'B', 'C'], 'val': [10, 30, 20]}) >>> ax = df.plot.barh(x='lab', y='val') Plot a whole DataFrame to a horizontal bar plot @@ -1049,7 +1049,7 @@ def box(self, by=None, **kwargs): Parameters ---------- - by : string or sequence + by : str or sequence Column in the DataFrame to group by. **kwds : optional Additional keywords are documented in
cc @datapythonista
https://api.github.com/repos/pandas-dev/pandas/pulls/27942
2019-08-15T23:13:17Z
2019-08-16T19:18:53Z
2019-08-16T19:18:53Z
2019-08-16T20:32:18Z
CLN: internals.blocks cleanup, typing
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index e24e6e088b92a..ea895db226ba0 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -7,7 +7,7 @@ import numpy as np -from pandas._libs import NaT, Timestamp, lib, tslib, tslibs +from pandas._libs import NaT, Timestamp, lib, tslib import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion from pandas._libs.tslibs.timezones import tz_compare @@ -407,7 +407,7 @@ def fillna(self, value, limit=None, inplace=False, downcast=None): return self.copy() if self._can_hold_element(value): - # equivalent: self._try_coerce_args(value) would not raise + # equivalent: _try_coerce_args(value) would not raise blocks = self.putmask(mask, value, inplace=inplace) return self._maybe_downcast(blocks, downcast) @@ -669,7 +669,7 @@ def convert( return self.copy() if copy else self - def _can_hold_element(self, element): + def _can_hold_element(self, element: Any) -> bool: """ require the same dtype as ourselves """ dtype = self.values.dtype.type tipo = maybe_infer_dtype_type(element) @@ -837,12 +837,6 @@ def setitem(self, indexer, value): if self._can_hold_element(value): value = self._try_coerce_args(value) - # can keep its own dtype - if hasattr(value, "dtype") and is_dtype_equal(values.dtype, value.dtype): - dtype = self.dtype - else: - dtype = "infer" - else: # current dtype cannot store value, coerce to common dtype find_dtype = False @@ -851,15 +845,9 @@ def setitem(self, indexer, value): dtype = value.dtype find_dtype = True - elif lib.is_scalar(value): - if isna(value): - # NaN promotion is handled in latter path - dtype = False - else: - dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True) - find_dtype = True - else: - dtype = "infer" + elif lib.is_scalar(value) and not isna(value): + dtype, _ = infer_dtype_from_scalar(value, pandas_dtype=True) + find_dtype = True if find_dtype: dtype = find_common_type([values.dtype, dtype]) @@ -1068,7 +1056,7 @@ def coerce_to_target_dtype(self, other): mytz = getattr(self.dtype, "tz", None) othertz = getattr(dtype, "tz", None) - if str(mytz) != str(othertz): + if not tz_compare(mytz, othertz): return self.astype(object) raise AssertionError( @@ -1288,7 +1276,7 @@ def take_nd(self, indexer, axis, new_mgr_locs=None, fill_tuple=None): else: return self.make_block_same_class(new_values, new_mgr_locs) - def diff(self, n, axis=1): + def diff(self, n: int, axis: int = 1) -> List["Block"]: """ return block for the diff of the values """ new_values = algos.diff(self.values, n, axis=axis) return [self.make_block(values=new_values)] @@ -1377,7 +1365,7 @@ def func(cond, values, other): if not ( (self.is_integer or self.is_bool) - and lib.is_scalar(other) + and lib.is_float(other) and np.isnan(other) ): # np.where will cast integer array to floats in this case @@ -1430,7 +1418,7 @@ def func(cond, values, other): return result_blocks - def equals(self, other): + def equals(self, other) -> bool: if self.dtype != other.dtype or self.shape != other.shape: return False return array_equivalent(self.values, other.values) @@ -1810,7 +1798,7 @@ def take_nd(self, indexer, axis=0, new_mgr_locs=None, fill_tuple=None): return self.make_block_same_class(new_values, new_mgr_locs) - def _can_hold_element(self, element): + def _can_hold_element(self, element: Any) -> bool: # XXX: We may need to think about pushing this onto the array. # We're doing the same as CategoricalBlock here. return True @@ -1980,7 +1968,7 @@ class NumericBlock(Block): class FloatOrComplexBlock(NumericBlock): __slots__ = () - def equals(self, other): + def equals(self, other) -> bool: if self.dtype != other.dtype or self.shape != other.shape: return False left, right = self.values, other.values @@ -1991,7 +1979,7 @@ class FloatBlock(FloatOrComplexBlock): __slots__ = () is_float = True - def _can_hold_element(self, element): + def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, (np.floating, np.integer)) and not issubclass( @@ -2055,7 +2043,7 @@ class ComplexBlock(FloatOrComplexBlock): __slots__ = () is_complex = True - def _can_hold_element(self, element): + def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, (np.floating, np.integer, np.complexfloating)) @@ -2072,7 +2060,7 @@ class IntBlock(NumericBlock): is_integer = True _can_hold_na = False - def _can_hold_element(self, element): + def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if tipo is not None: return ( @@ -2162,7 +2150,7 @@ def _astype(self, dtype, **kwargs): # delegate return super()._astype(dtype=dtype, **kwargs) - def _can_hold_element(self, element): + def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if tipo is not None: if self.is_datetimetz: @@ -2352,41 +2340,19 @@ def _slice(self, slicer): return self.values[slicer] def _try_coerce_args(self, other): - """ - localize and return i8 for the values - - Parameters - ---------- - other : ndarray-like or scalar - - Returns - ------- - base-type other - """ - if is_valid_nat_for_dtype(other, self.dtype): - other = np.datetime64("NaT", "ns") - elif isinstance(other, self._holder): - if not tz_compare(other.tz, self.values.tz): - raise ValueError("incompatible or non tz-aware value") - - elif isinstance(other, (np.datetime64, datetime, date)): - other = tslibs.Timestamp(other) - - # test we can have an equal time zone - if not tz_compare(other.tz, self.values.tz): - raise ValueError("incompatible or non tz-aware value") - else: - raise TypeError(other) - + # DatetimeArray handles this for us return other - def diff(self, n, axis=0): - """1st discrete difference + def diff(self, n: int, axis: int = 0) -> List["Block"]: + """ + 1st discrete difference. Parameters ---------- - n : int, number of periods to diff - axis : int, axis to diff upon. default 0 + n : int + Number of periods to diff. + axis : int, default 0 + Axis to diff upon. Returns ------- @@ -2448,7 +2414,7 @@ def setitem(self, indexer, value): ) return newb.setitem(indexer, value) - def equals(self, other): + def equals(self, other) -> bool: # override for significant performance improvement if self.dtype != other.dtype or self.shape != other.shape: return False @@ -2487,7 +2453,7 @@ def __init__(self, values, placement, ndim=None): def _holder(self): return TimedeltaArray - def _can_hold_element(self, element): + def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, np.timedelta64) @@ -2580,7 +2546,7 @@ class BoolBlock(NumericBlock): is_bool = True _can_hold_na = False - def _can_hold_element(self, element): + def _can_hold_element(self, element: Any) -> bool: tipo = maybe_infer_dtype_type(element) if tipo is not None: return issubclass(tipo.type, np.bool_) @@ -2674,7 +2640,7 @@ def _maybe_downcast(self, blocks: List["Block"], downcast=None) -> List["Block"] # split and convert the blocks return _extend_blocks([b.convert(datetime=True, numeric=False) for b in blocks]) - def _can_hold_element(self, element): + def _can_hold_element(self, element: Any) -> bool: return True def _try_coerce_args(self, other):
https://api.github.com/repos/pandas-dev/pandas/pulls/27941
2019-08-15T22:55:38Z
2019-08-26T23:52:45Z
2019-08-26T23:52:45Z
2019-08-27T20:48:21Z
Fix typos in HDFStore docs
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index 947bf15a49c7a..5d7a268631778 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -3572,7 +3572,7 @@ Closing a Store and using a context manager: Read/write API '''''''''''''' -``HDFStore`` supports an top-level API using ``read_hdf`` for reading and ``to_hdf`` for writing, +``HDFStore`` supports a top-level API using ``read_hdf`` for reading and ``to_hdf`` for writing, similar to how ``read_csv`` and ``to_csv`` work. .. ipython:: python @@ -3687,7 +3687,7 @@ Hierarchical keys Keys to a store can be specified as a string. These can be in a hierarchical path-name like format (e.g. ``foo/bar/bah``), which will generate a hierarchy of sub-stores (or ``Groups`` in PyTables -parlance). Keys can be specified with out the leading '/' and are **always** +parlance). Keys can be specified without the leading '/' and are **always** absolute (e.g. 'foo' refers to '/foo'). Removal operations can remove everything in the sub-store and **below**, so be *careful*. @@ -3825,7 +3825,7 @@ data. A query is specified using the ``Term`` class under the hood, as a boolean expression. -* ``index`` and ``columns`` are supported indexers of a ``DataFrames``. +* ``index`` and ``columns`` are supported indexers of ``DataFrames``. * if ``data_columns`` are specified, these can be used as additional indexers. Valid comparison operators are: @@ -3917,7 +3917,7 @@ Use boolean expressions, with in-line function evaluation. store.select('dfq', "index>pd.Timestamp('20130104') & columns=['A', 'B']") -Use and inline column reference +Use inline column reference. .. ipython:: python @@ -4593,8 +4593,8 @@ Performance write chunksize (default is 50000). This will significantly lower your memory usage on writing. * You can pass ``expectedrows=<int>`` to the first ``append``, - to set the TOTAL number of expected rows that ``PyTables`` will - expected. This will optimize read/write performance. + to set the TOTAL number of rows that ``PyTables`` will expect. + This will optimize read/write performance. * Duplicate rows can be written to tables, but are filtered out in selection (with the last items being selected; thus a table is unique on major, minor pairs)
https://api.github.com/repos/pandas-dev/pandas/pulls/27940
2019-08-15T21:28:26Z
2019-08-16T11:32:32Z
2019-08-16T11:32:32Z
2019-08-16T15:39:10Z
CLN: docstrings, circularity in core.computation
diff --git a/pandas/compat/chainmap.py b/pandas/compat/chainmap.py index 83f1da597d6a6..84824207de2a9 100644 --- a/pandas/compat/chainmap.py +++ b/pandas/compat/chainmap.py @@ -15,9 +15,3 @@ def __delitem__(self, key): del mapping[key] return raise KeyError(key) - - # override because the m parameter is introduced in Python 3.4 - def new_child(self, m=None): - if m is None: - m = {} - return self.__class__(m, *self.maps) diff --git a/pandas/core/computation/align.py b/pandas/core/computation/align.py index 1046401850963..3e1e5ed89d877 100644 --- a/pandas/core/computation/align.py +++ b/pandas/core/computation/align.py @@ -9,6 +9,7 @@ from pandas.errors import PerformanceWarning import pandas as pd +from pandas.core.base import PandasObject import pandas.core.common as com from pandas.core.computation.common import _result_type_many @@ -34,7 +35,7 @@ def _zip_axes_from_type(typ, new_axes): def _any_pandas_objects(terms): """Check a sequence of terms for instances of PandasObject.""" - return any(isinstance(term.value, pd.core.generic.PandasObject) for term in terms) + return any(isinstance(term.value, PandasObject) for term in terms) def _filter_special_cases(f): @@ -132,7 +133,8 @@ def _align(terms): def _reconstruct_object(typ, obj, axes, dtype): - """Reconstruct an object given its type, raw value, and possibly empty + """ + Reconstruct an object given its type, raw value, and possibly empty (None) axes. Parameters @@ -157,7 +159,7 @@ def _reconstruct_object(typ, obj, axes, dtype): res_t = np.result_type(obj.dtype, dtype) - if not isinstance(typ, partial) and issubclass(typ, pd.core.generic.PandasObject): + if not isinstance(typ, partial) and issubclass(typ, PandasObject): return typ(obj, dtype=res_t, **axes) # special case for pathological things like ~True/~False diff --git a/pandas/core/computation/common.py b/pandas/core/computation/common.py index 2a4277e4e0a20..bd32c8bee1cdf 100644 --- a/pandas/core/computation/common.py +++ b/pandas/core/computation/common.py @@ -36,8 +36,3 @@ def _remove_spaces_column_name(name): class NameResolutionError(NameError): pass - - -class StringMixin: - # TODO: delete this class. Removing this ATM caused a failure. - pass diff --git a/pandas/core/computation/engines.py b/pandas/core/computation/engines.py index 2c94b142a45b3..3cc34ea1f4ed7 100644 --- a/pandas/core/computation/engines.py +++ b/pandas/core/computation/engines.py @@ -17,7 +17,8 @@ class NumExprClobberingError(NameError): def _check_ne_builtin_clash(expr): - """Attempt to prevent foot-shooting in a helpful way. + """ + Attempt to prevent foot-shooting in a helpful way. Parameters ---------- @@ -53,7 +54,8 @@ def convert(self): return printing.pprint_thing(self.expr) def evaluate(self): - """Run the engine on the expression + """ + Run the engine on the expression. This method performs alignment which is necessary no matter what engine is being used, thus its implementation is in the base class. @@ -78,7 +80,8 @@ def _is_aligned(self): @abc.abstractmethod def _evaluate(self): - """Return an evaluated expression. + """ + Return an evaluated expression. Parameters ---------- @@ -94,7 +97,6 @@ def _evaluate(self): class NumExprEngine(AbstractEngine): - """NumExpr engine class""" has_neg_frac = True @@ -127,8 +129,8 @@ def _evaluate(self): class PythonEngine(AbstractEngine): - - """Evaluate an expression in Python space. + """ + Evaluate an expression in Python space. Mostly for testing purposes. """ diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index d0d87c23e9346..a58f256cf61d4 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -41,7 +41,8 @@ def tokenize_string(source): - """Tokenize a Python source code string. + """ + Tokenize a Python source code string. Parameters ---------- diff --git a/pandas/core/computation/expressions.py b/pandas/core/computation/expressions.py index 0ecf56cf6fe96..5b6d275001d36 100644 --- a/pandas/core/computation/expressions.py +++ b/pandas/core/computation/expressions.py @@ -99,15 +99,13 @@ def _evaluate_numexpr(op, op_str, a, b, truediv=True, reversed=False, **eval_kwa result = None if _can_use_numexpr(op, op_str, a, b, "evaluate"): - try: - - # we were originally called by a reversed op - # method - if reversed: - a, b = b, a + if reversed: + # we were originally called by a reversed op method + a, b = b, a - a_value = getattr(a, "values", a) - b_value = getattr(b, "values", b) + a_value = getattr(a, "values", a) + b_value = getattr(b, "values", b) + try: result = ne.evaluate( "a_value {op} b_value".format(op=op_str), local_dict={"a_value": a_value, "b_value": b_value}, @@ -138,11 +136,11 @@ def _where_numexpr(cond, a, b): result = None if _can_use_numexpr(None, "where", a, b, "where"): + cond_value = getattr(cond, "values", cond) + a_value = getattr(a, "values", a) + b_value = getattr(b, "values", b) try: - cond_value = getattr(cond, "values", cond) - a_value = getattr(a, "values", a) - b_value = getattr(b, "values", b) result = ne.evaluate( "where(cond_value, a_value, b_value)", local_dict={ @@ -209,7 +207,8 @@ def evaluate(op, op_str, a, b, use_numexpr=True, **eval_kwargs): Parameters ---------- op : the actual operand - op_str : the string version of the op + op_str : str + The string version of the op. a : left operand b : right operand use_numexpr : bool, default True @@ -224,11 +223,11 @@ def evaluate(op, op_str, a, b, use_numexpr=True, **eval_kwargs): def where(cond, a, b, use_numexpr=True): """ - Evaluate the where condition cond on a and b + Evaluate the where condition cond on a and b. Parameters ---------- - cond : ndarray[bool] + cond : np.ndarray[bool] a : return if cond is True b : return if cond is False use_numexpr : bool, default True diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index b49220ae701bc..28b6aef693bfe 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -476,8 +476,8 @@ def isnumeric(dtype): class Div(BinOp): - - """Div operator to special case casting. + """ + Div operator to special case casting. Parameters ---------- @@ -508,8 +508,8 @@ def __init__(self, lhs, rhs, truediv, *args, **kwargs): class UnaryOp(Op): - - """Hold a unary operator and its operands + """ + Hold a unary operator and its operands. Parameters ---------- diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py index 8ddd0dd7622e7..b11411eb2dc66 100644 --- a/pandas/core/computation/scope.py +++ b/pandas/core/computation/scope.py @@ -15,9 +15,6 @@ from pandas._libs.tslibs import Timestamp from pandas.compat.chainmap import DeepChainMap -import pandas.core.computation as compu -from pandas.core.computation.common import StringMixin - def _ensure_scope( level, global_dict=None, local_dict=None, resolvers=(), target=None, **kwargs @@ -67,7 +64,8 @@ def _raw_hex_id(obj): def _get_pretty_string(obj): - """Return a prettier version of obj + """ + Return a prettier version of obj. Parameters ---------- @@ -84,9 +82,9 @@ def _get_pretty_string(obj): return sio.getvalue() -class Scope(StringMixin): - - """Object to hold scope, with a few bells to deal with some custom syntax +class Scope: + """ + Object to hold scope, with a few bells to deal with some custom syntax and contexts added by pandas. Parameters @@ -105,7 +103,7 @@ class Scope(StringMixin): temps : dict """ - __slots__ = "level", "scope", "target", "temps" + __slots__ = ["level", "scope", "target", "resolvers", "temps"] def __init__( self, level, global_dict=None, local_dict=None, resolvers=(), target=None @@ -163,7 +161,8 @@ def has_resolvers(self): return bool(len(self.resolvers)) def resolve(self, key, is_local): - """Resolve a variable name in a possibly local context + """ + Resolve a variable name in a possibly local context. Parameters ---------- @@ -198,10 +197,14 @@ def resolve(self, key, is_local): # e.g., df[df > 0] return self.temps[key] except KeyError: - raise compu.ops.UndefinedVariableError(key, is_local) + # runtime import because ops imports from scope + from pandas.core.computation.ops import UndefinedVariableError + + raise UndefinedVariableError(key, is_local) def swapkey(self, old_key, new_key, new_value=None): - """Replace a variable name, with a potentially new value. + """ + Replace a variable name, with a potentially new value. Parameters ---------- @@ -225,7 +228,8 @@ def swapkey(self, old_key, new_key, new_value=None): return def _get_vars(self, stack, scopes): - """Get specifically scoped variables from a list of stack frames. + """ + Get specifically scoped variables from a list of stack frames. Parameters ---------- @@ -247,7 +251,8 @@ def _get_vars(self, stack, scopes): del frame def update(self, level): - """Update the current scope by going back `level` levels. + """ + Update the current scope by going back `level` levels. Parameters ---------- @@ -266,7 +271,8 @@ def update(self, level): del stack[:], stack def add_tmp(self, value): - """Add a temporary variable to the scope. + """ + Add a temporary variable to the scope. Parameters ---------- @@ -297,7 +303,8 @@ def ntemps(self): @property def full_scope(self): - """Return the full scope for use with passing to engines transparently + """ + Return the full scope for use with passing to engines transparently as a mapping. Returns
Things noticed while looking through this directory: - computation.pytables is only used io.pytables, might not belong in core.computation - UndefinedVariableError looks like it was defined as part of a `# python 3 compat kludge`, might no longer be necessary
https://api.github.com/repos/pandas-dev/pandas/pulls/27939
2019-08-15T21:08:43Z
2019-08-16T12:11:11Z
2019-08-16T12:11:11Z
2019-08-16T13:56:17Z
Backport PR #27878 on branch 0.25.x (TST: Raise ValueError and suggestion to use header=None if header=-1 is pa…)
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index b53b53c654ce3..102ecb9cb0f4e 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -105,7 +105,7 @@ I/O ^^^ - Avoid calling ``S3File.s3`` when reading parquet, as this was removed in s3fs version 0.3.0 (:issue:`27756`) -- +- Better error message when a negative header is passed in :func:`pandas.read_csv` (:issue:`27779`) - Plotting diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 300f17bd25432..45444ffa0c8bd 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1401,6 +1401,10 @@ def __init__(self, kwds): if isinstance(self.header, (list, tuple, np.ndarray)): if not all(map(is_integer, self.header)): raise ValueError("header must be integer or list of integers") + if any(i < 0 for i in self.header): + raise ValueError( + "cannot specify multi-index header with negative integers" + ) if kwds.get("usecols"): raise ValueError( "cannot specify usecols when " "specifying a multi-index header" @@ -1427,6 +1431,13 @@ def __init__(self, kwds): elif self.header is not None and not is_integer(self.header): raise ValueError("header must be integer or list of integers") + # GH 27779 + elif self.header is not None and self.header < 0: + raise ValueError( + "Passing negative integer to header is invalid. " + "For no header, use header=None instead" + ) + self._name_processed = False self._first_chunk = True diff --git a/pandas/tests/io/parser/test_header.py b/pandas/tests/io/parser/test_header.py index 99e0181741998..0ecd8be7ddc78 100644 --- a/pandas/tests/io/parser/test_header.py +++ b/pandas/tests/io/parser/test_header.py @@ -24,6 +24,35 @@ def test_read_with_bad_header(all_parsers): parser.read_csv(s, header=[10]) +def test_negative_header(all_parsers): + # see gh-27779 + parser = all_parsers + data = """1,2,3,4,5 +6,7,8,9,10 +11,12,13,14,15 +""" + with pytest.raises( + ValueError, + match="Passing negative integer to header is invalid. " + "For no header, use header=None instead", + ): + parser.read_csv(StringIO(data), header=-1) + + +@pytest.mark.parametrize("header", [([-1, 2, 4]), ([-5, 0])]) +def test_negative_multi_index_header(all_parsers, header): + # see gh-27779 + parser = all_parsers + data = """1,2,3,4,5 + 6,7,8,9,10 + 11,12,13,14,15 + """ + with pytest.raises( + ValueError, match="cannot specify multi-index header with negative integers" + ): + parser.read_csv(StringIO(data), header=header) + + @pytest.mark.parametrize("header", [True, False]) def test_bool_header_arg(all_parsers, header): # see gh-6114
Backport PR #27878: TST: Raise ValueError and suggestion to use header=None if header=-1 is pa…
https://api.github.com/repos/pandas-dev/pandas/pulls/27938
2019-08-15T20:27:58Z
2019-08-16T01:27:55Z
2019-08-16T01:27:55Z
2019-08-16T01:27:55Z
REF: implement array_ops
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 1aad130d9a3f5..093334a815938 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -195,11 +195,11 @@ def wrapper(self, other): return invalid_comparison(self, other, op) if is_object_dtype(other): - # We have to use _comp_method_OBJECT_ARRAY instead of numpy + # We have to use comp_method_OBJECT_ARRAY instead of numpy # comparison otherwise it would fail to raise when # comparing tz-aware and tz-naive with np.errstate(all="ignore"): - result = ops._comp_method_OBJECT_ARRAY( + result = ops.comp_method_OBJECT_ARRAY( op, self.astype(object), other ) o_mask = isna(other) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 5f17dde01d2c4..b983117478c61 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -109,7 +109,7 @@ def cmp_method(self, other): elif is_object_dtype(self) and not isinstance(self, ABCMultiIndex): # don't pass MultiIndex with np.errstate(all="ignore"): - result = ops._comp_method_OBJECT_ARRAY(op, self.values, other) + result = ops.comp_method_OBJECT_ARRAY(op, self.values, other) else: with np.errstate(all="ignore"): diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 26672593f98fb..dbcf09a401f27 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -13,11 +13,7 @@ from pandas.errors import NullFrequencyError from pandas.util._decorators import Appender -from pandas.core.dtypes.cast import ( - construct_1d_object_array_from_listlike, - find_common_type, - maybe_upcast_putmask, -) +from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike from pandas.core.dtypes.common import ( ensure_object, is_bool_dtype, @@ -29,7 +25,6 @@ is_integer_dtype, is_list_like, is_object_dtype, - is_period_dtype, is_scalar, is_timedelta64_dtype, ) @@ -37,7 +32,6 @@ ABCDataFrame, ABCDatetimeArray, ABCDatetimeIndex, - ABCIndex, ABCIndexClass, ABCSeries, ABCSparseSeries, @@ -47,7 +41,7 @@ import pandas as pd from pandas._typing import ArrayLike from pandas.core.construction import array, extract_array -from pandas.core.ops import missing +from pandas.core.ops.array_ops import comp_method_OBJECT_ARRAY, define_na_arithmetic_op from pandas.core.ops.docstrings import ( _arith_doc_FRAME, _flex_comp_doc_FRAME, @@ -398,63 +392,6 @@ def mask_cmp_op(x, y, op): return result -def masked_arith_op(x, y, op): - """ - If the given arithmetic operation fails, attempt it again on - only the non-null elements of the input array(s). - - Parameters - ---------- - x : np.ndarray - y : np.ndarray, Series, Index - op : binary operator - """ - # For Series `x` is 1D so ravel() is a no-op; calling it anyway makes - # the logic valid for both Series and DataFrame ops. - xrav = x.ravel() - assert isinstance(x, np.ndarray), type(x) - if isinstance(y, np.ndarray): - dtype = find_common_type([x.dtype, y.dtype]) - result = np.empty(x.size, dtype=dtype) - - # PeriodIndex.ravel() returns int64 dtype, so we have - # to work around that case. See GH#19956 - yrav = y if is_period_dtype(y) else y.ravel() - mask = notna(xrav) & notna(yrav) - - if yrav.shape != mask.shape: - # FIXME: GH#5284, GH#5035, GH#19448 - # Without specifically raising here we get mismatched - # errors in Py3 (TypeError) vs Py2 (ValueError) - # Note: Only = an issue in DataFrame case - raise ValueError("Cannot broadcast operands together.") - - if mask.any(): - with np.errstate(all="ignore"): - result[mask] = op(xrav[mask], yrav[mask]) - - else: - assert is_scalar(y), type(y) - assert isinstance(x, np.ndarray), type(x) - # mask is only meaningful for x - result = np.empty(x.size, dtype=x.dtype) - mask = notna(xrav) - - # 1 ** np.nan is 1. So we have to unmask those. - if op == pow: - mask = np.where(x == 1, False, mask) - elif op == rpow: - mask = np.where(y == 1, False, mask) - - if mask.any(): - with np.errstate(all="ignore"): - result[mask] = op(xrav[mask], y) - - result, changed = maybe_upcast_putmask(result, ~mask, np.nan) - result = result.reshape(x.shape) # 2D compat - return result - - # ----------------------------------------------------------------------------- # Dispatch logic @@ -673,33 +610,7 @@ def _arith_method_SERIES(cls, op, special): _construct_divmod_result if op in [divmod, rdivmod] else _construct_result ) - def na_op(x, y): - """ - Return the result of evaluating op on the passed in values. - - If native types are not compatible, try coersion to object dtype. - - Parameters - ---------- - x : array-like - y : array-like or scalar - - Returns - ------- - array-like - - Raises - ------ - TypeError : invalid operation - """ - import pandas.core.computation.expressions as expressions - - try: - result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs) - except TypeError: - result = masked_arith_op(x, y, op) - - return missing.dispatch_fill_zeros(op, x, y, result) + na_op = define_na_arithmetic_op(op, str_rep, eval_kwargs) def wrapper(left, right): if isinstance(right, ABCDataFrame): @@ -735,22 +646,6 @@ def wrapper(left, right): return wrapper -def _comp_method_OBJECT_ARRAY(op, x, y): - if isinstance(y, list): - y = construct_1d_object_array_from_listlike(y) - if isinstance(y, (np.ndarray, ABCSeries, ABCIndex)): - if not is_object_dtype(y.dtype): - y = y.astype(np.object_) - - if isinstance(y, (ABCSeries, ABCIndex)): - y = y.values - - result = libops.vec_compare(x, y, op) - else: - result = libops.scalar_compare(x, y, op) - return result - - def _comp_method_SERIES(cls, op, special): """ Wrapper function for Series arithmetic operations, to avoid @@ -764,7 +659,7 @@ def na_op(x, y): # Extension Dtypes are not called here if is_object_dtype(x.dtype): - result = _comp_method_OBJECT_ARRAY(op, x, y) + result = comp_method_OBJECT_ARRAY(op, x, y) elif is_datetimelike_v_numeric(x, y): return invalid_comparison(x, y, op) @@ -1091,15 +986,7 @@ def _arith_method_FRAME(cls, op, special): eval_kwargs = _gen_eval_kwargs(op_name) default_axis = _get_frame_op_default_axis(op_name) - def na_op(x, y): - import pandas.core.computation.expressions as expressions - - try: - result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs) - except TypeError: - result = masked_arith_op(x, y, op) - - return missing.dispatch_fill_zeros(op, x, y, result) + na_op = define_na_arithmetic_op(op, str_rep, eval_kwargs) if op_name in _op_descriptions: # i.e. include "add" but not "__add__" diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py new file mode 100644 index 0000000000000..a3bfb2e10bb66 --- /dev/null +++ b/pandas/core/ops/array_ops.py @@ -0,0 +1,127 @@ +""" +Functions for arithmetic and comparison operations on NumPy arrays and +ExtensionArrays. +""" +import numpy as np + +from pandas._libs import ops as libops + +from pandas.core.dtypes.cast import ( + construct_1d_object_array_from_listlike, + find_common_type, + maybe_upcast_putmask, +) +from pandas.core.dtypes.common import is_object_dtype, is_period_dtype, is_scalar +from pandas.core.dtypes.generic import ABCIndex, ABCSeries +from pandas.core.dtypes.missing import notna + +from pandas.core.ops import missing +from pandas.core.ops.roperator import rpow + + +def comp_method_OBJECT_ARRAY(op, x, y): + if isinstance(y, list): + y = construct_1d_object_array_from_listlike(y) + + # TODO: Should the checks below be ABCIndexClass? + if isinstance(y, (np.ndarray, ABCSeries, ABCIndex)): + # TODO: should this be ABCIndexClass?? + if not is_object_dtype(y.dtype): + y = y.astype(np.object_) + + if isinstance(y, (ABCSeries, ABCIndex)): + y = y.values + + result = libops.vec_compare(x, y, op) + else: + result = libops.scalar_compare(x, y, op) + return result + + +def masked_arith_op(x, y, op): + """ + If the given arithmetic operation fails, attempt it again on + only the non-null elements of the input array(s). + + Parameters + ---------- + x : np.ndarray + y : np.ndarray, Series, Index + op : binary operator + """ + # For Series `x` is 1D so ravel() is a no-op; calling it anyway makes + # the logic valid for both Series and DataFrame ops. + xrav = x.ravel() + assert isinstance(x, np.ndarray), type(x) + if isinstance(y, np.ndarray): + dtype = find_common_type([x.dtype, y.dtype]) + result = np.empty(x.size, dtype=dtype) + + # PeriodIndex.ravel() returns int64 dtype, so we have + # to work around that case. See GH#19956 + yrav = y if is_period_dtype(y) else y.ravel() + mask = notna(xrav) & notna(yrav) + + if yrav.shape != mask.shape: + # FIXME: GH#5284, GH#5035, GH#19448 + # Without specifically raising here we get mismatched + # errors in Py3 (TypeError) vs Py2 (ValueError) + # Note: Only = an issue in DataFrame case + raise ValueError("Cannot broadcast operands together.") + + if mask.any(): + with np.errstate(all="ignore"): + result[mask] = op(xrav[mask], yrav[mask]) + + else: + assert is_scalar(y), type(y) + assert isinstance(x, np.ndarray), type(x) + # mask is only meaningful for x + result = np.empty(x.size, dtype=x.dtype) + mask = notna(xrav) + + # 1 ** np.nan is 1. So we have to unmask those. + if op == pow: + mask = np.where(x == 1, False, mask) + elif op == rpow: + mask = np.where(y == 1, False, mask) + + if mask.any(): + with np.errstate(all="ignore"): + result[mask] = op(xrav[mask], y) + + result, changed = maybe_upcast_putmask(result, ~mask, np.nan) + result = result.reshape(x.shape) # 2D compat + return result + + +def define_na_arithmetic_op(op, str_rep, eval_kwargs): + def na_op(x, y): + """ + Return the result of evaluating op on the passed in values. + + If native types are not compatible, try coersion to object dtype. + + Parameters + ---------- + x : array-like + y : array-like or scalar + + Returns + ------- + array-like + + Raises + ------ + TypeError : invalid operation + """ + import pandas.core.computation.expressions as expressions + + try: + result = expressions.evaluate(op, str_rep, x, y, **eval_kwargs) + except TypeError: + result = masked_arith_op(x, y, op) + + return missing.dispatch_fill_zeros(op, x, y, result) + + return na_op
This begins the process of separating the (ndarray|EA)-specific parts of Series ops out from the Series ops themselves. Eventually these will a) become the op implementations for PandasArray, and b) be used block-wise instead of column-wise for DataFrame ops.
https://api.github.com/repos/pandas-dev/pandas/pulls/27936
2019-08-15T15:44:38Z
2019-08-16T12:12:28Z
2019-08-16T12:12:28Z
2019-08-16T13:56:59Z
BUG: set_precision format fixed (#13257)
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 7692651db840e..8fe3320b29000 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -354,6 +354,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:`pandas.io.formats.style.Styler` formatting for floating values not displaying decimals correctly (:issue:`13257`) Plotting ^^^^^^^^ diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 6b98eaca9dacc..0200b78e02fd2 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -156,7 +156,8 @@ def __init__( def default_display_func(x): if is_float(x): - return "{:>.{precision}g}".format(x, precision=self.precision) + display_format = "{0:.{precision}f}".format(x, precision=self.precision) + return display_format else: return x diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index 61c163d2cdaac..0f1402d7da389 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -1157,20 +1157,43 @@ def test_display_format_raises(self): with pytest.raises(TypeError): df.style.format(True) + def test_display_set_precision(self): + # Issue #13257 + df = pd.DataFrame(data=[[1.0, 2.0090], [3.2121, 4.566]], columns=["a", "b"]) + s = Styler(df) + + ctx = s.set_precision(1)._translate() + + assert s.precision == 1 + assert ctx["body"][0][1]["display_value"] == "1.0" + assert ctx["body"][0][2]["display_value"] == "2.0" + assert ctx["body"][1][1]["display_value"] == "3.2" + assert ctx["body"][1][2]["display_value"] == "4.6" + + ctx = s.set_precision(2)._translate() + assert s.precision == 2 + assert ctx["body"][0][1]["display_value"] == "1.00" + assert ctx["body"][0][2]["display_value"] == "2.01" + assert ctx["body"][1][1]["display_value"] == "3.21" + assert ctx["body"][1][2]["display_value"] == "4.57" + + ctx = s.set_precision(3)._translate() + assert s.precision == 3 + assert ctx["body"][0][1]["display_value"] == "1.000" + assert ctx["body"][0][2]["display_value"] == "2.009" + assert ctx["body"][1][1]["display_value"] == "3.212" + assert ctx["body"][1][2]["display_value"] == "4.566" + def test_display_subset(self): df = pd.DataFrame([[0.1234, 0.1234], [1.1234, 1.1234]], columns=["a", "b"]) ctx = df.style.format( {"a": "{:0.1f}", "b": "{0:.2%}"}, subset=pd.IndexSlice[0, :] )._translate() expected = "0.1" - assert ctx["body"][0][1]["display_value"] == expected - assert ctx["body"][1][1]["display_value"] == "1.1234" - assert ctx["body"][0][2]["display_value"] == "12.34%" - - raw_11 = "1.1234" - ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice[0, :])._translate() + raw_11 = "1.123400" assert ctx["body"][0][1]["display_value"] == expected assert ctx["body"][1][1]["display_value"] == raw_11 + assert ctx["body"][0][2]["display_value"] == "12.34%" ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice[0, :])._translate() assert ctx["body"][0][1]["display_value"] == expected @@ -1178,7 +1201,7 @@ def test_display_subset(self): ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice["a"])._translate() assert ctx["body"][0][1]["display_value"] == expected - assert ctx["body"][0][2]["display_value"] == "0.1234" + assert ctx["body"][0][2]["display_value"] == "0.123400" ctx = df.style.format("{:0.1f}", subset=pd.IndexSlice[0, "a"])._translate() assert ctx["body"][0][1]["display_value"] == expected @@ -1189,8 +1212,8 @@ def test_display_subset(self): )._translate() assert ctx["body"][0][1]["display_value"] == expected assert ctx["body"][1][1]["display_value"] == "1.1" - assert ctx["body"][0][2]["display_value"] == "0.1234" - assert ctx["body"][1][2]["display_value"] == "1.1234" + assert ctx["body"][0][2]["display_value"] == "0.123400" + assert ctx["body"][1][2]["display_value"] == raw_11 def test_display_dict(self): df = pd.DataFrame([[0.1234, 0.1234], [1.1234, 1.1234]], columns=["a", "b"])
- [x] closes #13257 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry I've tried to fix the set_precision format, does that fix it? ### INPUT -> df.style.set_precision(2) | A | B | | --- | --- | | 1 | 2.0090 | | 3.2121 | 4.566 | ### OUTPUT | A | B | | --- | --- | | 1 | 2.01 | | 3.21 | 4.57 | @vinigl @samuelgranato
https://api.github.com/repos/pandas-dev/pandas/pulls/27934
2019-08-15T14:32:22Z
2019-10-22T01:53:38Z
2019-10-22T01:53:38Z
2019-12-26T14:51:04Z
TST: Asserts all types are caterogical in function fillna with correct error message
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 21f1fa7ddec1f..751829f11570f 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -25,7 +25,6 @@ Bug fixes Categorical ^^^^^^^^^^^ -- - - diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index aeed3668fe774..c4f1317ad0c67 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -87,6 +87,7 @@ Bug fixes Categorical ^^^^^^^^^^^ +- Added test to assert the :func:`fillna` raises the correct ValueError message when the value isn't a value from categories (:issue:`13628`) - - diff --git a/pandas/tests/arrays/categorical/test_missing.py b/pandas/tests/arrays/categorical/test_missing.py index 1b62479530d24..3037ac79cd592 100644 --- a/pandas/tests/arrays/categorical/test_missing.py +++ b/pandas/tests/arrays/categorical/test_missing.py @@ -5,7 +5,7 @@ from pandas.core.dtypes.dtypes import CategoricalDtype -from pandas import Categorical, Index, isna +from pandas import Categorical, Index, Series, isna import pandas.util.testing as tm @@ -59,11 +59,13 @@ def test_set_item_nan(self): ), (dict(), "Must specify a fill 'value' or 'method'."), (dict(method="bad"), "Invalid fill method. Expecting .* bad"), + (dict(value=Series([1, 2, 3, 4, "a"])), "fill value must be in categories"), ], ) def test_fillna_raises(self, fillna_kwargs, msg): # https://github.com/pandas-dev/pandas/issues/19682 - cat = Categorical([1, 2, 3]) + # https://github.com/pandas-dev/pandas/issues/13628 + cat = Categorical([1, 2, 3, None, None]) with pytest.raises(ValueError, match=msg): cat.fillna(**fillna_kwargs)
- [x] closes #13628 - [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/27933
2019-08-15T14:12:40Z
2019-08-16T12:14:43Z
2019-08-16T12:14:43Z
2019-10-29T12:12:31Z
BUG: Ensure that fill_na in Categorical only replaces null values
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 21f1fa7ddec1f..647bc750907ce 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -25,7 +25,7 @@ Bug fixes Categorical ^^^^^^^^^^^ -- +- Bug in :meth:`Categorical.fillna` would replace all values, not just those that are ``NaN`` (:issue:`26215`) - - diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index bbbeb812d1fe9..a895da6184eeb 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1840,8 +1840,8 @@ def fillna(self, value=None, method=None, limit=None): raise ValueError("fill value must be in categories") values_codes = _get_codes_for_values(value, self.categories) - indexer = np.where(values_codes != -1) - codes[indexer] = values_codes[values_codes != -1] + indexer = np.where(codes == -1) + codes[indexer] = values_codes[indexer] # If value is not a dict or Series it should be a scalar elif is_hashable(value): diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index f1b84acf68755..ddd2c566f4cda 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -578,6 +578,28 @@ def test_fillna_categorical(self, fill_value, expected_output): exp = Series(Categorical(expected_output, categories=["a", "b"])) tm.assert_series_equal(s.fillna(fill_value), exp) + @pytest.mark.parametrize( + "fill_value, expected_output", + [ + (Series(["a", "b", "c", "d", "e"]), ["a", "b", "b", "d", "e"]), + (Series(["b", "d", "a", "d", "a"]), ["a", "d", "b", "d", "a"]), + ( + Series( + Categorical( + ["b", "d", "a", "d", "a"], categories=["b", "c", "d", "e", "a"] + ) + ), + ["a", "d", "b", "d", "a"], + ), + ], + ) + def test_fillna_categorical_with_new_categories(self, fill_value, expected_output): + # GH 26215 + data = ["a", np.nan, "b", np.nan, np.nan] + s = Series(Categorical(data, categories=["a", "b", "c", "d", "e"])) + exp = Series(Categorical(expected_output, categories=["a", "b", "c", "d", "e"])) + tm.assert_series_equal(s.fillna(fill_value), exp) + def test_fillna_categorical_raise(self): data = ["a", np.nan, "b", np.nan, np.nan] s = Series(Categorical(data, categories=["a", "b"]))
- [x] closes #26215 - [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/27932
2019-08-15T13:27:46Z
2019-08-16T11:22:20Z
2019-08-16T11:22:19Z
2019-08-22T08:38:45Z
API/DEPR: Change default skipna behaviour + deprecate numeric_only in Categorical.min and max
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 3f8d9d3916797..ee5098749105f 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -260,6 +260,26 @@ The following methods now also correctly output values for unobserved categories df.groupby(["cat_1", "cat_2"], observed=False)["value"].count() +By default :meth:`Categorical.min` now returns the minimum instead of np.nan +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +When :class:`Categorical` contains ``np.nan``, +:meth:`Categorical.min` no longer return ``np.nan`` by default (skipna=True) (:issue:`25303`) + +*pandas 0.25.x* + +.. code-block:: ipython + + In [1]: pd.Categorical([1, 2, np.nan], ordered=True).min() + Out[1]: nan + + +*pandas 1.0.0* + +.. ipython:: python + + pd.Categorical([1, 2, np.nan], ordered=True).min() + .. _whatsnew_1000.api_breaking.deps: Increased minimum versions for dependencies @@ -366,6 +386,8 @@ Deprecations - :func:`is_extension_type` is deprecated, :func:`is_extension_array_dtype` should be used instead (:issue:`29457`) - :func:`eval` keyword argument "truediv" is deprecated and will be removed in a future version (:issue:`29812`) - :meth:`Categorical.take_nd` is deprecated, use :meth:`Categorical.take` instead (:issue:`27745`) +- The parameter ``numeric_only`` of :meth:`Categorical.min` and :meth:`Categorical.max` is deprecated and replaced with ``skipna`` (:issue:`25303`) +- .. _whatsnew_1000.prior_deprecations: diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index ec1f5d2d6214c..6a7a225845440 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -2157,7 +2157,8 @@ def _reduce(self, name, axis=0, **kwargs): raise TypeError(f"Categorical cannot perform the operation {name}") return func(**kwargs) - def min(self, numeric_only=None, **kwargs): + @deprecate_kwarg(old_arg_name="numeric_only", new_arg_name="skipna") + def min(self, skipna=True): """ The minimum value of the object. @@ -2173,17 +2174,18 @@ def min(self, numeric_only=None, **kwargs): min : the minimum of this `Categorical` """ self.check_for_ordered("min") - if numeric_only: - good = self._codes != -1 - pointer = self._codes[good].min(**kwargs) - else: - pointer = self._codes.min(**kwargs) - if pointer == -1: - return np.nan + good = self._codes != -1 + if not good.all(): + if skipna: + pointer = self._codes[good].min() + else: + return np.nan else: - return self.categories[pointer] + pointer = self._codes.min() + return self.categories[pointer] - def max(self, numeric_only=None, **kwargs): + @deprecate_kwarg(old_arg_name="numeric_only", new_arg_name="skipna") + def max(self, skipna=True): """ The maximum value of the object. @@ -2199,15 +2201,15 @@ def max(self, numeric_only=None, **kwargs): max : the maximum of this `Categorical` """ self.check_for_ordered("max") - if numeric_only: - good = self._codes != -1 - pointer = self._codes[good].max(**kwargs) - else: - pointer = self._codes.max(**kwargs) - if pointer == -1: - return np.nan + good = self._codes != -1 + if not good.all(): + if skipna: + pointer = self._codes[good].max() + else: + return np.nan else: - return self.categories[pointer] + pointer = self._codes.max() + return self.categories[pointer] def mode(self, dropna=True): """ diff --git a/pandas/core/series.py b/pandas/core/series.py index 56039605651ac..01a8231f5fd02 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3869,9 +3869,7 @@ def _reduce( self._get_axis_number(axis) if isinstance(delegate, Categorical): - # TODO deprecate numeric_only argument for Categorical and use - # skipna as well, see GH25303 - return delegate._reduce(name, numeric_only=numeric_only, **kwds) + return delegate._reduce(name, skipna=skipna, **kwds) elif isinstance(delegate, ExtensionArray): # dispatch to ExtensionArray interface return delegate._reduce(name, skipna=skipna, **kwds) diff --git a/pandas/tests/arrays/categorical/test_analytics.py b/pandas/tests/arrays/categorical/test_analytics.py index 279f1492d7dad..637a47eba0597 100644 --- a/pandas/tests/arrays/categorical/test_analytics.py +++ b/pandas/tests/arrays/categorical/test_analytics.py @@ -35,31 +35,43 @@ def test_min_max(self): assert _min == "d" assert _max == "a" + @pytest.mark.parametrize("skipna", [True, False]) + def test_min_max_with_nan(self, skipna): + # GH 25303 cat = Categorical( [np.nan, "b", "c", np.nan], categories=["d", "c", "b", "a"], ordered=True ) - _min = cat.min() - _max = cat.max() - assert np.isnan(_min) - assert _max == "b" + _min = cat.min(skipna=skipna) + _max = cat.max(skipna=skipna) - _min = cat.min(numeric_only=True) - assert _min == "c" - _max = cat.max(numeric_only=True) - assert _max == "b" + if skipna is False: + assert np.isnan(_min) + assert np.isnan(_max) + else: + assert _min == "c" + assert _max == "b" cat = Categorical( [np.nan, 1, 2, np.nan], categories=[5, 4, 3, 2, 1], ordered=True ) - _min = cat.min() - _max = cat.max() - assert np.isnan(_min) - assert _max == 1 - - _min = cat.min(numeric_only=True) - assert _min == 2 - _max = cat.max(numeric_only=True) - assert _max == 1 + _min = cat.min(skipna=skipna) + _max = cat.max(skipna=skipna) + + if skipna is False: + assert np.isnan(_min) + assert np.isnan(_max) + else: + assert _min == 2 + assert _max == 1 + + @pytest.mark.parametrize("method", ["min", "max"]) + def test_deprecate_numeric_only_min_max(self, method): + # GH 25303 + cat = Categorical( + [np.nan, 1, 2, np.nan], categories=[5, 4, 3, 2, 1], ordered=True + ) + with tm.assert_produces_warning(expected_warning=FutureWarning): + getattr(cat, method)(numeric_only=True) @pytest.mark.parametrize( "values,categories,exp_mode", diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index b0ef0c58ca65a..80d148c919ab2 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -1043,7 +1043,7 @@ def test_min_max(self): ) _min = cat.min() _max = cat.max() - assert np.isnan(_min) + assert _min == "c" assert _max == "b" cat = Series( @@ -1053,30 +1053,24 @@ def test_min_max(self): ) _min = cat.min() _max = cat.max() - assert np.isnan(_min) + assert _min == 2 assert _max == 1 - def test_min_max_numeric_only(self): - # TODO deprecate numeric_only argument for Categorical and use - # skipna as well, see GH25303 + @pytest.mark.parametrize("skipna", [True, False]) + def test_min_max_skipna(self, skipna): + # GH 25303 cat = Series( Categorical(["a", "b", np.nan, "a"], categories=["b", "a"], ordered=True) ) + _min = cat.min(skipna=skipna) + _max = cat.max(skipna=skipna) - _min = cat.min() - _max = cat.max() - assert np.isnan(_min) - assert _max == "a" - - _min = cat.min(numeric_only=True) - _max = cat.max(numeric_only=True) - assert _min == "b" - assert _max == "a" - - _min = cat.min(numeric_only=False) - _max = cat.max(numeric_only=False) - assert np.isnan(_min) - assert _max == "a" + if skipna is True: + assert _min == "b" + assert _max == "a" + else: + assert np.isnan(_min) + assert np.isnan(_max) class TestSeriesMode:
- closes #25303 and follow up https://github.com/pandas-dev/pandas/pull/27801#discussion_r313075771 - 1 test added - passes `black pandas` - passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27929
2019-08-15T10:33:36Z
2019-12-02T10:37:12Z
2019-12-02T10:37:12Z
2023-12-11T23:49:50Z
Assignment of column via .loc for numpy non-ns datetimes
diff --git a/doc/source/whatsnew/v0.25.2.rst b/doc/source/whatsnew/v0.25.2.rst index 69f324211e5b2..de411ef63680a 100644 --- a/doc/source/whatsnew/v0.25.2.rst +++ b/doc/source/whatsnew/v0.25.2.rst @@ -52,7 +52,6 @@ Indexing - - - -- Missing ^^^^^^^ diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 77807a338d21f..2913d88fcd15f 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -170,6 +170,7 @@ Indexing - Bug in assignment using a reverse slicer (:issue:`26939`) - Bug in reindexing a :meth:`PeriodIndex` with another type of index that contained a `Period` (:issue:`28323`) (:issue:`28337`) +- Fix assignment of column via `.loc` with numpy non-ns datetime type (:issue:`27395`) Missing ^^^^^^^ diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 749dd735e159d..ac9b57dc8d342 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1029,7 +1029,10 @@ def maybe_cast_to_datetime(value, dtype, errors="raise"): ) if is_datetime64 and not is_dtype_equal(dtype, _NS_DTYPE): - if dtype.name in ("datetime64", "datetime64[ns]"): + + # pandas supports dtype whose granularity is less than [ns] + # e.g., [ps], [fs], [as] + if dtype <= np.dtype("M8[ns]"): if dtype.name == "datetime64": raise ValueError(msg.format(dtype=dtype.name)) dtype = _NS_DTYPE @@ -1047,7 +1050,10 @@ def maybe_cast_to_datetime(value, dtype, errors="raise"): value = [value] elif is_timedelta64 and not is_dtype_equal(dtype, _TD_DTYPE): - if dtype.name in ("timedelta64", "timedelta64[ns]"): + + # pandas supports dtype whose granularity is less than [ns] + # e.g., [ps], [fs], [as] + if dtype <= np.dtype("m8[ns]"): if dtype.name == "timedelta64": raise ValueError(msg.format(dtype=dtype.name)) dtype = _TD_DTYPE diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 9845b1ac3a4b9..35291efecd1ac 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -690,6 +690,28 @@ def test_loc_setitem_consistency_slice_column_len(self): ) tm.assert_series_equal(df[("Respondent", "Duration")], expected) + @pytest.mark.parametrize("unit", ["Y", "M", "D", "h", "m", "s", "ms", "us"]) + def test_loc_assign_non_ns_datetime(self, unit): + # GH 27395, non-ns dtype assignment via .loc should work + # and return the same result when using simple assignment + df = DataFrame( + { + "timestamp": [ + np.datetime64("2017-02-11 12:41:29"), + np.datetime64("1991-11-07 04:22:37"), + ] + } + ) + + df.loc[:, unit] = df.loc[:, "timestamp"].values.astype( + "datetime64[{unit}]".format(unit=unit) + ) + df["expected"] = df.loc[:, "timestamp"].values.astype( + "datetime64[{unit}]".format(unit=unit) + ) + expected = Series(df.loc[:, "expected"], name=unit) + tm.assert_series_equal(df.loc[:, unit], expected) + def test_loc_setitem_frame(self): df = self.frame_labels
- [x] closes #27395 - [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/27928
2019-08-15T07:16:16Z
2019-09-13T13:19:38Z
2019-09-13T13:19:38Z
2019-09-13T13:19:42Z
Fix regression in .ix fallback with IntervalIndex
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index dfa216b1db56e..1cc0da8fcc7b3 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -85,6 +85,7 @@ Indexing - Bug in partial-string indexing returning a NumPy array rather than a ``Series`` when indexing with a scalar like ``.loc['2015']`` (:issue:`27516`) - Break reference cycle involving :class:`Index` to allow garbage collection of :class:`Index` objects without running the GC. (:issue:`27585`) - Fix regression in assigning values to a single column of a DataFrame with a ``MultiIndex`` columns (:issue:`27841`). +- Fix regression in ``.ix`` fallback with an ``IntervalIndex`` (:issue:`27865`). - Missing diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index ea00737f776ee..7bb5e2fa3018d 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -124,7 +124,7 @@ def __getitem__(self, key): key = tuple(com.apply_if_callable(x, self.obj) for x in key) try: values = self.obj._get_value(*key) - except (KeyError, TypeError, InvalidIndexError): + except (KeyError, TypeError, InvalidIndexError, AttributeError): # TypeError occurs here if the key has non-hashable entries, # generally slice or list. # TODO(ix): most/all of the TypeError cases here are for ix, @@ -132,6 +132,9 @@ def __getitem__(self, key): # The InvalidIndexError is only catched for compatibility # with geopandas, see # https://github.com/pandas-dev/pandas/issues/27258 + # TODO: The AttributeError is for IntervalIndex which + # incorrectly implements get_value, see + # https://github.com/pandas-dev/pandas/issues/27865 pass else: if is_scalar(values): diff --git a/pandas/tests/indexing/test_ix.py b/pandas/tests/indexing/test_ix.py index 45ccd8d1b8fb3..6029db8ed66f6 100644 --- a/pandas/tests/indexing/test_ix.py +++ b/pandas/tests/indexing/test_ix.py @@ -343,3 +343,13 @@ def test_ix_duplicate_returns_series(self): 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)
closes #27865 cc @jbrockmendel this is another one from limiting the catched exceptions in https://github.com/pandas-dev/pandas/pull/27223/files#diff-7489e290a23303c4db4f803011ecaf8eR121. But also this time it's again rather a bug in the code that raises this error. For some reason, `DataFrame._get_value` for a DataFrame with an IntervalIndex raises an AttributeError. That's a bug in itself which should be solved (and probably is the cause of more bugs in other places where `_get_value` is used, eg in `.at`). But will open a separate issue for that.
https://api.github.com/repos/pandas-dev/pandas/pulls/27926
2019-08-15T06:54:38Z
2019-08-19T19:26:21Z
2019-08-19T19:26:21Z
2019-08-20T06:47:37Z
BUG: Help python csv engine read binary buffers
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 0be4ebc627b30..3ce558ca336c3 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -158,7 +158,7 @@ MultiIndex I/O ^^^ -- +- :meth:`read_csv` now accepts binary mode file buffers when using the Python csv engine (:issue:`23779`) - Plotting diff --git a/pandas/io/common.py b/pandas/io/common.py index ac57cef372399..26b68dda7b464 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -5,7 +5,7 @@ import csv import gzip from http.client import HTTPException # noqa -from io import BytesIO +from io import BufferedIOBase, BytesIO import mmap import os import pathlib @@ -344,9 +344,9 @@ def _get_handle( try: from s3fs import S3File - need_text_wrapping = (BytesIO, S3File) + need_text_wrapping = (BufferedIOBase, S3File) except ImportError: - need_text_wrapping = (BytesIO,) + need_text_wrapping = BufferedIOBase handles = list() f = path_or_buf @@ -422,8 +422,10 @@ def _get_handle( if is_text and (compression or isinstance(f, need_text_wrapping)): from io import TextIOWrapper - f = TextIOWrapper(f, encoding=encoding, newline="") - handles.append(f) + g = TextIOWrapper(f, encoding=encoding, newline="") + if not isinstance(f, BufferedIOBase): + handles.append(g) + f = g if memory_map and hasattr(f, "fileno"): try: diff --git a/pandas/tests/io/parser/test_common.py b/pandas/tests/io/parser/test_common.py index b94d5cd497ccf..e5366a8357adb 100644 --- a/pandas/tests/io/parser/test_common.py +++ b/pandas/tests/io/parser/test_common.py @@ -2020,9 +2020,34 @@ def test_file_handles_with_open(all_parsers, csv1): # Don't close user provided file handles. parser = all_parsers - with open(csv1, "r") as f: - parser.read_csv(f) - assert not f.closed + for mode in ["r", "rb"]: + with open(csv1, mode) as f: + parser.read_csv(f) + assert not f.closed + + +@pytest.mark.parametrize( + "fname,encoding", + [ + ("test1.csv", "utf-8"), + ("unicode_series.csv", "latin-1"), + ("sauron.SHIFT_JIS.csv", "shiftjis"), + ], +) +def test_binary_mode_file_buffers(all_parsers, csv_dir_path, fname, encoding): + # gh-23779: Python csv engine shouldn't error on files opened in binary. + parser = all_parsers + + fpath = os.path.join(csv_dir_path, fname) + expected = parser.read_csv(fpath, encoding=encoding) + + with open(fpath, mode="r", encoding=encoding) as fa: + result = parser.read_csv(fa) + tm.assert_frame_equal(expected, result) + + with open(fpath, mode="rb") as fb: + result = parser.read_csv(fb, encoding=encoding) + tm.assert_frame_equal(expected, result) def test_invalid_file_buffer_class(all_parsers):
The file buffer given to read_csv could have been opened in binary mode, but the python csv reader errors on binary buffers. - [x] closes #23779 - [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/27925
2019-08-15T04:15:34Z
2019-08-19T16:23:41Z
2019-08-19T16:23:41Z
2019-08-19T16:23:41Z
CLN: simplify comparison method, docstring cleanups
diff --git a/pandas/core/computation/common.py b/pandas/core/computation/common.py index b8e212fd2a32e..2a4277e4e0a20 100644 --- a/pandas/core/computation/common.py +++ b/pandas/core/computation/common.py @@ -2,7 +2,7 @@ import numpy as np -import pandas as pd +from pandas._config import get_option # A token value Python's tokenizer probably will never use. _BACKTICK_QUOTED_STRING = 100 @@ -11,7 +11,7 @@ def _ensure_decoded(s): """ if we have bytes, decode them to unicode """ if isinstance(s, (np.bytes_, bytes)): - s = s.decode(pd.get_option("display.encoding")) + s = s.decode(get_option("display.encoding")) return s diff --git a/pandas/core/computation/expressions.py b/pandas/core/computation/expressions.py index d9dc194d484ae..0ecf56cf6fe96 100644 --- a/pandas/core/computation/expressions.py +++ b/pandas/core/computation/expressions.py @@ -203,17 +203,18 @@ def _bool_arith_check( def evaluate(op, op_str, a, b, use_numexpr=True, **eval_kwargs): - """ evaluate and return the expression of the op on a and b - - Parameters - ---------- - - op : the actual operand - op_str: the string version of the op - a : left operand - b : right operand - use_numexpr : whether to try to use numexpr (default True) - """ + """ + Evaluate and return the expression of the op on a and b. + + Parameters + ---------- + op : the actual operand + op_str : the string version of the op + a : left operand + b : right operand + use_numexpr : bool, default True + Whether to try to use numexpr. + """ use_numexpr = use_numexpr and _bool_arith_check(op_str, a, b) if use_numexpr: @@ -222,16 +223,17 @@ def evaluate(op, op_str, a, b, use_numexpr=True, **eval_kwargs): def where(cond, a, b, use_numexpr=True): - """ evaluate the where condition cond on a and b - - Parameters - ---------- - - cond : a boolean array - a : return if cond is True - b : return if cond is False - use_numexpr : whether to try to use numexpr (default True) - """ + """ + Evaluate the where condition cond on a and b + + Parameters + ---------- + cond : ndarray[bool] + a : return if cond is True + b : return if cond is False + use_numexpr : bool, default True + Whether to try to use numexpr. + """ if use_numexpr: return _where(cond, a, b) diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index 2bf09a553ce18..b49220ae701bc 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -51,8 +51,9 @@ class UndefinedVariableError(NameError): - - """NameError subclass for local variables.""" + """ + NameError subclass for local variables. + """ def __init__(self, name, is_local): if is_local: @@ -191,8 +192,8 @@ def __repr__(self): class Op: - - """Hold an operator of arbitrary arity + """ + Hold an operator of arbitrary arity. """ def __init__(self, op, operands, *args, **kwargs): @@ -204,8 +205,9 @@ def __iter__(self): return iter(self.operands) def __repr__(self): - """Print a generic n-ary operator and its operands using infix - notation""" + """ + Print a generic n-ary operator and its operands using infix notation. + """ # recurse over the operands parened = ("({0})".format(pprint_thing(opr)) for opr in self.operands) return pprint_thing(" {0} ".format(self.op).join(parened)) @@ -296,7 +298,8 @@ def _not_in(x, y): def _cast_inplace(terms, acceptable_dtypes, dtype): - """Cast an expression inplace. + """ + Cast an expression inplace. Parameters ---------- @@ -304,7 +307,6 @@ def _cast_inplace(terms, acceptable_dtypes, dtype): The expression that should cast. acceptable_dtypes : list of acceptable numpy.dtype Will not cast if term's dtype in this list. - dtype : str or numpy.dtype The dtype to cast to. """ @@ -325,8 +327,8 @@ def is_term(obj): class BinOp(Op): - - """Hold a binary operator and its operands + """ + Hold a binary operator and its operands. Parameters ---------- @@ -355,7 +357,8 @@ def __init__(self, op, lhs, rhs, **kwargs): ) def __call__(self, env): - """Recursively evaluate an expression in Python space. + """ + Recursively evaluate an expression in Python space. Parameters ---------- @@ -377,7 +380,8 @@ def __call__(self, env): return self.func(left, right) def evaluate(self, env, engine, parser, term_type, eval_in_python): - """Evaluate a binary operation *before* being passed to the engine. + """ + Evaluate a binary operation *before* being passed to the engine. Parameters ---------- diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 843f12c20b07b..26672593f98fb 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -32,7 +32,6 @@ is_period_dtype, is_scalar, is_timedelta64_dtype, - needs_i8_conversion, ) from pandas.core.dtypes.generic import ( ABCDataFrame, @@ -758,17 +757,12 @@ def _comp_method_SERIES(cls, op, special): code duplication. """ op_name = _get_op_name(op, special) - masker = _gen_eval_kwargs(op_name).get("masker", False) def na_op(x, y): # TODO: - # should have guarantess on what x, y can be type-wise + # should have guarantees on what x, y can be type-wise # Extension Dtypes are not called here - # Checking that cases that were once handled here are no longer - # reachable. - assert not (is_categorical_dtype(y) and not is_scalar(y)) - if is_object_dtype(x.dtype): result = _comp_method_OBJECT_ARRAY(op, x, y) @@ -776,32 +770,11 @@ def na_op(x, y): return invalid_comparison(x, y, op) else: - - # we want to compare like types - # we only want to convert to integer like if - # we are not NotImplemented, otherwise - # we would allow datetime64 (but viewed as i8) against - # integer comparisons - - # we have a datetime/timedelta and may need to convert - assert not needs_i8_conversion(x) - mask = None - if not is_scalar(y) and needs_i8_conversion(y): - mask = isna(x) | isna(y) - y = y.view("i8") - x = x.view("i8") - - method = getattr(x, op_name, None) - if method is not None: - with np.errstate(all="ignore"): - result = method(y) - if result is NotImplemented: - return invalid_comparison(x, y, op) - else: - result = op(x, y) - - if mask is not None and mask.any(): - result[mask] = masker + method = getattr(x, op_name) + with np.errstate(all="ignore"): + result = method(y) + if result is NotImplemented: + return invalid_comparison(x, y, op) return result
https://api.github.com/repos/pandas-dev/pandas/pulls/27923
2019-08-15T02:41:41Z
2019-08-15T12:44:11Z
2019-08-15T12:44:11Z
2019-08-15T14:20:33Z
CLN: Remove incorrect check, comment, rename
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 0de28f0a4a8b3..7e03b9544ee72 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -730,9 +730,12 @@ def wrapper(self, other, axis=None): ) result = self._constructor(res_values, index=self.index) - # rename is needed in case res_name is None and result.name - # is not. - return finalizer(result).rename(res_name) + result = finalizer(result) + + # Set the result's name after finalizer is called because finalizer + # would set it back to self.name + result.name = res_name + return result wrapper.__name__ = op_name return wrapper
cc @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/27922
2019-08-14T21:47:59Z
2019-08-20T06:35:43Z
2019-08-20T06:35:43Z
2019-08-20T14:01:01Z
BUG: Lambda function returns KeyError in DataFrameGroupBy.agg
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 2bfc09e52c68b..a436dcbf60ac4 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -177,6 +177,7 @@ Groupby/resample/rolling - - - Bug in :meth:`DataFrame.groupby` not offering selection by column name when ``axis=1`` (:issue:`27614`) +- Bug in :meth:`DataFrameGroupby.agg` not able to use lambda function with named aggregation (:issue:`27519`) Reshaping ^^^^^^^^^ diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index ea2bd22cccc3d..e3bc90f49a08f 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -268,7 +268,9 @@ def aggregate(self, func, *args, **kwargs): result.index = np.arange(len(result)) if relabeling: - result = result[order] + + # used reordered index of columns + result = result.iloc[:, order] result.columns = columns return result._convert(datetime=True) @@ -1731,8 +1733,8 @@ def _normalize_keyword_aggregation(kwargs): The transformed kwargs. columns : List[str] The user-provided keys. - order : List[Tuple[str, str]] - Pairs of the input and output column names. + col_idx_order : List[int] + List of columns indices. Examples -------- @@ -1759,7 +1761,39 @@ def _normalize_keyword_aggregation(kwargs): else: aggspec[column] = [aggfunc] order.append((column, com.get_callable_name(aggfunc) or aggfunc)) - return aggspec, columns, order + + # uniquify aggfunc name if duplicated in order list + uniquified_order = _make_unique(order) + + # GH 25719, due to aggspec will change the order of assigned columns in aggregation + # uniquified_aggspec will store uniquified order list and will compare it with order + # based on index + aggspec_order = [ + (column, com.get_callable_name(aggfunc) or aggfunc) + for column, aggfuncs in aggspec.items() + for aggfunc in aggfuncs + ] + uniquified_aggspec = _make_unique(aggspec_order) + + # get the new indice of columns by comparison + col_idx_order = Index(uniquified_aggspec).get_indexer(uniquified_order) + return aggspec, columns, col_idx_order + + +def _make_unique(seq): + """Uniquify aggfunc name of the pairs in the order list + + Examples: + -------- + >>> _make_unique([('a', '<lambda>'), ('a', '<lambda>'), ('b', '<lambda>')]) + [('a', '<lambda>_0'), ('a', '<lambda>_1'), ('b', '<lambda>')] + """ + return [ + (pair[0], "_".join([pair[1], str(seq[:i].count(pair))])) + if seq.count(pair) > 1 + else pair + for i, pair in enumerate(seq) + ] # TODO: Can't use, because mypy doesn't like us setting __name__ diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index 52d4fa76bf879..aa80c461a00e7 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -10,7 +10,7 @@ import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series, compat, concat from pandas.core.base import SpecificationError -from pandas.core.groupby.generic import _maybe_mangle_lambdas +from pandas.core.groupby.generic import _make_unique, _maybe_mangle_lambdas from pandas.core.groupby.grouper import Grouping import pandas.util.testing as tm @@ -560,3 +560,150 @@ def test_with_kwargs(self): result = pd.Series([1, 2]).groupby([0, 0]).agg([f1, f2], 0, b=10) expected = pd.DataFrame({"<lambda_0>": [13], "<lambda_1>": [30]}) tm.assert_frame_equal(result, expected) + + def test_agg_with_one_lambda(self): + # GH 25719, write tests for DataFrameGroupby.agg with only one lambda + df = pd.DataFrame( + { + "kind": ["cat", "dog", "cat", "dog"], + "height": [9.1, 6.0, 9.5, 34.0], + "weight": [7.9, 7.5, 9.9, 198.0], + } + ) + + # sort for 35 and earlier + columns = ["height_sqr_min", "height_max", "weight_max"] + if compat.PY35: + columns = ["height_max", "height_sqr_min", "weight_max"] + expected = pd.DataFrame( + { + "height_sqr_min": [82.81, 36.00], + "height_max": [9.5, 34.0], + "weight_max": [9.9, 198.0], + }, + index=pd.Index(["cat", "dog"], name="kind"), + columns=columns, + ) + + # check pd.NameAgg case + result1 = df.groupby(by="kind").agg( + height_sqr_min=pd.NamedAgg( + column="height", aggfunc=lambda x: np.min(x ** 2) + ), + height_max=pd.NamedAgg(column="height", aggfunc="max"), + weight_max=pd.NamedAgg(column="weight", aggfunc="max"), + ) + tm.assert_frame_equal(result1, expected) + + # check agg(key=(col, aggfunc)) case + result2 = df.groupby(by="kind").agg( + height_sqr_min=("height", lambda x: np.min(x ** 2)), + height_max=("height", "max"), + weight_max=("weight", "max"), + ) + tm.assert_frame_equal(result2, expected) + + def test_agg_multiple_lambda(self): + # GH25719, test for DataFrameGroupby.agg with multiple lambdas + # with mixed aggfunc + df = pd.DataFrame( + { + "kind": ["cat", "dog", "cat", "dog"], + "height": [9.1, 6.0, 9.5, 34.0], + "weight": [7.9, 7.5, 9.9, 198.0], + } + ) + # sort for 35 and earlier + columns = [ + "height_sqr_min", + "height_max", + "weight_max", + "height_max_2", + "weight_min", + ] + if compat.PY35: + columns = [ + "height_max", + "height_max_2", + "height_sqr_min", + "weight_max", + "weight_min", + ] + expected = pd.DataFrame( + { + "height_sqr_min": [82.81, 36.00], + "height_max": [9.5, 34.0], + "weight_max": [9.9, 198.0], + "height_max_2": [9.5, 34.0], + "weight_min": [7.9, 7.5], + }, + index=pd.Index(["cat", "dog"], name="kind"), + columns=columns, + ) + + # check agg(key=(col, aggfunc)) case + result1 = df.groupby(by="kind").agg( + height_sqr_min=("height", lambda x: np.min(x ** 2)), + height_max=("height", "max"), + weight_max=("weight", "max"), + height_max_2=("height", lambda x: np.max(x)), + weight_min=("weight", lambda x: np.min(x)), + ) + tm.assert_frame_equal(result1, expected) + + # check pd.NamedAgg case + result2 = df.groupby(by="kind").agg( + height_sqr_min=pd.NamedAgg( + column="height", aggfunc=lambda x: np.min(x ** 2) + ), + height_max=pd.NamedAgg(column="height", aggfunc="max"), + weight_max=pd.NamedAgg(column="weight", aggfunc="max"), + height_max_2=pd.NamedAgg(column="height", aggfunc=lambda x: np.max(x)), + weight_min=pd.NamedAgg(column="weight", aggfunc=lambda x: np.min(x)), + ) + tm.assert_frame_equal(result2, expected) + + @pytest.mark.parametrize( + "order, expected_reorder", + [ + ( + [ + ("height", "<lambda>"), + ("height", "max"), + ("weight", "max"), + ("height", "<lambda>"), + ("weight", "<lambda>"), + ], + [ + ("height", "<lambda>_0"), + ("height", "max"), + ("weight", "max"), + ("height", "<lambda>_1"), + ("weight", "<lambda>"), + ], + ), + ( + [ + ("col2", "min"), + ("col1", "<lambda>"), + ("col1", "<lambda>"), + ("col1", "<lambda>"), + ], + [ + ("col2", "min"), + ("col1", "<lambda>_0"), + ("col1", "<lambda>_1"), + ("col1", "<lambda>_2"), + ], + ), + ( + [("col", "<lambda>"), ("col", "<lambda>"), ("col", "<lambda>")], + [("col", "<lambda>_0"), ("col", "<lambda>_1"), ("col", "<lambda>_2")], + ), + ], + ) + def test_make_unique(self, order, expected_reorder): + # GH 27519, test if make_unique function reorders correctly + result = _make_unique(order) + + assert result == expected_reorder
- [x] closes #27519 - [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/27921
2019-08-14T21:16:03Z
2019-08-30T14:47:18Z
2019-08-30T14:47:17Z
2019-08-30T14:47:18Z
Updated table with read_fwf()
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index 947bf15a49c7a..ad250dedb7771 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -28,6 +28,7 @@ The pandas I/O API is a set of top level ``reader`` functions accessed like :delim: ; text;`CSV <https://en.wikipedia.org/wiki/Comma-separated_values>`__;:ref:`read_csv<io.read_csv_table>`;:ref:`to_csv<io.store_in_csv>` + text;`TXT <https://www.oracle.com/webfolder/technetwork/data-quality/edqhelp/Content/introduction/getting_started/configuring_fixed_width_text_file_formats.htm>`__;:ref:`read_fwf<io.fwf_reader>` text;`JSON <https://www.json.org/>`__;:ref:`read_json<io.json_reader>`;:ref:`to_json<io.json_writer>` text;`HTML <https://en.wikipedia.org/wiki/HTML>`__;:ref:`read_html<io.read_html>`;:ref:`to_html<io.html>` text; Local clipboard;:ref:`read_clipboard<io.clipboard>`;:ref:`to_clipboard<io.clipboard>` @@ -1372,6 +1373,7 @@ should pass the ``escapechar`` option: print(data) pd.read_csv(StringIO(data), escapechar='\\') +.. _io.fwf_reader: .. _io.fwf: Files with fixed width columns
- [X] closes #27884 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry @TomAugspurger Can you merge?
https://api.github.com/repos/pandas-dev/pandas/pulls/27920
2019-08-14T21:15:33Z
2019-08-19T11:43:35Z
2019-08-19T11:43:34Z
2019-08-19T12:04:35Z
DOC: Fix section reference placement in whatsnew
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index b35f230100f8d..aeed3668fe774 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -21,27 +21,27 @@ including other versions of pandas. Enhancements ~~~~~~~~~~~~ -.. _whatsnew_1000.enhancements.other: - - - +.. _whatsnew_1000.enhancements.other: + Other enhancements ^^^^^^^^^^^^^^^^^^ -.. _whatsnew_1000.api_breaking: - - - +.. _whatsnew_1000.api_breaking: + Backwards incompatible API changes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. _whatsnew_1000.api.other: - - :class:`pandas.core.groupby.GroupBy.transform` now raises on invalid operation names (:issue:`27489`). - +.. _whatsnew_1000.api.other: + Other API changes ^^^^^^^^^^^^^^^^^
A few of the section references are misaligned with the tick marks. Moved the misaligned references as appropriate.
https://api.github.com/repos/pandas-dev/pandas/pulls/27919
2019-08-14T20:41:21Z
2019-08-14T22:50:45Z
2019-08-14T22:50:45Z
2019-08-14T22:50:52Z
Backport PR #27840 on branch 0.25.x (PERF: Break reference cycle for all Index types)
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index a81fc19221ef7..b53b53c654ce3 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -83,7 +83,7 @@ Indexing ^^^^^^^^ - Bug in partial-string indexing returning a NumPy array rather than a ``Series`` when indexing with a scalar like ``.loc['2015']`` (:issue:`27516`) -- Break reference cycle involving :class:`Index` to allow garbage collection of :class:`Index` objects without running the GC. (:issue:`27585`) +- Break reference cycle involving :class:`Index` and other index classes to allow garbage collection of index objects without running the GC. (:issue:`27585`, :issue:`27840`) - Fix regression in assigning values to a single column of a DataFrame with a ``MultiIndex`` columns (:issue:`27841`). - diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index e49ad751ad150..680976f44ee1e 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -711,7 +711,7 @@ def _cleanup(self): def _engine(self): # property, for now, slow to look up - # to avoid a refernce cycle, bind `_ndarray_values` to a local variable, so + # to avoid a reference cycle, bind `_ndarray_values` to a local variable, so # `self` is not passed into the lambda. _ndarray_values = self._ndarray_values return self._engine_type(lambda: _ndarray_values, len(self)) diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index e14bf7f86c0be..2b7d4ad7243ba 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -445,9 +445,11 @@ def argsort(self, *args, **kwargs): @cache_readonly def _engine(self): - - # we are going to look things up with the codes themselves - return self._engine_type(lambda: self.codes, len(self)) + # we are going to look things up with the codes themselves. + # To avoid a reference cycle, bind `codes` to a local variable, so + # `self` is not passed into the lambda. + codes = self.codes + return self._engine_type(lambda: codes, len(self)) # introspection @cache_readonly diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 96031645365c6..def2fdaa72768 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -1,5 +1,6 @@ from datetime import datetime, timedelta import warnings +import weakref import numpy as np @@ -438,7 +439,9 @@ def _formatter_func(self): @cache_readonly def _engine(self): - return self._engine_type(lambda: self, len(self)) + # To avoid a reference cycle, pass a weakref of self to _engine_type. + period = weakref.ref(self) + return self._engine_type(period, len(self)) @Appender(_index_shared_docs["contains"]) def __contains__(self, key): diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 9459069f0ea2d..0e74c87388682 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -1,3 +1,5 @@ +import gc + import numpy as np import pytest @@ -908,3 +910,10 @@ def test_is_unique(self): # multiple NA should not be unique index_na_dup = index_na.insert(0, np.nan) assert index_na_dup.is_unique is False + + def test_engine_reference_cycle(self): + # GH27585 + index = self.create_index() + nrefs_pre = len(gc.get_referrers(index)) + index._engine + assert len(gc.get_referrers(index)) == nrefs_pre diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index fe1eb96df1e97..d1ed79118d2fa 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1,6 +1,5 @@ from collections import defaultdict from datetime import datetime, timedelta -import gc from io import StringIO import math import operator @@ -2425,13 +2424,6 @@ def test_deprecated_contains(self): with tm.assert_produces_warning(FutureWarning): index.contains(1) - def test_engine_reference_cycle(self): - # https://github.com/pandas-dev/pandas/issues/27585 - index = pd.Index([1, 2, 3]) - nrefs_pre = len(gc.get_referrers(index)) - index._engine - assert len(gc.get_referrers(index)) == nrefs_pre - class TestMixedIntIndex(Base): # Mostly the tests from common.py for which the results differ
Backport PR #27840: PERF: Break reference cycle for all Index types
https://api.github.com/repos/pandas-dev/pandas/pulls/27918
2019-08-14T20:11:45Z
2019-08-14T21:56:07Z
2019-08-14T21:56:07Z
2019-08-14T21:56:07Z
Backport PR #27907 on branch 0.25.x (Revert 37 pins)
diff --git a/ci/deps/azure-37-locale.yaml b/ci/deps/azure-37-locale.yaml index 6844e929eae78..05adbf0c924dc 100644 --- a/ci/deps/azure-37-locale.yaml +++ b/ci/deps/azure-37-locale.yaml @@ -17,7 +17,7 @@ dependencies: - openpyxl - pytables - python-dateutil - - python=3.7.3 + - python=3.7.* - pytz - s3fs - scipy diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml index 3b68a573497e6..5cf897c98da10 100644 --- a/ci/deps/azure-37-numpydev.yaml +++ b/ci/deps/azure-37-numpydev.yaml @@ -2,7 +2,7 @@ name: pandas-dev channels: - defaults dependencies: - - python=3.7.3 + - python=3.7.* - pytz - Cython>=0.28.2 # universal diff --git a/ci/deps/travis-37.yaml b/ci/deps/travis-37.yaml index 2d7f4b483729f..c9a8c274fb144 100644 --- a/ci/deps/travis-37.yaml +++ b/ci/deps/travis-37.yaml @@ -4,7 +4,7 @@ channels: - conda-forge - c3i_test dependencies: - - python=3.7.3 + - python=3.7.* - botocore>=1.11 - cython>=0.28.2 - numpy diff --git a/environment.yml b/environment.yml index d54caf9d013c7..93e8302b498a0 100644 --- a/environment.yml +++ b/environment.yml @@ -5,7 +5,7 @@ channels: dependencies: # required - numpy>=1.15 - - python=3.7.3 + - python=3 - python-dateutil>=2.6.1 - pytz diff --git a/requirements-dev.txt b/requirements-dev.txt index 9d80a13350579..e49ad10bfc99d 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,5 +1,4 @@ numpy>=1.15 -python==3.7.3 python-dateutil>=2.6.1 pytz asv
Backport PR #27907: Revert 37 pins
https://api.github.com/repos/pandas-dev/pandas/pulls/27917
2019-08-14T19:34:39Z
2019-08-14T21:55:43Z
2019-08-14T21:55:43Z
2019-08-14T21:55:44Z
BUG: fix to_timestamp out_of_bounds
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 21f1fa7ddec1f..a6e85803244de 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -32,7 +32,7 @@ Categorical Datetimelike ^^^^^^^^^^^^ - Bug in :func:`to_datetime` where passing a timezone-naive :class:`DatetimeArray` or :class:`DatetimeIndex` and ``utc=True`` would incorrectly return a timezone-naive result (:issue:`27733`) -- +- Bug in :meth:`Period.to_timestamp` where a :class:`Period` outside the :class:`Timestamp` implementation bounds (roughly 1677-09-21 to 2262-04-11) would return an incorrect :class:`Timestamp` instead of raising ``OutOfBoundsDatetime`` (:issue:`19643`) - - diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index c68d686ff2bf2..98e55f50062a2 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -21,7 +21,8 @@ PyDateTime_IMPORT from pandas._libs.tslibs.np_datetime cimport ( npy_datetimestruct, dtstruct_to_dt64, dt64_to_dtstruct, - pandas_datetime_to_datetimestruct, NPY_DATETIMEUNIT, NPY_FR_D) + pandas_datetime_to_datetimestruct, check_dts_bounds, + NPY_DATETIMEUNIT, NPY_FR_D) cdef extern from "src/datetime/np_datetime.h": int64_t npy_datetimestruct_to_datetime(NPY_DATETIMEUNIT fr, @@ -1011,7 +1012,7 @@ def dt64arr_to_periodarr(int64_t[:] dtarr, int freq, tz=None): @cython.wraparound(False) @cython.boundscheck(False) -def periodarr_to_dt64arr(int64_t[:] periodarr, int freq): +def periodarr_to_dt64arr(const int64_t[:] periodarr, int freq): """ Convert array to datetime64 values from a set of ordinals corresponding to periods per period convention. @@ -1024,9 +1025,8 @@ def periodarr_to_dt64arr(int64_t[:] periodarr, int freq): out = np.empty(l, dtype='i8') - with nogil: - for i in range(l): - out[i] = period_ordinal_to_dt64(periodarr[i], freq) + for i in range(l): + out[i] = period_ordinal_to_dt64(periodarr[i], freq) return out.base # .base to access underlying np.ndarray @@ -1179,7 +1179,7 @@ cpdef int64_t period_ordinal(int y, int m, int d, int h, int min, return get_period_ordinal(&dts, freq) -cpdef int64_t period_ordinal_to_dt64(int64_t ordinal, int freq) nogil: +cdef int64_t period_ordinal_to_dt64(int64_t ordinal, int freq) except? -1: cdef: npy_datetimestruct dts @@ -1187,6 +1187,7 @@ cpdef int64_t period_ordinal_to_dt64(int64_t ordinal, int freq) nogil: return NPY_NAT get_date_info(ordinal, freq, &dts) + check_dts_bounds(&dts) return dtstruct_to_dt64(&dts) diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 0b3ccc0ae0e2d..7c482664bca48 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -1,6 +1,8 @@ import numpy as np import pytest +from pandas._libs import OutOfBoundsDatetime + import pandas as pd from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray import pandas.util.testing as tm @@ -615,6 +617,15 @@ def test_to_timestamp(self, how, period_index): # an EA-specific tm.assert_ function tm.assert_index_equal(pd.Index(result), pd.Index(expected)) + def test_to_timestamp_out_of_bounds(self): + # GH#19643 previously overflowed silently + pi = pd.period_range("1500", freq="Y", periods=3) + with pytest.raises(OutOfBoundsDatetime): + pi.to_timestamp() + + with pytest.raises(OutOfBoundsDatetime): + pi._data.to_timestamp() + @pytest.mark.parametrize("propname", PeriodArray._bool_ops) def test_bool_properties(self, period_index, propname): # in this case _bool_ops is just `is_leap_year` diff --git a/pandas/tests/scalar/period/test_asfreq.py b/pandas/tests/scalar/period/test_asfreq.py index 4cff061cabc40..357274e724c68 100644 --- a/pandas/tests/scalar/period/test_asfreq.py +++ b/pandas/tests/scalar/period/test_asfreq.py @@ -30,11 +30,8 @@ def test_asfreq_near_zero_weekly(self): assert week1.asfreq("D", "E") >= per1 assert week2.asfreq("D", "S") <= per2 - @pytest.mark.xfail( - reason="GH#19643 period_helper asfreq functions fail to check for overflows" - ) def test_to_timestamp_out_of_bounds(self): - # GH#19643, currently gives Timestamp('1754-08-30 22:43:41.128654848') + # GH#19643, used to incorrectly give Timestamp in 1754 per = Period("0001-01-01", freq="B") with pytest.raises(OutOfBoundsDatetime): per.to_timestamp()
- [x] closes #19643 - [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/27916
2019-08-14T15:28:09Z
2019-08-20T07:00:45Z
2019-08-20T07:00:45Z
2019-08-20T13:54:28Z
STYLE: run pre-commit filters on the repo
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 32ffb3330564c..5cc22c638c9b1 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,17 +1,21 @@ repos: - - repo: https://github.com/python/black - rev: stable - hooks: - - id: black - language_version: python3.7 - - repo: https://gitlab.com/pycqa/flake8 - rev: 3.7.7 - hooks: - - id: flake8 - language: python_venv - additional_dependencies: [flake8-comprehensions] - - repo: https://github.com/pre-commit/mirrors-isort - rev: v4.3.20 - hooks: - - id: isort - language: python_venv +- repo: https://github.com/python/black + rev: stable + hooks: + - id: black + language_version: python3.7 +- repo: https://gitlab.com/pycqa/flake8 + rev: 3.7.7 + hooks: + - id: flake8 + language: python_venv + additional_dependencies: [flake8-comprehensions] +- repo: https://github.com/pre-commit/mirrors-isort + rev: v4.3.20 + hooks: + - id: isort + language: python_venv +- repo: https://github.com/asottile/seed-isort-config + rev: v1.9.2 + hooks: + - id: seed-isort-config diff --git a/asv_bench/benchmarks/attrs_caching.py b/asv_bench/benchmarks/attrs_caching.py index c43e5dfd729aa..501e27b9078ec 100644 --- a/asv_bench/benchmarks/attrs_caching.py +++ b/asv_bench/benchmarks/attrs_caching.py @@ -1,4 +1,5 @@ import numpy as np + from pandas import DataFrame try: @@ -32,4 +33,4 @@ def time_cache_readonly(self): self.obj.prop -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/binary_ops.py b/asv_bench/benchmarks/binary_ops.py index fd3324b78f1c3..58e0db67d6025 100644 --- a/asv_bench/benchmarks/binary_ops.py +++ b/asv_bench/benchmarks/binary_ops.py @@ -1,4 +1,5 @@ import numpy as np + from pandas import DataFrame, Series, date_range from pandas.core.algorithms import checked_add_with_arr @@ -155,4 +156,4 @@ def time_add_overflow_both_arg_nan(self): ) -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py index 8097118a79d20..559aa7050a640 100644 --- a/asv_bench/benchmarks/categoricals.py +++ b/asv_bench/benchmarks/categoricals.py @@ -1,7 +1,9 @@ +import warnings + import numpy as np + import pandas as pd import pandas.util.testing as tm -import warnings try: from pandas.api.types import union_categoricals @@ -280,4 +282,4 @@ def time_sort_values(self): self.index.sort_values(ascending=False) -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/ctors.py b/asv_bench/benchmarks/ctors.py index 654075292cdf6..ec3dd7a48a89f 100644 --- a/asv_bench/benchmarks/ctors.py +++ b/asv_bench/benchmarks/ctors.py @@ -1,6 +1,7 @@ import numpy as np + +from pandas import DatetimeIndex, Index, MultiIndex, Series, Timestamp import pandas.util.testing as tm -from pandas import Series, Index, DatetimeIndex, Timestamp, MultiIndex def no_change(arr): @@ -113,4 +114,4 @@ def time_multiindex_from_iterables(self): MultiIndex.from_product(self.iterables) -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/dtypes.py b/asv_bench/benchmarks/dtypes.py index 60800b1f9cae7..24cc1c6f9fa70 100644 --- a/asv_bench/benchmarks/dtypes.py +++ b/asv_bench/benchmarks/dtypes.py @@ -1,14 +1,14 @@ +import numpy as np + from pandas.api.types import pandas_dtype -import numpy as np from .pandas_vb_common import ( - numeric_dtypes, datetime_dtypes, - string_dtypes, extension_dtypes, + numeric_dtypes, + string_dtypes, ) - _numpy_dtypes = [ np.dtype(dtype) for dtype in (numeric_dtypes + datetime_dtypes + string_dtypes) ] @@ -40,4 +40,4 @@ def time_pandas_dtype_invalid(self, dtype): pass -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/eval.py b/asv_bench/benchmarks/eval.py index 84e94315cc28b..06a181875aaa8 100644 --- a/asv_bench/benchmarks/eval.py +++ b/asv_bench/benchmarks/eval.py @@ -1,4 +1,5 @@ import numpy as np + import pandas as pd try: @@ -62,4 +63,4 @@ def time_query_with_boolean_selection(self): self.df.query("(a >= @self.min_val) & (a <= @self.max_val)") -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/frame_ctor.py b/asv_bench/benchmarks/frame_ctor.py index acfb26bcf5d7c..3944e0bc523d8 100644 --- a/asv_bench/benchmarks/frame_ctor.py +++ b/asv_bench/benchmarks/frame_ctor.py @@ -1,6 +1,7 @@ import numpy as np + +from pandas import DataFrame, MultiIndex, Series, Timestamp, date_range import pandas.util.testing as tm -from pandas import DataFrame, Series, MultiIndex, Timestamp, date_range try: from pandas.tseries.offsets import Nano, Hour @@ -104,4 +105,4 @@ def time_frame_from_lists(self): self.df = DataFrame(self.data) -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py index e2f6764c76eef..05f98c66faa2b 100644 --- a/asv_bench/benchmarks/frame_methods.py +++ b/asv_bench/benchmarks/frame_methods.py @@ -1,5 +1,5 @@ -import warnings import string +import warnings import numpy as np @@ -609,4 +609,4 @@ def time_dataframe_describe(self): self.df.describe() -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/gil.py b/asv_bench/benchmarks/gil.py index 0d0b75561d057..d57492dd37268 100644 --- a/asv_bench/benchmarks/gil.py +++ b/asv_bench/benchmarks/gil.py @@ -1,7 +1,8 @@ import numpy as np -import pandas.util.testing as tm -from pandas import DataFrame, Series, read_csv, factorize, date_range + +from pandas import DataFrame, Series, date_range, factorize, read_csv from pandas.core.algorithms import take_1d +import pandas.util.testing as tm try: from pandas import ( @@ -36,7 +37,7 @@ def wrapper(fname): return wrapper -from .pandas_vb_common import BaseIO +from .pandas_vb_common import BaseIO # noqa: E402 isort:skip class ParallelGroupbyMethods: @@ -301,4 +302,4 @@ def time_loop(self, threads): self.loop() -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index 39b07d4734399..d51c53e2264f1 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -15,7 +15,6 @@ ) import pandas.util.testing as tm - method_blacklist = { "object": { "median", @@ -626,4 +625,4 @@ def time_first(self): self.df_nans.groupby("key").transform("first") -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/index_object.py b/asv_bench/benchmarks/index_object.py index 49834ae94cc38..a94960d494707 100644 --- a/asv_bench/benchmarks/index_object.py +++ b/asv_bench/benchmarks/index_object.py @@ -1,15 +1,17 @@ import gc + import numpy as np -import pandas.util.testing as tm + from pandas import ( - Series, - date_range, DatetimeIndex, - Index, - RangeIndex, Float64Index, + Index, IntervalIndex, + RangeIndex, + Series, + date_range, ) +import pandas.util.testing as tm class SetOperations: @@ -243,4 +245,4 @@ def peakmem_gc_instances(self, N): gc.enable() -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/indexing.py b/asv_bench/benchmarks/indexing.py index 84604b8196536..ac35139c1954a 100644 --- a/asv_bench/benchmarks/indexing.py +++ b/asv_bench/benchmarks/indexing.py @@ -1,22 +1,23 @@ import warnings import numpy as np -import pandas.util.testing as tm + from pandas import ( - Series, + CategoricalIndex, DataFrame, - MultiIndex, - Int64Index, - UInt64Index, Float64Index, - IntervalIndex, - CategoricalIndex, IndexSlice, + Int64Index, + IntervalIndex, + MultiIndex, + Series, + UInt64Index, concat, date_range, option_context, period_range, ) +import pandas.util.testing as tm class NumericSeriesIndexing: @@ -371,4 +372,4 @@ def time_chained_indexing(self, mode): df2["C"] = 1.0 -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/inference.py b/asv_bench/benchmarks/inference.py index 66ef4f2aec380..e85b3bd2c7687 100644 --- a/asv_bench/benchmarks/inference.py +++ b/asv_bench/benchmarks/inference.py @@ -1,8 +1,9 @@ import numpy as np -import pandas.util.testing as tm + from pandas import DataFrame, Series, to_numeric +import pandas.util.testing as tm -from .pandas_vb_common import numeric_dtypes, lib +from .pandas_vb_common import lib, numeric_dtypes class NumericInferOps: @@ -120,4 +121,4 @@ def time_convert(self, data): lib.maybe_convert_numeric(data, set(), coerce_numeric=False) -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/io/csv.py b/asv_bench/benchmarks/io/csv.py index 4525e504fc4dd..9b8599b0a1b64 100644 --- a/asv_bench/benchmarks/io/csv.py +++ b/asv_bench/benchmarks/io/csv.py @@ -1,10 +1,11 @@ +from io import StringIO import random import string import numpy as np + +from pandas import Categorical, DataFrame, date_range, read_csv, to_datetime import pandas.util.testing as tm -from pandas import DataFrame, Categorical, date_range, read_csv, to_datetime -from io import StringIO from ..pandas_vb_common import BaseIO @@ -406,4 +407,4 @@ def time_to_datetime_format_DD_MM_YYYY(self, cache_dates): to_datetime(df["date"], cache=cache_dates, format="%d-%m-%Y") -from ..pandas_vb_common import setup # noqa: F401 +from ..pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/io/excel.py b/asv_bench/benchmarks/io/excel.py index 12e70f84e5203..9aa5cbd5b6f7c 100644 --- a/asv_bench/benchmarks/io/excel.py +++ b/asv_bench/benchmarks/io/excel.py @@ -1,6 +1,8 @@ from io import BytesIO + import numpy as np -from pandas import DataFrame, date_range, ExcelWriter, read_excel + +from pandas import DataFrame, ExcelWriter, date_range, read_excel import pandas.util.testing as tm @@ -35,4 +37,4 @@ def time_write_excel(self, engine): writer_write.save() -from ..pandas_vb_common import setup # noqa: F401 +from ..pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/io/hdf.py b/asv_bench/benchmarks/io/hdf.py index 2874a7889156b..8ec04a2087f1b 100644 --- a/asv_bench/benchmarks/io/hdf.py +++ b/asv_bench/benchmarks/io/hdf.py @@ -1,5 +1,6 @@ import numpy as np -from pandas import DataFrame, date_range, HDFStore, read_hdf + +from pandas import DataFrame, HDFStore, date_range, read_hdf import pandas.util.testing as tm from ..pandas_vb_common import BaseIO @@ -127,4 +128,4 @@ def time_write_hdf(self, format): self.df.to_hdf(self.fname, "df", format=format) -from ..pandas_vb_common import setup # noqa: F401 +from ..pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/io/json.py b/asv_bench/benchmarks/io/json.py index fc07f2a484102..b249c92b53e93 100644 --- a/asv_bench/benchmarks/io/json.py +++ b/asv_bench/benchmarks/io/json.py @@ -1,6 +1,7 @@ import numpy as np + +from pandas import DataFrame, concat, date_range, read_json, timedelta_range import pandas.util.testing as tm -from pandas import DataFrame, date_range, timedelta_range, concat, read_json from ..pandas_vb_common import BaseIO @@ -214,4 +215,4 @@ def peakmem_float(self, frames): df.to_json() -from ..pandas_vb_common import setup # noqa: F401 +from ..pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/io/msgpack.py b/asv_bench/benchmarks/io/msgpack.py index d97b4ae13f0bd..f5038602539ab 100644 --- a/asv_bench/benchmarks/io/msgpack.py +++ b/asv_bench/benchmarks/io/msgpack.py @@ -1,5 +1,7 @@ import warnings + import numpy as np + from pandas import DataFrame, date_range, read_msgpack import pandas.util.testing as tm @@ -27,4 +29,4 @@ def time_write_msgpack(self): self.df.to_msgpack(self.fname) -from ..pandas_vb_common import setup # noqa: F401 +from ..pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/io/pickle.py b/asv_bench/benchmarks/io/pickle.py index 286ac767c02e7..647e9d27dec9d 100644 --- a/asv_bench/benchmarks/io/pickle.py +++ b/asv_bench/benchmarks/io/pickle.py @@ -1,4 +1,5 @@ import numpy as np + from pandas import DataFrame, date_range, read_pickle import pandas.util.testing as tm @@ -25,4 +26,4 @@ def time_write_pickle(self): self.df.to_pickle(self.fname) -from ..pandas_vb_common import setup # noqa: F401 +from ..pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/io/sql.py b/asv_bench/benchmarks/io/sql.py index b80872b17a9e4..fe84c869717e3 100644 --- a/asv_bench/benchmarks/io/sql.py +++ b/asv_bench/benchmarks/io/sql.py @@ -1,10 +1,11 @@ import sqlite3 import numpy as np -import pandas.util.testing as tm -from pandas import DataFrame, date_range, read_sql_query, read_sql_table from sqlalchemy import create_engine +from pandas import DataFrame, date_range, read_sql_query, read_sql_table +import pandas.util.testing as tm + class SQL: @@ -141,4 +142,4 @@ def time_read_sql_table_column(self, dtype): read_sql_table(self.table_name, self.con, columns=[dtype]) -from ..pandas_vb_common import setup # noqa: F401 +from ..pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/io/stata.py b/asv_bench/benchmarks/io/stata.py index b3ed71af47dc8..28829785d72e9 100644 --- a/asv_bench/benchmarks/io/stata.py +++ b/asv_bench/benchmarks/io/stata.py @@ -1,4 +1,5 @@ import numpy as np + from pandas import DataFrame, date_range, read_stata import pandas.util.testing as tm @@ -50,4 +51,4 @@ def setup(self, convert_dates): self.df.to_stata(self.fname, self.convert_dates) -from ..pandas_vb_common import setup # noqa: F401 +from ..pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/join_merge.py b/asv_bench/benchmarks/join_merge.py index 7c899e3dc6ac8..6aa82a43a4d6a 100644 --- a/asv_bench/benchmarks/join_merge.py +++ b/asv_bench/benchmarks/join_merge.py @@ -1,8 +1,9 @@ import string import numpy as np + +from pandas import DataFrame, MultiIndex, Series, concat, date_range, merge, merge_asof import pandas.util.testing as tm -from pandas import DataFrame, Series, MultiIndex, date_range, concat, merge, merge_asof try: from pandas import merge_ordered @@ -348,4 +349,4 @@ def time_series_align_left_monotonic(self): self.ts1.align(self.ts2, join="left") -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/multiindex_object.py b/asv_bench/benchmarks/multiindex_object.py index eda059a68e8a5..3f4fd7ad911c1 100644 --- a/asv_bench/benchmarks/multiindex_object.py +++ b/asv_bench/benchmarks/multiindex_object.py @@ -1,8 +1,9 @@ import string import numpy as np + +from pandas import DataFrame, MultiIndex, date_range import pandas.util.testing as tm -from pandas import date_range, MultiIndex, DataFrame class GetLoc: @@ -146,4 +147,4 @@ def time_categorical_level(self): self.df.set_index(["a", "b"]) -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/offset.py b/asv_bench/benchmarks/offset.py index 31c3b6fb6cb60..d822646e712ae 100644 --- a/asv_bench/benchmarks/offset.py +++ b/asv_bench/benchmarks/offset.py @@ -1,7 +1,8 @@ -import warnings from datetime import datetime +import warnings import numpy as np + import pandas as pd try: diff --git a/asv_bench/benchmarks/pandas_vb_common.py b/asv_bench/benchmarks/pandas_vb_common.py index fdc8207021c0f..1faf13329110d 100644 --- a/asv_bench/benchmarks/pandas_vb_common.py +++ b/asv_bench/benchmarks/pandas_vb_common.py @@ -1,7 +1,8 @@ -import os from importlib import import_module +import os import numpy as np + import pandas as pd # Compatibility import for lib diff --git a/asv_bench/benchmarks/period.py b/asv_bench/benchmarks/period.py index 2f8ae0650ab75..7303240a25f29 100644 --- a/asv_bench/benchmarks/period.py +++ b/asv_bench/benchmarks/period.py @@ -1,4 +1,5 @@ from pandas import DataFrame, Period, PeriodIndex, Series, date_range, period_range + from pandas.tseries.frequencies import to_offset diff --git a/asv_bench/benchmarks/plotting.py b/asv_bench/benchmarks/plotting.py index 4fb0876f05a0a..5c718516360ed 100644 --- a/asv_bench/benchmarks/plotting.py +++ b/asv_bench/benchmarks/plotting.py @@ -1,11 +1,12 @@ +import matplotlib import numpy as np -from pandas import DataFrame, Series, DatetimeIndex, date_range + +from pandas import DataFrame, DatetimeIndex, Series, date_range try: from pandas.plotting import andrews_curves except ImportError: from pandas.tools.plotting import andrews_curves -import matplotlib matplotlib.use("Agg") @@ -93,4 +94,4 @@ def time_plot_andrews_curves(self): andrews_curves(self.df, "Name") -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/reindex.py b/asv_bench/benchmarks/reindex.py index 8d4c9ebaf3e89..cd450f801c805 100644 --- a/asv_bench/benchmarks/reindex.py +++ b/asv_bench/benchmarks/reindex.py @@ -1,6 +1,8 @@ import numpy as np + +from pandas import DataFrame, Index, MultiIndex, Series, date_range, period_range import pandas.util.testing as tm -from pandas import DataFrame, Series, MultiIndex, Index, date_range, period_range + from .pandas_vb_common import lib @@ -159,4 +161,4 @@ def time_lib_fast_zip(self): lib.fast_zip(self.col_array_list) -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/replace.py b/asv_bench/benchmarks/replace.py index 6137e944e6b9e..f13fd2460e0a8 100644 --- a/asv_bench/benchmarks/replace.py +++ b/asv_bench/benchmarks/replace.py @@ -1,4 +1,5 @@ import numpy as np + import pandas as pd @@ -56,4 +57,4 @@ def time_replace(self, constructor, replace_data): self.data.replace(self.to_replace) -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/reshape.py b/asv_bench/benchmarks/reshape.py index cc373f413fb88..441f4b380656e 100644 --- a/asv_bench/benchmarks/reshape.py +++ b/asv_bench/benchmarks/reshape.py @@ -1,9 +1,10 @@ -import string from itertools import product +import string import numpy as np -from pandas import DataFrame, MultiIndex, date_range, melt, wide_to_long + import pandas as pd +from pandas import DataFrame, MultiIndex, date_range, melt, wide_to_long class Melt: @@ -262,4 +263,4 @@ def time_explode(self, n_rows, max_list_length): self.series.explode() -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py index a70977fcf539f..3640513d31be2 100644 --- a/asv_bench/benchmarks/rolling.py +++ b/asv_bench/benchmarks/rolling.py @@ -1,6 +1,7 @@ -import pandas as pd import numpy as np +import pandas as pd + class Methods: @@ -121,4 +122,4 @@ def peakmem_fixed(self): self.roll.max() -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index 6038a2ab4bd9f..a3f1d92545c3f 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -1,8 +1,9 @@ from datetime import datetime import numpy as np + +from pandas import NaT, Series, date_range import pandas.util.testing as tm -from pandas import Series, date_range, NaT class SeriesConstructor: @@ -275,4 +276,4 @@ def time_func(self, func, N, dtype): self.func() -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/sparse.py b/asv_bench/benchmarks/sparse.py index 19d08c086a508..ac78ca53679fd 100644 --- a/asv_bench/benchmarks/sparse.py +++ b/asv_bench/benchmarks/sparse.py @@ -136,4 +136,4 @@ def time_division(self, fill_value): self.arr1 / self.arr2 -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/stat_ops.py b/asv_bench/benchmarks/stat_ops.py index 620a6de0f5f34..6032bee41958e 100644 --- a/asv_bench/benchmarks/stat_ops.py +++ b/asv_bench/benchmarks/stat_ops.py @@ -1,6 +1,6 @@ import numpy as np -import pandas as pd +import pandas as pd ops = ["mean", "sum", "median", "std", "skew", "kurt", "mad", "prod", "sem", "var"] @@ -148,4 +148,4 @@ def time_cov_series(self, use_bottleneck): self.s.cov(self.s2) -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/asv_bench/benchmarks/strings.py b/asv_bench/benchmarks/strings.py index 6be2fa92d9eac..f30b2482615bd 100644 --- a/asv_bench/benchmarks/strings.py +++ b/asv_bench/benchmarks/strings.py @@ -1,7 +1,8 @@ import warnings import numpy as np -from pandas import Series, DataFrame + +from pandas import DataFrame, Series import pandas.util.testing as tm diff --git a/asv_bench/benchmarks/timeseries.py b/asv_bench/benchmarks/timeseries.py index 1020b773f8acb..498774034d642 100644 --- a/asv_bench/benchmarks/timeseries.py +++ b/asv_bench/benchmarks/timeseries.py @@ -2,7 +2,9 @@ import dateutil import numpy as np -from pandas import to_datetime, date_range, Series, DataFrame, period_range + +from pandas import DataFrame, Series, date_range, period_range, to_datetime + from pandas.tseries.frequencies import infer_freq try: @@ -426,4 +428,4 @@ def time_dt_accessor_year(self, tz): self.series.dt.year -from .pandas_vb_common import setup # noqa: F401 +from .pandas_vb_common import setup # noqa: F401 isort:skip diff --git a/ci/print_skipped.py b/ci/print_skipped.py index a44281044e11d..6bc1dcfcd320d 100755 --- a/ci/print_skipped.py +++ b/ci/print_skipped.py @@ -1,8 +1,8 @@ #!/usr/bin/env python +import math import os import sys -import math import xml.etree.ElementTree as et diff --git a/doc/logo/pandas_logo.py b/doc/logo/pandas_logo.py index 5a07b094e6ad3..89410e3847bef 100644 --- a/doc/logo/pandas_logo.py +++ b/doc/logo/pandas_logo.py @@ -1,7 +1,6 @@ # script to generate the pandas logo -from matplotlib import pyplot as plt -from matplotlib import rcParams +from matplotlib import pyplot as plt, rcParams import numpy as np rcParams["mathtext.fontset"] = "cm" diff --git a/doc/make.py b/doc/make.py index 48febef20fbe6..cbb1fa6a5324a 100755 --- a/doc/make.py +++ b/doc/make.py @@ -11,18 +11,18 @@ $ python make.py html $ python make.py latex """ +import argparse +import csv import importlib -import sys import os import shutil -import csv import subprocess -import argparse +import sys import webbrowser + import docutils import docutils.parsers.rst - DOC_PATH = os.path.dirname(os.path.abspath(__file__)) SOURCE_PATH = os.path.join(DOC_PATH, "source") BUILD_PATH = os.path.join(DOC_PATH, "build") diff --git a/doc/source/conf.py b/doc/source/conf.py index 3ebc5d8b6333b..8a8cc4b61b7d8 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -10,15 +10,15 @@ # All configuration values have a default; values that are commented out # serve to show the default. -import sys -import os -import inspect import importlib +import inspect import logging +import os +import sys + import jinja2 -from sphinx.ext.autosummary import _import_by_name from numpydoc.docscrape import NumpyDocString - +from sphinx.ext.autosummary import _import_by_name logger = logging.getLogger(__name__) @@ -141,7 +141,7 @@ # built documents. # # The short X.Y version. -import pandas +import pandas # noqa: E402 isort:skip # version = '%s r%s' % (pandas.__version__, svn_version()) version = str(pandas.__version__) @@ -433,10 +433,14 @@ # Add custom Documenter to handle attributes/methods of an AccessorProperty # eg pandas.Series.str and pandas.Series.dt (see GH9322) -import sphinx -from sphinx.util import rpartition -from sphinx.ext.autodoc import Documenter, MethodDocumenter, AttributeDocumenter -from sphinx.ext.autosummary import Autosummary +import sphinx # noqa: E402 isort:skip +from sphinx.util import rpartition # noqa: E402 isort:skip +from sphinx.ext.autodoc import ( # noqa: E402 isort:skip + AttributeDocumenter, + Documenter, + MethodDocumenter, +) +from sphinx.ext.autosummary import Autosummary # noqa: E402 isort:skip class AccessorDocumenter(MethodDocumenter): diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index 7ba103c5ff996..3d7667c81c24a 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -3206,7 +3206,7 @@ argument to ``to_excel`` and to ``ExcelWriter``. The built-in engines are: writer = pd.ExcelWriter('path_to_file.xlsx', engine='xlsxwriter') # Or via pandas configuration. - from pandas import options # noqa: E402 + from pandas import options # noqa: E402 options.io.excel.xlsx.writer = 'xlsxwriter' df.to_excel('path_to_file.xlsx', sheet_name='Sheet1') diff --git a/doc/sphinxext/contributors.py b/doc/sphinxext/contributors.py index 4256e4659715d..1a064f71792e9 100644 --- a/doc/sphinxext/contributors.py +++ b/doc/sphinxext/contributors.py @@ -8,12 +8,11 @@ code contributors and commits, and then list each contributor individually. """ +from announce import build_components from docutils import nodes from docutils.parsers.rst import Directive import git -from announce import build_components - class ContributorsDirective(Directive): required_arguments = 1 diff --git a/pandas/core/api.py b/pandas/core/api.py index 73323d93b8215..bd2a57a15bdd2 100644 --- a/pandas/core/api.py +++ b/pandas/core/api.py @@ -2,6 +2,16 @@ import numpy as np +from pandas.core.dtypes.dtypes import ( + CategoricalDtype, + DatetimeTZDtype, + IntervalDtype, + PeriodDtype, +) +from pandas.core.dtypes.missing import isna, isnull, notna, notnull + +from pandas.core.algorithms import factorize, unique, value_counts +from pandas.core.arrays import Categorical from pandas.core.arrays.integer import ( Int8Dtype, Int16Dtype, @@ -12,45 +22,38 @@ UInt32Dtype, UInt64Dtype, ) -from pandas.core.algorithms import factorize, unique, value_counts -from pandas.core.dtypes.missing import isna, isnull, notna, notnull -from pandas.core.dtypes.dtypes import ( - CategoricalDtype, - PeriodDtype, - IntervalDtype, - DatetimeTZDtype, -) -from pandas.core.arrays import Categorical from pandas.core.construction import array + from pandas.core.groupby import Grouper, NamedAgg -from pandas.io.formats.format import set_eng_float_format + +# DataFrame needs to be imported after NamedAgg to avoid a circular import +from pandas.core.frame import DataFrame # isort:skip from pandas.core.index import ( - Index, CategoricalIndex, - Int64Index, - UInt64Index, - RangeIndex, + DatetimeIndex, Float64Index, - MultiIndex, + Index, + Int64Index, IntervalIndex, - TimedeltaIndex, - DatetimeIndex, - PeriodIndex, + MultiIndex, NaT, + PeriodIndex, + RangeIndex, + TimedeltaIndex, + UInt64Index, ) +from pandas.core.indexes.datetimes import Timestamp, bdate_range, date_range +from pandas.core.indexes.interval import Interval, interval_range from pandas.core.indexes.period import Period, period_range from pandas.core.indexes.timedeltas import Timedelta, timedelta_range -from pandas.core.indexes.datetimes import Timestamp, date_range, bdate_range -from pandas.core.indexes.interval import Interval, interval_range - -from pandas.core.series import Series -from pandas.core.frame import DataFrame - -# TODO: Remove import when statsmodels updates #18264 -from pandas.core.reshape.reshape import get_dummies - from pandas.core.indexing import IndexSlice -from pandas.core.tools.numeric import to_numeric -from pandas.tseries.offsets import DateOffset +from pandas.core.reshape.reshape import ( + get_dummies, +) # TODO: Remove get_dummies import when statsmodels updates #18264 +from pandas.core.series import Series from pandas.core.tools.datetimes import to_datetime +from pandas.core.tools.numeric import to_numeric from pandas.core.tools.timedeltas import to_timedelta + +from pandas.io.formats.format import set_eng_float_format +from pandas.tseries.offsets import DateOffset diff --git a/pandas/io/msgpack/__init__.py b/pandas/io/msgpack/__init__.py index 9b09cffd83f75..7107263c180cb 100644 --- a/pandas/io/msgpack/__init__.py +++ b/pandas/io/msgpack/__init__.py @@ -2,8 +2,8 @@ from collections import namedtuple -from pandas.io.msgpack.exceptions import * # noqa -from pandas.io.msgpack._version import version # noqa +from pandas.io.msgpack.exceptions import * # noqa: F401,F403 isort:skip +from pandas.io.msgpack._version import version # noqa: F401 isort:skip class ExtType(namedtuple("ExtType", "code data")): @@ -19,10 +19,14 @@ def __new__(cls, code, data): return super().__new__(cls, code, data) -import os # noqa +import os # noqa: F401,E402 isort:skip -from pandas.io.msgpack._packer import Packer # noqa -from pandas.io.msgpack._unpacker import unpack, unpackb, Unpacker # noqa +from pandas.io.msgpack._unpacker import ( # noqa: F401,E402 isort:skip + Unpacker, + unpack, + unpackb, +) +from pandas.io.msgpack._packer import Packer # noqa: E402 isort:skip def pack(o, stream, **kwargs): diff --git a/pandas/tests/io/pytables/test_pytables.py b/pandas/tests/io/pytables/test_pytables.py index d67f2c3b7bd66..7306393a1339e 100644 --- a/pandas/tests/io/pytables/test_pytables.py +++ b/pandas/tests/io/pytables/test_pytables.py @@ -37,7 +37,6 @@ import pandas.util.testing as tm from pandas.util.testing import assert_frame_equal, assert_series_equal, set_timezone -from pandas.io import pytables as pytables # noqa:E402 from pandas.io.formats.printing import pprint_thing from pandas.io.pytables import ( ClosedFileError, @@ -46,7 +45,9 @@ Term, read_hdf, ) -from pandas.io.pytables import TableIterator # noqa:E402 + +from pandas.io import pytables as pytables # noqa: E402 isort:skip +from pandas.io.pytables import TableIterator # noqa: E402 isort:skip tables = pytest.importorskip("tables") diff --git a/pandas/tests/io/test_feather.py b/pandas/tests/io/test_feather.py index 87a2405a10dd5..ee668d6890756 100644 --- a/pandas/tests/io/test_feather.py +++ b/pandas/tests/io/test_feather.py @@ -8,7 +8,7 @@ import pandas.util.testing as tm from pandas.util.testing import assert_frame_equal, ensure_clean -from pandas.io.feather_format import read_feather, to_feather # noqa:E402 +from pandas.io.feather_format import read_feather, to_feather # noqa: E402 isort:skip pyarrow = pytest.importorskip("pyarrow") diff --git a/scripts/find_commits_touching_func.py b/scripts/find_commits_touching_func.py index 1075a257d4270..95a892b822cff 100755 --- a/scripts/find_commits_touching_func.py +++ b/scripts/find_commits_touching_func.py @@ -10,11 +10,11 @@ Usage:: $ ./find_commits_touching_func.py (see arguments below) """ -import logging -import re -import os import argparse from collections import namedtuple +import logging +import os +import re from dateutil.parser import parse diff --git a/scripts/generate_pip_deps_from_conda.py b/scripts/generate_pip_deps_from_conda.py index 6ae10c2cb07d2..29fe8bf84c12b 100755 --- a/scripts/generate_pip_deps_from_conda.py +++ b/scripts/generate_pip_deps_from_conda.py @@ -16,8 +16,8 @@ import os import re import sys -import yaml +import yaml EXCLUDE = {"python=3"} RENAME = {"pytables": "tables", "pyqt": "pyqt5"} diff --git a/scripts/merge-pr.py b/scripts/merge-pr.py index 95352751a23c6..300cb149f387f 100755 --- a/scripts/merge-pr.py +++ b/scripts/merge-pr.py @@ -22,14 +22,15 @@ # usage: ./apache-pr-merge.py (see config env vars below) # # Lightly modified from version of this script in incubator-parquet-format -from subprocess import check_output -from requests.auth import HTTPBasicAuth -import requests import os +from subprocess import check_output import sys import textwrap +import requests +from requests.auth import HTTPBasicAuth + PANDAS_HOME = "." PROJECT_NAME = "pandas" print("PANDAS_HOME = " + PANDAS_HOME) diff --git a/scripts/tests/test_validate_docstrings.py b/scripts/tests/test_validate_docstrings.py index 35aaf10458f44..85e5bf239cbfa 100644 --- a/scripts/tests/test_validate_docstrings.py +++ b/scripts/tests/test_validate_docstrings.py @@ -2,12 +2,13 @@ import random import string import textwrap -import pytest -import numpy as np -import pandas as pd +import numpy as np +import pytest import validate_docstrings +import pandas as pd + validate_one = validate_docstrings.validate_one diff --git a/scripts/validate_docstrings.py b/scripts/validate_docstrings.py index bf5d861281a36..401eaf8ff5ed5 100755 --- a/scripts/validate_docstrings.py +++ b/scripts/validate_docstrings.py @@ -13,20 +13,20 @@ $ ./validate_docstrings.py $ ./validate_docstrings.py pandas.DataFrame.head """ -import os -import sys -import json -import re -import glob -import functools -import collections import argparse -import pydoc -import inspect -import importlib +import ast +import collections import doctest +import functools +import glob +import importlib +import inspect +import json +import os +import pydoc +import re +import sys import tempfile -import ast import textwrap import flake8.main.application @@ -41,20 +41,20 @@ # script. Setting here before matplotlib is loaded. # We don't warn for the number of open plots, as none is actually being opened os.environ["MPLBACKEND"] = "Template" -import matplotlib +import matplotlib # noqa: E402 isort:skip matplotlib.rc("figure", max_open_warning=10000) -import numpy +import numpy # noqa: E402 isort:skip BASE_PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, os.path.join(BASE_PATH)) -import pandas +import pandas # noqa: E402 isort:skip sys.path.insert(1, os.path.join(BASE_PATH, "doc", "sphinxext")) -from numpydoc.docscrape import NumpyDocString -from pandas.io.formats.printing import pprint_thing +from numpydoc.docscrape import NumpyDocString # noqa: E402 isort:skip +from pandas.io.formats.printing import pprint_thing # noqa: E402 isort:skip PRIVATE_CLASSES = ["NDFrame", "IndexOpsMixin"] diff --git a/setup.cfg b/setup.cfg index 716ff5d9d8853..43dbac15f5cfe 100644 --- a/setup.cfg +++ b/setup.cfg @@ -110,68 +110,25 @@ directory = coverage_html_report # To be kept consistent with "Import Formatting" section in contributing.rst [isort] -known_pre_libs=pandas._config -known_pre_core=pandas._libs,pandas.util._*,pandas.compat,pandas.errors -known_dtypes=pandas.core.dtypes -known_post_core=pandas.tseries,pandas.io,pandas.plotting -sections=FUTURE,STDLIB,THIRDPARTY,PRE_LIBS,PRE_CORE,DTYPES,FIRSTPARTY,POST_CORE,LOCALFOLDER - -known_first_party=pandas -known_third_party=Cython,numpy,dateutil,matplotlib,python-dateutil,pytz,pyarrow,pytest - -multi_line_output=3 -include_trailing_comma=True -force_grid_wrap=0 -combine_as_imports=True -line_length=88 -force_sort_within_sections=True -skip_glob=env, -skip= - pandas/__init__.py - pandas/core/api.py, - pandas/io/msgpack/__init__.py - asv_bench/benchmarks/attrs_caching.py, - asv_bench/benchmarks/binary_ops.py, - asv_bench/benchmarks/categoricals.py, - asv_bench/benchmarks/ctors.py, - asv_bench/benchmarks/eval.py, - asv_bench/benchmarks/frame_ctor.py, - asv_bench/benchmarks/frame_methods.py, - asv_bench/benchmarks/gil.py, - asv_bench/benchmarks/groupby.py, - asv_bench/benchmarks/index_object.py, - asv_bench/benchmarks/indexing.py, - asv_bench/benchmarks/inference.py, - asv_bench/benchmarks/io/csv.py, - asv_bench/benchmarks/io/excel.py, - asv_bench/benchmarks/io/hdf.py, - asv_bench/benchmarks/io/json.py, - asv_bench/benchmarks/io/msgpack.py, - asv_bench/benchmarks/io/pickle.py, - asv_bench/benchmarks/io/sql.py, - asv_bench/benchmarks/io/stata.py, - asv_bench/benchmarks/join_merge.py, - asv_bench/benchmarks/multiindex_object.py, - asv_bench/benchmarks/panel_ctor.py, - asv_bench/benchmarks/panel_methods.py, - asv_bench/benchmarks/plotting.py, - asv_bench/benchmarks/reindex.py, - asv_bench/benchmarks/replace.py, - asv_bench/benchmarks/reshape.py, - asv_bench/benchmarks/rolling.py, - asv_bench/benchmarks/series_methods.py, - asv_bench/benchmarks/sparse.py, - asv_bench/benchmarks/stat_ops.py, - asv_bench/benchmarks/timeseries.py - asv_bench/benchmarks/pandas_vb_common.py - asv_bench/benchmarks/offset.py - asv_bench/benchmarks/dtypes.py - asv_bench/benchmarks/strings.py - asv_bench/benchmarks/period.py +known_pre_libs = pandas._config +known_pre_core = pandas._libs,pandas.util._*,pandas.compat,pandas.errors +known_dtypes = pandas.core.dtypes +known_post_core = pandas.tseries,pandas.io,pandas.plotting +sections = FUTURE,STDLIB,THIRDPARTY,PRE_LIBS,PRE_CORE,DTYPES,FIRSTPARTY,POST_CORE,LOCALFOLDER +known_first_party = pandas +known_third_party = _pytest,announce,dateutil,docutils,flake8,git,hypothesis,jinja2,lxml,matplotlib,numpy,numpydoc,pkg_resources,pyarrow,pytest,pytz,requests,scipy,setuptools,sphinx,sqlalchemy,validate_docstrings,yaml +multi_line_output = 3 +include_trailing_comma = True +force_grid_wrap = 0 +combine_as_imports = True +line_length = 88 +force_sort_within_sections = True +skip_glob = env, +skip = pandas/__init__.py,pandas/core/api.py [mypy] ignore_missing_imports=True no_implicit_optional=True [mypy-pandas.conftest,pandas.tests.*] -ignore_errors=True \ No newline at end of file +ignore_errors=True diff --git a/setup.py b/setup.py index d2c6b18b892cd..a86527ace092b 100755 --- a/setup.py +++ b/setup.py @@ -6,16 +6,16 @@ BSD license. Parts are from lxml (https://github.com/lxml/lxml) """ +from distutils.sysconfig import get_config_vars +from distutils.version import LooseVersion import os from os.path import join as pjoin - -import pkg_resources import platform -from distutils.sysconfig import get_config_vars -import sys import shutil -from distutils.version import LooseVersion -from setuptools import setup, Command, find_packages +import sys + +import pkg_resources +from setuptools import Command, find_packages, setup # versioning import versioneer @@ -58,8 +58,8 @@ def is_platform_mac(): # The import of Extension must be after the import of Cython, otherwise # we do not get the appropriately patched class. # See https://cython.readthedocs.io/en/latest/src/reference/compilation.html -from distutils.extension import Extension # noqa:E402 -from distutils.command.build import build # noqa:E402 +from distutils.extension import Extension # noqa: E402 isort:skip +from distutils.command.build import build # noqa: E402 isort:skip try: if not _CYTHON_INSTALLED: @@ -831,9 +831,7 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): ] }, entry_points={ - "pandas_plotting_backends": [ - "matplotlib = pandas:plotting._matplotlib", - ], + "pandas_plotting_backends": ["matplotlib = pandas:plotting._matplotlib"] }, **setuptools_kwargs )
I noticed that `pre-commit` is used and ran `pre-commit run --all-files` which results in massive diffs, mostly because of `isort`. I have added the correct `noqa` and `isort:skip` flags to the lines which needed it to function correctly with the current `.pre-commit-config.yaml`, such that the imports are correctly sorted now. I also added `seed-isort-config` such that `setup.cfg` is parsed for `pre-commit` and fixed the formatting of `.pre-commit-config.yaml`. ~~Finally, there is `pandas/__init__.py` that is touched by `pre-commit run --all-files`, however, this has less trivial changes and might result in something breaking, so I don't dare to touch it.~~ It was because the `skip` entry in `[isort]` in `setup.cfg` is somehow ignored when running pre-commit and I can't figure out why (I will open an issue in the `isort` repo when it's clear that this will be merged). I have also deleted the other ignored files because I fixed the problems there. `pandas/core/api.py` needs to stay in `skip` because `isort` and `black` make conflicting edits.
https://api.github.com/repos/pandas-dev/pandas/pulls/27915
2019-08-14T09:40:45Z
2019-08-30T17:05:32Z
2019-08-30T17:05:32Z
2019-08-30T17:05:45Z
REF: use should_extension_dispatch for comparison method
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index dbcf09a401f27..0de28f0a4a8b3 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -17,9 +17,7 @@ from pandas.core.dtypes.common import ( ensure_object, is_bool_dtype, - is_categorical_dtype, is_datetime64_dtype, - is_datetime64tz_dtype, is_datetimelike_v_numeric, is_extension_array_dtype, is_integer_dtype, @@ -32,6 +30,7 @@ ABCDataFrame, ABCDatetimeArray, ABCDatetimeIndex, + ABCExtensionArray, ABCIndexClass, ABCSeries, ABCSparseSeries, @@ -699,42 +698,17 @@ def wrapper(self, other, axis=None): if isinstance(other, ABCSeries) and not self._indexed_same(other): raise ValueError("Can only compare identically-labeled Series objects") - elif ( - is_list_like(other) - and len(other) != len(self) - and not isinstance(other, (set, frozenset)) - ): - raise ValueError("Lengths must match") - elif isinstance(other, (np.ndarray, ABCIndexClass, ABCSeries)): + elif isinstance( + other, (np.ndarray, ABCExtensionArray, ABCIndexClass, ABCSeries) + ): # TODO: make this treatment consistent across ops and classes. # We are not catching all listlikes here (e.g. frozenset, tuple) # The ambiguous case is object-dtype. See GH#27803 if len(self) != len(other): raise ValueError("Lengths must match to compare") - if is_categorical_dtype(self): - # Dispatch to Categorical implementation; CategoricalIndex - # behavior is non-canonical GH#19513 - res_values = dispatch_to_extension_op(op, self, other) - - elif is_datetime64_dtype(self) or is_datetime64tz_dtype(self): - # Dispatch to DatetimeIndex to ensure identical - # Series/Index behavior - from pandas.core.arrays import DatetimeArray - - res_values = dispatch_to_extension_op(op, DatetimeArray(self), other) - - elif is_timedelta64_dtype(self): - from pandas.core.arrays import TimedeltaArray - - res_values = dispatch_to_extension_op(op, TimedeltaArray(self), other) - - elif is_extension_array_dtype(self) or ( - is_extension_array_dtype(other) and not is_scalar(other) - ): - # Note: the `not is_scalar(other)` condition rules out - # e.g. other == "category" + if should_extension_dispatch(self, other): res_values = dispatch_to_extension_op(op, self, other) elif is_scalar(other) and isna(other):
This sits on top of #27815
https://api.github.com/repos/pandas-dev/pandas/pulls/27912
2019-08-14T00:50:52Z
2019-08-19T21:48:39Z
2019-08-19T21:48:38Z
2019-08-19T21:57:36Z
CLN: missing boilerplate in Sparse op
diff --git a/pandas/core/arrays/sparse.py b/pandas/core/arrays/sparse.py index 2234167fe0193..201174b6b1995 100644 --- a/pandas/core/arrays/sparse.py +++ b/pandas/core/arrays/sparse.py @@ -39,6 +39,7 @@ ) from pandas.core.dtypes.dtypes import register_extension_dtype from pandas.core.dtypes.generic import ( + ABCDataFrame, ABCIndexClass, ABCSeries, ABCSparseArray, @@ -1735,13 +1736,15 @@ def sparse_unary_method(self): @classmethod def _create_arithmetic_method(cls, op): - def sparse_arithmetic_method(self, other): - op_name = op.__name__ + op_name = op.__name__ - if isinstance(other, (ABCSeries, ABCIndexClass)): + def sparse_arithmetic_method(self, other): + if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)): # Rely on pandas to dispatch to us. return NotImplemented + other = lib.item_from_zerodim(other) + if isinstance(other, SparseArray): return _sparse_array_op(self, other, op, op_name) diff --git a/pandas/tests/arrays/sparse/test_arithmetics.py b/pandas/tests/arrays/sparse/test_arithmetics.py index 57e5a35d99e48..cb5b437c962f9 100644 --- a/pandas/tests/arrays/sparse/test_arithmetics.py +++ b/pandas/tests/arrays/sparse/test_arithmetics.py @@ -441,6 +441,23 @@ def test_with_list(op): tm.assert_sp_array_equal(result, expected) +def test_with_dataframe(): + # GH#27910 + arr = pd.SparseArray([0, 1], fill_value=0) + df = pd.DataFrame([[1, 2], [3, 4]]) + result = arr.__add__(df) + assert result is NotImplemented + + +def test_with_zerodim_ndarray(): + # GH#27910 + arr = pd.SparseArray([0, 1], fill_value=0) + + result = arr * np.array(2) + expected = arr * 2 + tm.assert_sp_array_equal(result, expected) + + @pytest.mark.parametrize("ufunc", [np.abs, np.exp]) @pytest.mark.parametrize( "arr", [pd.SparseArray([0, 0, -1, 1]), pd.SparseArray([None, None, -1, 1])]
After this I think we'll be ready for #23853
https://api.github.com/repos/pandas-dev/pandas/pulls/27910
2019-08-13T23:33:04Z
2019-08-19T16:45:42Z
2019-08-19T16:45:42Z
2019-08-19T18:07:22Z
CLN: Catch more specific exceptions in groupby
diff --git a/pandas/_libs/index.pyx b/pandas/_libs/index.pyx index 7424c4ddc3d92..979dad6db0838 100644 --- a/pandas/_libs/index.pyx +++ b/pandas/_libs/index.pyx @@ -1,4 +1,5 @@ from datetime import datetime, timedelta, date +import warnings import cython diff --git a/pandas/_libs/index_class_helper.pxi.in b/pandas/_libs/index_class_helper.pxi.in index 3c9a096e7ecc0..4db048eeb0383 100644 --- a/pandas/_libs/index_class_helper.pxi.in +++ b/pandas/_libs/index_class_helper.pxi.in @@ -60,7 +60,16 @@ cdef class {{name}}Engine(IndexEngine): # A view is needed for some subclasses, such as PeriodEngine: values = self._get_index_values().view('{{dtype}}') - indexer = values == val + try: + with warnings.catch_warnings(): + # e.g. if values is float64 and `val` is a str, suppress warning + warnings.filterwarnings("ignore", category=FutureWarning) + indexer = values == val + except TypeError: + # if the equality above returns a bool, cython will raise TypeError + # when trying to cast it to ndarray + raise KeyError(val) + found = np.where(indexer)[0] count = len(found) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 6c95b521110a9..c0436e9389078 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -349,7 +349,7 @@ def _decide_output_index(self, output, labels): output_keys = sorted(output) try: output_keys.sort() - except Exception: # pragma: no cover + except TypeError: pass if isinstance(labels, MultiIndex): diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 6deef16bdec13..55def024cb1d4 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -727,8 +727,7 @@ def f(g): with option_context("mode.chained_assignment", None): try: result = self._python_apply_general(f) - except Exception: - + except TypeError: # gh-20949 # try again, with .apply acting as a filtering # operation, by excluding the grouping column diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 31623171e9e63..d079a1c4ef4f7 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -592,9 +592,11 @@ def is_in_axis(key): # if the grouper is obj[name] def is_in_obj(gpr): + if not hasattr(gpr, "name"): + return False try: - return id(gpr) == id(obj[gpr.name]) - except Exception: + return gpr is obj[gpr.name] + except (KeyError, IndexError): return False for i, (gpr, level) in enumerate(zip(keys, levels)): diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 7afb0a28f943e..6263973fb0d2f 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -212,8 +212,8 @@ def apply(self, f, data, axis=0): # This Exception is also raised if `f` triggers an exception # but it is preferable to raise the exception in Python. pass - except Exception: - # raise this error to the caller + except TypeError: + # occurs if we have any EAs pass for key, (i, group) in zip(group_keys, splitter):
Working hypothesis is that this will help turn up the problem underlying #27902. Regardless catching more specific exceptions is worthwhile.
https://api.github.com/repos/pandas-dev/pandas/pulls/27909
2019-08-13T21:39:09Z
2019-09-03T11:39:20Z
2019-09-03T11:39:20Z
2019-09-03T14:20:56Z
CLN: remove never-True checks in algorithms.py
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 21d12d02c9008..c0ed198e200f1 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -28,13 +28,11 @@ is_complex_dtype, is_datetime64_any_dtype, is_datetime64_ns_dtype, - is_datetime64tz_dtype, is_datetimelike, is_extension_array_dtype, is_float_dtype, is_integer, is_integer_dtype, - is_interval_dtype, is_list_like, is_numeric_dtype, is_object_dtype, @@ -183,8 +181,6 @@ def _reconstruct_data(values, dtype, original): if is_extension_array_dtype(dtype): values = dtype.construct_array_type()._from_sequence(values) - elif is_datetime64tz_dtype(dtype) or is_period_dtype(dtype): - values = Index(original)._shallow_copy(values, name=None) elif is_bool_dtype(dtype): values = values.astype(dtype) @@ -1645,19 +1641,13 @@ def take_nd( May be the same type as the input, or cast to an ndarray. """ - # TODO(EA): Remove these if / elifs as datetimeTZ, interval, become EAs - # dispatch to internal type takes if is_extension_array_dtype(arr): return arr.take(indexer, fill_value=fill_value, allow_fill=allow_fill) - elif is_datetime64tz_dtype(arr): - return arr.take(indexer, fill_value=fill_value, allow_fill=allow_fill) - elif is_interval_dtype(arr): - return arr.take(indexer, fill_value=fill_value, allow_fill=allow_fill) if is_sparse(arr): arr = arr.to_dense() elif isinstance(arr, (ABCIndexClass, ABCSeries)): - arr = arr.values + arr = arr._values arr = np.asarray(arr)
https://api.github.com/repos/pandas-dev/pandas/pulls/27908
2019-08-13T21:30:25Z
2019-08-14T20:21:30Z
2019-08-14T20:21:30Z
2019-08-14T21:35:58Z
Revert 37 pins
diff --git a/ci/deps/azure-37-locale.yaml b/ci/deps/azure-37-locale.yaml index 437fbc24b9411..26dcd213bbfa0 100644 --- a/ci/deps/azure-37-locale.yaml +++ b/ci/deps/azure-37-locale.yaml @@ -17,7 +17,7 @@ dependencies: - openpyxl - pytables - python-dateutil - - python=3.7.3 + - python=3.7.* - pytz - s3fs - scipy diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml index e1acda7ecf3c7..65c92ec1dcf0d 100644 --- a/ci/deps/azure-37-numpydev.yaml +++ b/ci/deps/azure-37-numpydev.yaml @@ -2,7 +2,7 @@ name: pandas-dev channels: - defaults dependencies: - - python=3.7.3 + - python=3.7.* - pytz - Cython>=0.28.2 # universal diff --git a/ci/deps/travis-37.yaml b/ci/deps/travis-37.yaml index d7bed9e3f03f2..9e08c41a3d9c0 100644 --- a/ci/deps/travis-37.yaml +++ b/ci/deps/travis-37.yaml @@ -4,7 +4,7 @@ channels: - conda-forge - c3i_test dependencies: - - python=3.7.3 + - python=3.7.* - botocore>=1.11 - cython>=0.28.2 - numpy diff --git a/environment.yml b/environment.yml index 0cbd500209b6c..6d2cd701c3854 100644 --- a/environment.yml +++ b/environment.yml @@ -5,7 +5,7 @@ channels: dependencies: # required - numpy>=1.15 - - python=3.7.3 + - python=3 - python-dateutil>=2.6.1 - pytz diff --git a/requirements-dev.txt b/requirements-dev.txt index f866f1436edc6..cf11a3ee28258 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,5 +1,4 @@ numpy>=1.15 -python==3.7.3 python-dateutil>=2.6.1 pytz asv
~second commit is temporary.~ Closes #27907 cc @jjhelmus
https://api.github.com/repos/pandas-dev/pandas/pulls/27907
2019-08-13T21:23:55Z
2019-08-14T19:34:11Z
2019-08-14T19:34:10Z
2019-08-14T19:46:11Z
CI: Skip flaky test that fails Azure to make pipeline succeed
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 756de3edd33dd..37ace3faf0e30 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -4,6 +4,8 @@ import numpy as np import pytest +from pandas.compat import PY37 + import pandas as pd from pandas import ( Categorical, @@ -207,7 +209,8 @@ def test_level_get_group(observed): assert_frame_equal(result, expected) -# GH#21636 previously flaky on py37 +# GH#21636 flaky on py37 is not solved, remove xfail when it is solved +@pytest.mark.xfail(PY37, reason="flaky on 3.7, xref gh-21636", strict=False) @pytest.mark.parametrize("ordered", [True, False]) def test_apply(ordered): # GH 10138
- [ ] 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/27906
2019-08-13T21:04:05Z
2019-08-14T13:29:56Z
null
2019-08-14T13:29:56Z
EHN: Add encoding_errors option in pandas.DataFrame.to_csv (#27750)
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index 338c890ce317c..0e500db6fec63 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -1710,6 +1710,8 @@ function takes a number of arguments. Only the first is required. appropriate (default None) * ``chunksize``: Number of rows to write at a time * ``date_format``: Format string for datetime objects +* ``encoding_errors``: Behavior when the input string can’t be converted according to the encoding’s rules (strict, ignore, replace, etc.) + .. versionadded:: 1.0.0 Writing a formatted string ++++++++++++++++++++++++++ diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 3b6288146bdf2..afcb5b5f45bb3 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -21,7 +21,7 @@ including other versions of pandas. Enhancements ~~~~~~~~~~~~ -- +- :meth:`Dataframe.to_csv` Add `encoding_errors` option (:issue:`27750`). - .. _whatsnew_1000.enhancements.other: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 1a5b36b07e93c..7adb3b9675c6a 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3084,6 +3084,7 @@ def to_csv( doublequote: bool_t = True, escapechar: Optional[str] = None, decimal: Optional[str] = ".", + encoding_errors: Optional[str] = "strict", ) -> Optional[str]: r""" Write object to a comma-separated values (csv) file. @@ -3171,6 +3172,11 @@ def to_csv( decimal : str, default '.' Character recognized as decimal separator. E.g. use ',' for European data. + encoding_errors : str, default 'strict' + Behavior when the input string can’t be converted according to + the encoding’s rules (strict, ignore, replace, etc.) + See: https://docs.python.org/3/library/codecs.html#codec-base-classes + .. versionadded:: 1.0.0 Returns ------- @@ -3224,6 +3230,7 @@ def to_csv( doublequote=doublequote, escapechar=escapechar, decimal=decimal, + encoding_errors=encoding_errors, ) formatter.save() diff --git a/pandas/io/common.py b/pandas/io/common.py index 30228d660e816..fea57344718f6 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -363,6 +363,7 @@ def _get_handle( compression: Optional[Union[str, Dict[str, Any]]] = None, memory_map: bool = False, is_text: bool = True, + encoding_errors: Optional[str] = "strict", ): """ Get file handle for given path/buffer and mode. @@ -395,6 +396,11 @@ def _get_handle( is_text : boolean, default True whether file/buffer is in text format (csv, json, etc.), or in binary mode (pickle, etc.). + encoding_errors : str, default 'strict' + Behavior when the input string can’t be converted according to + the encoding’s rules (strict, ignore, replace, etc.) + See: https://docs.python.org/3/library/codecs.html#codec-base-classes + .. versionadded:: 1.0.0 Returns ------- @@ -472,10 +478,12 @@ def _get_handle( elif is_path: if encoding: # Encoding - f = open(path_or_buf, mode, encoding=encoding, newline="") + f = open( + path_or_buf, mode, errors=encoding_errors, encoding=encoding, newline="" + ) elif is_text: # No explicit encoding - f = open(path_or_buf, mode, errors="replace", newline="") + f = open(path_or_buf, mode, errors=encoding_errors, newline="") else: # Binary mode f = open(path_or_buf, mode) diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py index e25862537cbfc..814c2c12d9037 100644 --- a/pandas/io/formats/csvs.py +++ b/pandas/io/formats/csvs.py @@ -52,6 +52,7 @@ def __init__( doublequote=True, escapechar=None, decimal=".", + encoding_errors="strict", ): self.obj = obj @@ -97,6 +98,8 @@ def __init__( self.has_mi_columns = isinstance(obj.columns, ABCMultiIndex) + self.encoding_errors = encoding_errors + # validate mi options if self.has_mi_columns: if cols is not None: @@ -183,6 +186,7 @@ def save(self): self.mode, encoding=self.encoding, compression=dict(self.compression_args, method=self.compression), + encoding_errors=self.encoding_errors, ) close = True diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index ab44b8b8059eb..39c488b3afd7f 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -555,3 +555,467 @@ def test_to_csv_zip_arguments(self, compression, archive_name): assert len(zp.filelist) == 1 archived_file = os.path.basename(zp.filelist[0].filename) assert archived_file == expected_arcname + + def test_to_csv_path_with_sjis(self): + # https://github.com/pandas-dev/pandas/issues/27750 + data = {"int": [1, 2, 3], "str_sjis": ["abc", "\u070a", "def"]} + df = pd.DataFrame(data) + # case 1: encoding_errors=strict + with tm.ensure_clean("sjis_test.csv") as path: + with pytest.raises(UnicodeEncodeError): + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="strict", + index=False, + ) + + # case 2: encoding_errors=replace + with tm.ensure_clean("sjis_test.csv") as path: + expected_sjis = """\ +int,str_sjis +1,abc +2,? +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="replace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_sjis + + # case 3: encoding_errors=ignore + with tm.ensure_clean("sjis_test.csv") as path: + expected_sjis = """\ +int,str_sjis +1,abc +2, +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="ignore", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_sjis + + # case 4: encoding_errors=xmlcharrefreplace + with tm.ensure_clean("sjis_test.csv") as path: + expected_sjis = """\ +int,str_sjis +1,abc +2,&#1802; +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="xmlcharrefreplace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_sjis + + # case 5: encoding_errors=backslashreplace + with tm.ensure_clean("sjis_test.csv") as path: + expected_sjis = """\ +int,str_sjis +1,abc +2,\\u070a +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="backslashreplace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_sjis + + # case 6: encoding_errors=namereplace + with tm.ensure_clean("sjis_test.csv") as path: + expected_sjis = """\ +int,str_sjis +1,abc +2,\\N{SYRIAC CONTRACTION} +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="namereplace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_sjis + + # case 7: encoding_errors=surrogatepass + with tm.ensure_clean("sjis_test.csv") as path: + with pytest.raises(UnicodeEncodeError): + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="surrogatepass", + index=False, + ) + + def test_to_csv_path_with_cp932(self): + # https://github.com/pandas-dev/pandas/issues/27750 + data = {"int": [1, 2, 3], "str_cp932": ["abc", "\u070a", "def"]} + df = pd.DataFrame(data) + # case 1: encoding_errors=strict + with tm.ensure_clean("cp932_test.csv") as path: + with pytest.raises(UnicodeEncodeError): + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="strict", + index=False, + ) + + # case 2: encoding_errors=replace + with tm.ensure_clean("cp932_test.csv") as path: + expected_cp932 = """\ +int,str_cp932 +1,abc +2,? +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="replace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_cp932 + + # case 3: encoding_errors=ignore + with tm.ensure_clean("cp932_test.csv") as path: + expected_cp932 = """\ +int,str_cp932 +1,abc +2, +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="ignore", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_cp932 + + # case 4: encoding_errors=xmlcharrefreplace + with tm.ensure_clean("cp932_test.csv") as path: + expected_cp932 = """\ +int,str_cp932 +1,abc +2,&#1802; +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="xmlcharrefreplace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_cp932 + + # case 5: encoding_errors=backslashreplace + with tm.ensure_clean("cp932_test.csv") as path: + expected_cp932 = """\ +int,str_cp932 +1,abc +2,\\u070a +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="backslashreplace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_cp932 + + # case 6: encoding_errors=namereplace + with tm.ensure_clean("cp932_test.csv") as path: + expected_cp932 = """\ +int,str_cp932 +1,abc +2,\\N{SYRIAC CONTRACTION} +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="namereplace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_cp932 + + # case 7: encoding_errors=surrogatepass + with tm.ensure_clean("cp932_test.csv") as path: + with pytest.raises(UnicodeEncodeError): + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="surrogatepass", + index=False, + ) + + def test_to_csv_file_object_with_sjis(self): + # https://github.com/pandas-dev/pandas/issues/27750 + data = {"int": [1, 2, 3], "str_sjis": ["abc", "\u070a", "def"]} + df = pd.DataFrame(data) + # case 1: encoding_errors=strict + with tm.ensure_clean() as path: + with pytest.raises(UnicodeEncodeError): + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="strict", + index=False, + ) + + # case 2: encoding_errors=replace + with tm.ensure_clean() as path: + expected_sjis = """\ +int,str_sjis +1,abc +2,? +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="replace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_sjis + + # case 3: encoding_errors=ignore + with tm.ensure_clean() as path: + expected_sjis = """\ +int,str_sjis +1,abc +2, +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="ignore", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_sjis + + # case 4: encoding_errors=xmlcharrefreplace + with tm.ensure_clean() as path: + expected_sjis = """\ +int,str_sjis +1,abc +2,&#1802; +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="xmlcharrefreplace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_sjis + + # case 5: encoding_errors=backslashreplace + with tm.ensure_clean() as path: + expected_sjis = """\ +int,str_sjis +1,abc +2,\\u070a +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="backslashreplace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_sjis + + # case 6: encoding_errors=namereplace + with tm.ensure_clean() as path: + expected_sjis = """\ +int,str_sjis +1,abc +2,\\N{SYRIAC CONTRACTION} +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="namereplace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_sjis + + # case 7: encoding_errors=surrogatepass + with tm.ensure_clean() as path: + with pytest.raises(UnicodeEncodeError): + df.to_csv( + path, + line_terminator="\n", + encoding="sjis", + encoding_errors="surrogatepass", + index=False, + ) + + def test_to_csv_file_object_with_cp932(self): + # https://github.com/pandas-dev/pandas/issues/27750 + data = {"int": [1, 2, 3], "str_cp932": ["abc", "\u070a", "def"]} + df = pd.DataFrame(data) + # case 1: encoding_errors=strict + with tm.ensure_clean() as path: + with pytest.raises(UnicodeEncodeError): + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="strict", + index=False, + ) + + # case 2: encoding_errors=replace + with tm.ensure_clean() as path: + expected_cp932 = """\ +int,str_cp932 +1,abc +2,? +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="replace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_cp932 + + # case 3: encoding_errors=ignore + with tm.ensure_clean() as path: + expected_cp932 = """\ +int,str_cp932 +1,abc +2, +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="ignore", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_cp932 + + # case 4: encoding_errors=xmlcharrefreplace + with tm.ensure_clean() as path: + expected_cp932 = """\ +int,str_cp932 +1,abc +2,&#1802; +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="xmlcharrefreplace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_cp932 + + # case 5: encoding_errors=backslashreplace + with tm.ensure_clean() as path: + expected_cp932 = """\ +int,str_cp932 +1,abc +2,\\u070a +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="backslashreplace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_cp932 + + # case 6: encoding_errors=namereplace + with tm.ensure_clean() as path: + expected_cp932 = """\ +int,str_cp932 +1,abc +2,\\N{SYRIAC CONTRACTION} +3,def +""" + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="namereplace", + index=False, + ) + with open(path, "r") as f: + assert f.read() == expected_cp932 + + # case 7: encoding_errors=surrogatepass + with tm.ensure_clean() as path: + with pytest.raises(UnicodeEncodeError): + df.to_csv( + path, + line_terminator="\n", + encoding="cp932", + encoding_errors="surrogatepass", + index=False, + )
- [x] closes #27750 - [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/27899
2019-08-13T11:39:49Z
2019-09-10T21:05:20Z
null
2019-09-10T21:05:20Z
CLN: remove _maybe_update_attributes
diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 6899e47045c1c..3609c68a26c0f 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -776,12 +776,14 @@ def __rdivmod__(self, other): res2 = other - res1 * self return res1, res2 - # Note: TimedeltaIndex overrides this in call to cls._add_numeric_methods def __neg__(self): if self.freq is not None: return type(self)(-self._data, freq=-self.freq) return type(self)(-self._data) + def __pos__(self): + return type(self)(self._data, freq=self.freq) + def __abs__(self): # Note: freq is not preserved return type(self)(np.abs(self._data)) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 4e098b2f8be9b..5f17dde01d2c4 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -695,7 +695,6 @@ def __array_wrap__(self, result, context=None): return result attrs = self._get_attributes_dict() - attrs = self._maybe_update_attributes(attrs) return Index(result, **attrs) @cache_readonly @@ -5335,12 +5334,6 @@ def _add_numeric_methods_disabled(cls): cls.__abs__ = make_invalid_op("__abs__") cls.__inv__ = make_invalid_op("__inv__") - def _maybe_update_attributes(self, attrs): - """ - Update Index attributes (e.g. freq) depending on op. - """ - return attrs - @classmethod def _add_numeric_methods_binary(cls): """ @@ -5374,7 +5367,6 @@ def _make_evaluate_unary(op, opstr): def _evaluate_numeric_unary(self): attrs = self._get_attributes_dict() - attrs = self._maybe_update_attributes(attrs) return Index(op(self.values), **attrs) _evaluate_numeric_unary.__name__ = opstr diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index af99c7a2754e5..c7664d9777c71 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -15,6 +15,7 @@ from pandas.core.dtypes.common import ( ensure_int64, + is_bool_dtype, is_dtype_equal, is_float, is_integer, @@ -163,6 +164,20 @@ def values(self): def asi8(self): return self._data.asi8 + def __array_wrap__(self, result, context=None): + """ + Gets called after a ufunc. + """ + result = lib.item_from_zerodim(result) + if is_bool_dtype(result) or lib.is_scalar(result): + return result + + attrs = self._get_attributes_dict() + if not is_period_dtype(self) and attrs["freq"]: + # no need to infer if freq is None + attrs["freq"] = "infer" + return Index(result, **attrs) + # ------------------------------------------------------------------------ def equals(self, other): diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 9f2b31f23d2fa..caae9a0b5f751 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -465,14 +465,6 @@ def _convert_for_op(self, value): return _to_M8(value) raise ValueError("Passed item and index have different timezone") - def _maybe_update_attributes(self, attrs): - """ Update Index attributes (e.g. freq) depending on op """ - freq = attrs.get("freq", None) - if freq is not None: - # no need to infer if freq is None - attrs["freq"] = "infer" - return attrs - # -------------------------------------------------------------------- # Rendering Methods diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index cfdaf65955dab..43ed6e7b122ea 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -75,7 +75,7 @@ class RangeIndex(Int64Index): _engine_type = libindex.Int64Engine _range = None # type: range - # check whether self._data has benn called + # check whether self._data has been called _cached_data = None # type: np.ndarray # -------------------------------------------------------------------- # Constructors @@ -785,7 +785,6 @@ def _evaluate_numeric_binop(self, other): other = extract_array(other, extract_numpy=True) attrs = self._get_attributes_dict() - attrs = self._maybe_update_attributes(attrs) left, right = self, other diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index f2ce562536b95..d06afa3daa792 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -44,7 +44,12 @@ class TimedeltaDelegateMixin(DatetimelikeDelegateMixin): # which we we dont' want to expose in the .dt accessor. _delegate_class = TimedeltaArray _delegated_properties = TimedeltaArray._datetimelike_ops + ["components"] - _delegated_methods = TimedeltaArray._datetimelike_methods + ["_box_values"] + _delegated_methods = TimedeltaArray._datetimelike_methods + [ + "_box_values", + "__neg__", + "__pos__", + "__abs__", + ] _raw_properties = {"components"} _raw_methods = {"to_pytimedelta"} @@ -56,7 +61,7 @@ class TimedeltaDelegateMixin(DatetimelikeDelegateMixin): TimedeltaArray, TimedeltaDelegateMixin._delegated_methods, typ="method", - overwrite=False, + overwrite=True, ) class TimedeltaIndex( DatetimeIndexOpsMixin, dtl.TimelikeOps, Int64Index, TimedeltaDelegateMixin @@ -279,14 +284,6 @@ def __setstate__(self, state): _unpickle_compat = __setstate__ - def _maybe_update_attributes(self, attrs): - """ Update Index attributes (e.g. freq) depending on op """ - freq = attrs.get("freq", None) - if freq is not None: - # no need to infer if freq is None - attrs["freq"] = "infer" - return attrs - # ------------------------------------------------------------------- # Rendering Methods @@ -689,7 +686,6 @@ def delete(self, loc): TimedeltaIndex._add_comparison_ops() -TimedeltaIndex._add_numeric_methods_unary() TimedeltaIndex._add_logical_methods_disabled() TimedeltaIndex._add_datetimelike_methods()
It is only non-trivial for DTI and TDI, and only actually needed in `__array_wrap__`. It is cleaner to implement the relevant patch in `DatetimeIndexOpsMixin.__array_wrap__` and avoid the need for maybe_update_attributes altogether.
https://api.github.com/repos/pandas-dev/pandas/pulls/27896
2019-08-13T03:37:31Z
2019-08-15T12:42:38Z
2019-08-15T12:42:38Z
2019-10-19T12:11:51Z
Infer names in MultiIndex.from_product
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 71374a3bff692..8efcde7954338 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -28,7 +28,7 @@ Enhancements Other enhancements ^^^^^^^^^^^^^^^^^^ -- +- :meth:`MultiIndex.from_product` infers level names from inputs when not explicitly provided (:issue:`27292`) - .. _whatsnew_1000.api_breaking: diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 761862b9f30e9..28603bc7705ca 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -508,7 +508,9 @@ def from_product(cls, iterables, sortorder=None, names=None): Level of sortedness (must be lexicographically sorted by that level). names : list / sequence of str, optional - Names for the levels in the index. + Names for the levels in the index. If not provided, names + will be inferred from iterables if the elements of iterables + have a name attribute. Returns ------- @@ -526,6 +528,18 @@ def from_product(cls, iterables, sortorder=None, names=None): >>> colors = ['green', 'purple'] >>> pd.MultiIndex.from_product([numbers, colors], ... names=['number', 'color']) + MultiIndex([(0, 'green'), + (0, 'purple'), + (1, 'green'), + (1, 'purple'), + (2, 'green'), + (2, 'purple')], + names=['number', 'color']) + + >>> numbers = pd.Series([0, 1, 2], name='number') + >>> colors = pd.Series(['green', 'purple'], name='color') + >>> pd.MultiIndex.from_product([numbers, colors]) + ... MultiIndex([(0, 'green'), (0, 'purple'), (1, 'green'), @@ -541,6 +555,13 @@ def from_product(cls, iterables, sortorder=None, names=None): elif is_iterator(iterables): iterables = list(iterables) + # Infer names from iterable if attribute is available + if names is None: + names = [getattr(idx, "name", None) for idx in iterables] + + if all(name is None for name in names): + names = None + codes, levels = _factorize_from_iterables(iterables) codes = cartesian_product(codes) return MultiIndex(levels, codes, sortorder=sortorder, names=names) diff --git a/pandas/tests/indexes/multi/test_constructor.py b/pandas/tests/indexes/multi/test_constructor.py index 86c9ee3455d0b..bff325b727344 100644 --- a/pandas/tests/indexes/multi/test_constructor.py +++ b/pandas/tests/indexes/multi/test_constructor.py @@ -473,6 +473,29 @@ def test_from_product_datetimeindex(): tm.assert_numpy_array_equal(mi.values, etalon) +@pytest.mark.parametrize( + "a, b, expected_names", + [ + ( + pd.Series([1, 2, 3], name="foo"), + pd.Series(["a", "b"], name="bar"), + ["foo", "bar"], + ), + (pd.Series([1, 2, 3]), pd.Series(["a", "b"]), None), + (pd.Series([1, 2, 3], name="foo"), ["a", "b"], ["foo", None]), + ([1, 2, 3], ["a", "b"], None), + ], +) +def test_from_product_infers_partial_names(a, b, expected_names): + result = MultiIndex.from_product([a, b]) + expected = MultiIndex( + levels=[[1, 2, 3], ["a", "b"]], + codes=[[0, 0, 1, 1, 2, 2], [0, 1, 0, 1, 0, 1]], + names=expected_names, + ) + tm.assert_index_equal(result, expected) + + @pytest.mark.parametrize("ordered", [False, True]) @pytest.mark.parametrize("f", [lambda x: x, lambda x: pd.Series(x), lambda x: x.values]) def test_from_product_index_series_categorical(ordered, f):
- [x] closes #27292 - [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/27895
2019-08-13T03:00:46Z
2019-09-12T16:00:06Z
null
2019-09-12T16:00:17Z
DOC: clarify see also for DataFrame.iterrows()
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 02241eeaae7b2..e3edab117668f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -845,8 +845,8 @@ def iterrows(self): See Also -------- - itertuples : Iterate over DataFrame rows as namedtuples of the values. - items : Iterate over (column name, Series) pairs. + DataFrame.itertuples : Iterate over DataFrame rows as namedtuples of the values. + DataFrame.items : Iterate over (column name, Series) pairs. Notes -----
- [x] closes #27862 - [ ] tests added / passed - [x] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/27893
2019-08-13T02:57:17Z
2019-08-13T07:57:20Z
2019-08-13T07:57:20Z
2019-08-13T07:57:21Z
CLN: remove unnecessary validate_for_numeric_unary
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 7272d4e2752be..a2e0582da6ee3 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -5341,16 +5341,6 @@ def _maybe_update_attributes(self, attrs): """ return attrs - def _validate_for_numeric_unaryop(self, op, opstr): - """ - Validate if we can perform a numeric unary operation. - """ - if not self._is_numeric_dtype: - raise TypeError( - "cannot evaluate a numeric op " - "{opstr} for type: {typ}".format(opstr=opstr, typ=type(self).__name__) - ) - @classmethod def _add_numeric_methods_binary(cls): """ @@ -5383,7 +5373,6 @@ def _add_numeric_methods_unary(cls): def _make_evaluate_unary(op, opstr): def _evaluate_numeric_unary(self): - self._validate_for_numeric_unaryop(op, opstr) attrs = self._get_attributes_dict() attrs = self._maybe_update_attributes(attrs) return Index(op(self.values), **attrs)
https://api.github.com/repos/pandas-dev/pandas/pulls/27891
2019-08-13T02:01:04Z
2019-08-14T20:39:53Z
2019-08-14T20:39:53Z
2019-08-14T21:33:55Z
BUG: fix Sparse reduction
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index b97f45efbeae9..dfa216b1db56e 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -133,7 +133,7 @@ Reshaping Sparse ^^^^^^ - +- Bug in reductions for :class:`Series` with Sparse dtypes (:issue:`27080`) - - - diff --git a/pandas/core/arrays/sparse.py b/pandas/core/arrays/sparse.py index 8aa83c3fbc37d..2234167fe0193 100644 --- a/pandas/core/arrays/sparse.py +++ b/pandas/core/arrays/sparse.py @@ -1693,6 +1693,9 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): for sp_value, fv in zip(sp_values, fill_value) ) return arrays + elif is_scalar(sp_values): + # e.g. reductions + return sp_values return self._simple_new( sp_values, self.sp_index, SparseDtype(sp_values.dtype, fill_value) diff --git a/pandas/tests/series/test_ufunc.py b/pandas/tests/series/test_ufunc.py index c024e9caba156..8144a3931b9b8 100644 --- a/pandas/tests/series/test_ufunc.py +++ b/pandas/tests/series/test_ufunc.py @@ -252,10 +252,7 @@ def __add__(self, other): "values", [ pd.array([1, 3, 2]), - pytest.param( - pd.array([1, 10, 0], dtype="Sparse[int]"), - marks=pytest.mark.xfail(resason="GH-27080. Bug in SparseArray"), - ), + pd.array([1, 10, 0], dtype="Sparse[int]"), pd.to_datetime(["2000", "2010", "2001"]), pd.to_datetime(["2000", "2010", "2001"]).tz_localize("CET"), pd.to_datetime(["2000", "2010", "2001"]).to_period(freq="D"),
- [x] closes #27080 - [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/27890
2019-08-13T01:52:58Z
2019-08-13T16:15:37Z
2019-08-13T16:15:36Z
2019-08-13T16:23:38Z
CLN: remove unnecessary dtype checks
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 13058882084ff..a0fa1b5ff6d92 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1,3 +1,4 @@ +import operator from shutil import get_terminal_size import textwrap from typing import Type, Union, cast @@ -77,7 +78,9 @@ ) -def _cat_compare_op(opname): +def _cat_compare_op(op): + opname = "__{op}__".format(op=op.__name__) + def f(self, other): # On python2, you can usually compare any type to any type, and # Categoricals can be seen as a custom type, but having different @@ -1240,12 +1243,12 @@ def map(self, mapper): new_categories = new_categories.insert(len(new_categories), np.nan) return np.take(new_categories, self._codes) - __eq__ = _cat_compare_op("__eq__") - __ne__ = _cat_compare_op("__ne__") - __lt__ = _cat_compare_op("__lt__") - __gt__ = _cat_compare_op("__gt__") - __le__ = _cat_compare_op("__le__") - __ge__ = _cat_compare_op("__ge__") + __eq__ = _cat_compare_op(operator.eq) + __ne__ = _cat_compare_op(operator.ne) + __lt__ = _cat_compare_op(operator.lt) + __gt__ = _cat_compare_op(operator.gt) + __le__ = _cat_compare_op(operator.le) + __ge__ = _cat_compare_op(operator.ge) # for Series/ndarray like compat @property diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 0372b8f0c080a..1988726edc79b 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -22,7 +22,6 @@ is_datetime64tz_dtype, is_datetime_or_timedelta_dtype, is_dtype_equal, - is_extension_array_dtype, is_float_dtype, is_integer_dtype, is_list_like, @@ -1230,29 +1229,17 @@ def __add__(self, other): if not is_period_dtype(self): maybe_integer_op_deprecated(self) result = self._addsub_int_array(other, operator.add) - elif is_float_dtype(other): - # Explicitly catch invalid dtypes - raise TypeError( - "cannot add {dtype}-dtype to {cls}".format( - dtype=other.dtype, cls=type(self).__name__ - ) - ) - elif is_period_dtype(other): - # if self is a TimedeltaArray and other is a PeriodArray with - # a timedelta-like (i.e. Tick) freq, this operation is valid. - # Defer to the PeriodArray implementation. - # In remaining cases, this will end up raising TypeError. - return NotImplemented - elif is_extension_array_dtype(other): - # Categorical op will raise; defer explicitly - return NotImplemented - else: # pragma: no cover + else: + # Includes Categorical, other ExtensionArrays + # For PeriodDtype, if self is a TimedeltaArray and other is a + # PeriodArray with a timedelta-like (i.e. Tick) freq, this + # operation is valid. Defer to the PeriodArray implementation. + # In remaining cases, this will end up raising TypeError. return NotImplemented if is_timedelta64_dtype(result) and isinstance(result, np.ndarray): from pandas.core.arrays import TimedeltaArray - # TODO: infer freq? return TimedeltaArray(result) return result @@ -1302,29 +1289,13 @@ def __sub__(self, other): if not is_period_dtype(self): maybe_integer_op_deprecated(self) result = self._addsub_int_array(other, operator.sub) - elif isinstance(other, ABCIndexClass): - raise TypeError( - "cannot subtract {cls} and {typ}".format( - cls=type(self).__name__, typ=type(other).__name__ - ) - ) - elif is_float_dtype(other): - # Explicitly catch invalid dtypes - raise TypeError( - "cannot subtract {dtype}-dtype from {cls}".format( - dtype=other.dtype, cls=type(self).__name__ - ) - ) - elif is_extension_array_dtype(other): - # Categorical op will raise; defer explicitly - return NotImplemented - else: # pragma: no cover + else: + # Includes ExtensionArrays, float_dtype return NotImplemented if is_timedelta64_dtype(result) and isinstance(result, np.ndarray): from pandas.core.arrays import TimedeltaArray - # TODO: infer freq? return TimedeltaArray(result) return result diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 28537124536e7..1aad130d9a3f5 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -223,8 +223,6 @@ def wrapper(self, other): result = op(self.view("i8"), other.view("i8")) o_mask = other._isnan - result = com.values_from_object(result) - if o_mask.any(): result[o_mask] = nat_result diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 3920cfcc002d7..1fb93a182ba0b 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -1097,7 +1097,13 @@ def test_dt64arr_add_timestamp_raises(self, box_with_array): def test_dt64arr_add_sub_float(self, other, box_with_array): dti = DatetimeIndex(["2011-01-01", "2011-01-02"], freq="D") dtarr = tm.box_expected(dti, box_with_array) - msg = "|".join(["unsupported operand type", "cannot (add|subtract)"]) + msg = "|".join( + [ + "unsupported operand type", + "cannot (add|subtract)", + "ufunc '?(add|subtract)'? cannot use operands with types", + ] + ) with pytest.raises(TypeError, match=msg): dtarr + other with pytest.raises(TypeError, match=msg):
these aren't accomplishing anything and are very non-performant. Also, remove an unnecessary values_from_object call and use operator.foo instead of `"__foo__"` in categorical ops.
https://api.github.com/repos/pandas-dev/pandas/pulls/27889
2019-08-13T01:20:48Z
2019-08-13T12:22:41Z
2019-08-13T12:22:41Z
2019-08-13T13:50:42Z
DOC: Updated Series.items 'See also' section for clarity
diff --git a/pandas/core/series.py b/pandas/core/series.py index 4e64a25e430eb..c891298d6e499 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1681,7 +1681,8 @@ def items(self): See Also -------- - DataFrame.items : Equivalent to Series.items for DataFrame. + DataFrame.items : Iterate over (column name, Series) pairs. + DataFrame.iterrows : Iterate over DataFrame rows as (index, Series) pairs. Examples --------
I changed the See also to: DataFrame.items : Iterate over (column name, Series) pairs. DataFrame.iterrows : Iterate over DataFrame rows as (index, Series) pairs. No assertions about the equivalence of DataFrame.items and Series.items closes #27859
https://api.github.com/repos/pandas-dev/pandas/pulls/27888
2019-08-13T01:14:57Z
2019-08-13T07:50:40Z
2019-08-13T07:50:40Z
2019-08-13T07:50:48Z
Backport PR #27855 on branch 0.25.x (BUG: add back check for MultiIndex case and take_split_path)
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 637ac5c9c8bd1..9a435e1d18640 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -84,7 +84,7 @@ Indexing - Bug in partial-string indexing returning a NumPy array rather than a ``Series`` when indexing with a scalar like ``.loc['2015']`` (:issue:`27516`) - Break reference cycle involving :class:`Index` to allow garbage collection of :class:`Index` objects without running the GC. (:issue:`27585`) -- +- Fix regression in assigning values to a single column of a DataFrame with a ``MultiIndex`` columns (:issue:`27841`). - Missing diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 8f242f0ae7d7c..71985c0707095 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -326,6 +326,17 @@ def _setitem_with_indexer(self, indexer, value): val = list(value.values()) if isinstance(value, dict) else value take_split_path = not blk._can_hold_element(val) + # if we have any multi-indexes that have non-trivial slices + # (not null slices) then we must take the split path, xref + # GH 10360, GH 27841 + if isinstance(indexer, tuple) and len(indexer) == len(self.obj.axes): + for i, ax in zip(indexer, self.obj.axes): + if isinstance(ax, MultiIndex) and not ( + is_integer(i) or com.is_null_slice(i) + ): + take_split_path = True + break + if isinstance(indexer, tuple): nindexer = [] for i, idx in enumerate(indexer): diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index a08b2b4c66af2..8b48c2bf7169f 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -390,3 +390,26 @@ def test_loc_getitem_lowerdim_corner(multiindex_dataframe_random_data): expected = 0 result = df.sort_index().loc[("bar", "three"), "B"] assert result == expected + + +def test_loc_setitem_single_column_slice(): + # case from https://github.com/pandas-dev/pandas/issues/27841 + df = DataFrame( + "string", + index=list("abcd"), + columns=MultiIndex.from_product([["Main"], ("another", "one")]), + ) + df["labels"] = "a" + df.loc[:, "labels"] = df.index + tm.assert_numpy_array_equal(np.asarray(df["labels"]), np.asarray(df.index)) + + # test with non-object block + df = DataFrame( + np.nan, + index=range(4), + columns=MultiIndex.from_tuples([("A", "1"), ("A", "2"), ("B", "1")]), + ) + expected = df.copy() + df.loc[:, "B"] = np.arange(4) + expected.iloc[:, 2] = np.arange(4) + tm.assert_frame_equal(df, expected)
Backport PR #27855: BUG: add back check for MultiIndex case and take_split_path
https://api.github.com/repos/pandas-dev/pandas/pulls/27887
2019-08-13T01:04:32Z
2019-08-13T08:40:19Z
2019-08-13T08:40:19Z
2019-08-13T08:40:19Z
CLN: remove unnecessary validate_for_numeric_binop
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 598c4dca9ce88..164cc6cda00a9 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1,4 +1,4 @@ -from datetime import datetime, timedelta +from datetime import datetime import operator from textwrap import dedent from typing import Union @@ -49,7 +49,6 @@ from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes.generic import ( ABCDataFrame, - ABCDateOffset, ABCDatetimeArray, ABCDatetimeIndex, ABCIndexClass, @@ -5384,51 +5383,6 @@ def _validate_for_numeric_unaryop(self, op, opstr): "{opstr} for type: {typ}".format(opstr=opstr, typ=type(self).__name__) ) - def _validate_for_numeric_binop(self, other, op): - """ - Return valid other; evaluate or raise TypeError if we are not of - the appropriate type. - - Notes - ----- - This is an internal method called by ops. - """ - opstr = "__{opname}__".format(opname=op.__name__) - # if we are an inheritor of numeric, - # but not actually numeric (e.g. DatetimeIndex/PeriodIndex) - if not self._is_numeric_dtype: - raise TypeError( - "cannot evaluate a numeric op {opstr} " - "for type: {typ}".format(opstr=opstr, typ=type(self).__name__) - ) - - if isinstance(other, Index): - if not other._is_numeric_dtype: - raise TypeError( - "cannot evaluate a numeric op " - "{opstr} with type: {typ}".format(opstr=opstr, typ=type(other)) - ) - elif isinstance(other, np.ndarray) and not other.ndim: - other = other.item() - - if isinstance(other, (Index, ABCSeries, np.ndarray)): - if len(self) != len(other): - 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") - elif isinstance(other, (ABCDateOffset, np.timedelta64, timedelta)): - # higher up to handle - pass - elif isinstance(other, (datetime, np.datetime64)): - # higher up to handle - pass - else: - if not (is_float(other) or is_integer(other)): - raise TypeError("can only perform ops with scalar values") - - return other - @classmethod def _add_numeric_methods_binary(cls): """ diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index d2bea5f68b92d..cfdaf65955dab 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -25,6 +25,7 @@ from pandas.core import ops import pandas.core.common as com +from pandas.core.construction import extract_array import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs from pandas.core.indexes.numeric import Int64Index @@ -782,7 +783,7 @@ def _evaluate_numeric_binop(self, other): # Must be an np.ndarray; GH#22390 return op(self._int64index, other) - other = self._validate_for_numeric_binop(other, op) + other = extract_array(other, extract_numpy=True) attrs = self._get_attributes_dict() attrs = self._maybe_update_attributes(attrs)
Lots of Index ops cleanup, breaking it up into small pieces.
https://api.github.com/repos/pandas-dev/pandas/pulls/27886
2019-08-12T23:13:41Z
2019-08-13T12:21:42Z
2019-08-13T12:21:41Z
2019-08-13T13:56:57Z
CLN: Index.__new__
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 02241eeaae7b2..d2a6d718a6543 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3447,15 +3447,14 @@ def _get_info_slice(obj, indexer): if not is_list_like(exclude): exclude = (exclude,) if exclude is not None else () - selection = tuple(map(frozenset, (include, exclude))) + selection = (frozenset(include), frozenset(exclude)) if not any(selection): 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( - lambda x: frozenset(map(infer_dtype_from_object, x)), selection - ) + include = frozenset(infer_dtype_from_object(x) for x in include) + exclude = frozenset(infer_dtype_from_object(x) for x in exclude) for dtypes in (include, exclude): invalidate_string_dtypes(dtypes) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 598c4dca9ce88..0ef63672325ca 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -309,12 +309,12 @@ def __new__( elif ( is_datetime64_any_dtype(data) - or (dtype is not None and is_datetime64_any_dtype(dtype)) + or is_datetime64_any_dtype(dtype) or "tz" in kwargs ): from pandas import DatetimeIndex - if dtype is not None and is_dtype_equal(_o_dtype, dtype): + if is_dtype_equal(_o_dtype, dtype): # GH#23524 passing `dtype=object` to DatetimeIndex is invalid, # will raise in the where `data` is already tz-aware. So # we leave it out of this step and cast to object-dtype after @@ -329,12 +329,10 @@ def __new__( ) return result - elif is_timedelta64_dtype(data) or ( - dtype is not None and is_timedelta64_dtype(dtype) - ): + elif is_timedelta64_dtype(data) or is_timedelta64_dtype(dtype): from pandas import TimedeltaIndex - if dtype is not None and is_dtype_equal(_o_dtype, dtype): + if is_dtype_equal(_o_dtype, dtype): # Note we can pass copy=False because the .astype below # will always make a copy result = TimedeltaIndex(data, copy=False, name=name, **kwargs) @@ -355,11 +353,9 @@ def __new__( elif is_extension_array_dtype(data) or is_extension_array_dtype(dtype): data = np.asarray(data) if not (dtype is None or is_object_dtype(dtype)): - # coerce to the provided dtype - data = dtype.construct_array_type()._from_sequence( - data, dtype=dtype, copy=False - ) + ea_cls = dtype.construct_array_type() + data = ea_cls._from_sequence(data, dtype=dtype, copy=False) # coerce to the object dtype data = data.astype(object) @@ -368,58 +364,48 @@ def __new__( # index-like elif isinstance(data, (np.ndarray, Index, ABCSeries)): if dtype is not None: - try: - - # we need to avoid having numpy coerce - # things that look like ints/floats to ints unless - # they are actually ints, e.g. '0' and 0.0 - # should not be coerced - # GH 11836 - if is_integer_dtype(dtype): - inferred = lib.infer_dtype(data, skipna=False) - if inferred == "integer": - 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") - - if inferred == "mixed-integer-float": - data = maybe_cast_to_integer_array(data, dtype) - - # If we are actually all equal to integers, - # then coerce to integer. - try: - return cls._try_convert_to_int_index( - data, copy, name, dtype - ) - except ValueError: - pass - - # Return an actual float index. - from .numeric import Float64Index - - return Float64Index(data, copy=copy, dtype=dtype, name=name) - - elif inferred == "string": - pass - else: - data = data.astype(dtype) - elif is_float_dtype(dtype): - inferred = lib.infer_dtype(data, skipna=False) - if inferred == "string": + # we need to avoid having numpy coerce + # things that look like ints/floats to ints unless + # they are actually ints, e.g. '0' and 0.0 + # should not be coerced + # GH 11836 + if is_integer_dtype(dtype): + inferred = lib.infer_dtype(data, skipna=False) + if inferred == "integer": + 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") + + if inferred == "mixed-integer-float": + data = maybe_cast_to_integer_array(data, dtype) + + # If we are actually all equal to integers, + # then coerce to integer. + try: + return cls._try_convert_to_int_index( + data, copy, name, dtype + ) + except ValueError: pass - else: - data = data.astype(dtype) + + # Return an actual float index. + from .numeric import Float64Index + + return Float64Index(data, copy=copy, dtype=dtype, name=name) + + elif inferred == "string": + pass else: - data = np.array(data, dtype=dtype, copy=copy) - - except (TypeError, ValueError) as e: - msg = str(e) - if ( - "cannot convert float" in msg - or "Trying to coerce float values to integer" in msg - ): - raise + data = data.astype(dtype) + elif is_float_dtype(dtype): + inferred = lib.infer_dtype(data, skipna=False) + if inferred == "string": + pass + else: + data = data.astype(dtype) + else: + data = np.array(data, dtype=dtype, copy=copy) # maybe coerce to a sub-class from pandas.core.indexes.period import PeriodIndex, IncompatibleFrequency @@ -555,16 +541,6 @@ def _simple_new(cls, values, name=None, dtype=None, **kwargs): Must be careful not to recurse. """ - if not hasattr(values, "dtype"): - if (values is None or not len(values)) and dtype is not None: - values = np.empty(0, dtype=dtype) - else: - values = np.array(values, copy=False) - if is_object_dtype(values): - values = cls( - values, name=name, dtype=dtype, **kwargs - )._ndarray_values - if isinstance(values, (ABCSeries, ABCIndexClass)): # Index._data must always be an ndarray. # This is no-copy for when _values is an ndarray, @@ -1862,8 +1838,6 @@ def inferred_type(self): @cache_readonly def is_all_dates(self): - if self._data is None: - return False return is_datetime_array(ensure_object(self.values)) # -------------------------------------------------------------------- @@ -3134,13 +3108,9 @@ def _convert_scalar_indexer(self, key, kind=None): """ @Appender(_index_shared_docs["_convert_slice_indexer"]) - def _convert_slice_indexer(self, key, kind=None): + def _convert_slice_indexer(self, key: slice, kind=None): assert kind in ["ix", "loc", "getitem", "iloc", None] - # if we are not a slice, then we are done - if not isinstance(key, slice): - return key - # validate iloc if kind == "iloc": return slice(
underlying goal is to share code between Index.__new__ and pd.array Unrelated cleanup in DataFrame.select_dtypes because I found it cumbersome.
https://api.github.com/repos/pandas-dev/pandas/pulls/27883
2019-08-12T21:16:22Z
2019-08-13T12:20:40Z
2019-08-13T12:20:40Z
2019-08-13T13:51:13Z
BUG: lzma is a required part of python, make it optional
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 7c2e488b98509..b8475b41a4950 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -103,7 +103,6 @@ MultiIndex I/O ^^^ - - Avoid calling ``S3File.s3`` when reading parquet, as this was removed in s3fs version 0.3.0 (:issue:`27756`) - - @@ -160,6 +159,14 @@ Other - - +I/O and LZMA +~~~~~~~~~~~~ + +Some users may unknowingly have an incomplete Python installation, which lacks the `lzma` module from the standard library. In this case, `import pandas` failed due to an `ImportError` (:issue: `27575`). +Pandas will now warn, rather than raising an `ImportError` if the `lzma` module is not present. Any subsequent attempt to use `lzma` methods will raise a `RuntimeError`. +A possible fix for the lack of the `lzma` module is to ensure you have the necessary libraries and then re-install Python. +For example, on MacOS installing Python with `pyenv` may lead to an incomplete Python installation due to unmet system dependencies at compilation time (like `xz`). Compilation will succeed, but Python might fail at run time. The issue can be solved by installing the necessary dependencies and then re-installing Python. + .. _whatsnew_0.251.contributors: Contributors diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index cafc31dad3568..6cc9dd22ce7c9 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -2,7 +2,6 @@ # See LICENSE for the license import bz2 import gzip -import lzma import os import sys import time @@ -59,9 +58,12 @@ from pandas.core.arrays import Categorical from pandas.core.dtypes.concat import union_categoricals import pandas.io.common as icom +from pandas.compat import _import_lzma, _get_lzma_file from pandas.errors import (ParserError, DtypeWarning, EmptyDataError, ParserWarning) +lzma = _import_lzma() + # Import CParserError as alias of ParserError for backwards compatibility. # Ultimately, we want to remove this import. See gh-12665 and gh-14479. CParserError = ParserError @@ -645,9 +647,9 @@ cdef class TextReader: 'zip file %s', str(zip_names)) elif self.compression == 'xz': if isinstance(source, str): - source = lzma.LZMAFile(source, 'rb') + source = _get_lzma_file(lzma)(source, 'rb') else: - source = lzma.LZMAFile(filename=source) + source = _get_lzma_file(lzma)(filename=source) else: raise ValueError('Unrecognized compression type: %s' % self.compression) diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 5ecd641fc68be..b32da8da3a1fb 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -10,6 +10,7 @@ import platform import struct import sys +import warnings PY35 = sys.version_info[:2] == (3, 5) PY36 = sys.version_info >= (3, 6) @@ -65,3 +66,32 @@ def is_platform_mac(): def is_platform_32bit(): return struct.calcsize("P") * 8 < 64 + + +def _import_lzma(): + """Attempts to import lzma, warning the user when lzma is not available. + """ + try: + import lzma + + return lzma + except ImportError: + msg = ( + "Could not import the lzma module. " + "Your installed Python is incomplete. " + "Attempting to use lzma compression will result in a RuntimeError." + ) + warnings.warn(msg) + + +def _get_lzma_file(lzma): + """Returns the lzma method LZMAFile when the module was correctly imported. + Otherwise, raises a RuntimeError. + """ + if lzma is None: + raise RuntimeError( + "lzma module not available. " + "A Python re-install with the proper " + "dependencies might be required to solve this issue." + ) + return lzma.LZMAFile diff --git a/pandas/io/common.py b/pandas/io/common.py index e01e473047b88..ac57cef372399 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -6,7 +6,6 @@ import gzip from http.client import HTTPException # noqa from io import BytesIO -import lzma import mmap import os import pathlib @@ -23,6 +22,7 @@ from urllib.request import pathname2url, urlopen import zipfile +from pandas.compat import _get_lzma_file, _import_lzma from pandas.errors import ( # noqa AbstractMethodError, DtypeWarning, @@ -35,6 +35,8 @@ from pandas._typing import FilePathOrBuffer +lzma = _import_lzma() + # gh-12665: Alias for now and remove later. CParserError = ParserError @@ -395,7 +397,7 @@ def _get_handle( # XZ Compression elif compression == "xz": - f = lzma.LZMAFile(path_or_buf, mode) + f = _get_lzma_file(lzma)(path_or_buf, mode) # Unrecognized Compression else: diff --git a/pandas/tests/io/test_compression.py b/pandas/tests/io/test_compression.py index ce459ab24afe0..16ca1109f266c 100644 --- a/pandas/tests/io/test_compression.py +++ b/pandas/tests/io/test_compression.py @@ -1,5 +1,7 @@ import contextlib import os +import subprocess +import textwrap import warnings import pytest @@ -125,3 +127,33 @@ def test_compression_warning(compression_only): with tm.assert_produces_warning(RuntimeWarning, check_stacklevel=False): with f: df.to_csv(f, compression=compression_only) + + +def test_with_missing_lzma(): + """Tests if import pandas works when lzma is not present.""" + # https://github.com/pandas-dev/pandas/issues/27575 + code = textwrap.dedent( + """\ + import sys + sys.modules['lzma'] = None + import pandas + """ + ) + subprocess.check_output(["python", "-c", code]) + + +def test_with_missing_lzma_runtime(): + """Tests if RuntimeError is hit when calling lzma without + having the module available.""" + code = textwrap.dedent( + """ + import sys + import pytest + sys.modules['lzma'] = None + import pandas + df = pandas.DataFrame() + with pytest.raises(RuntimeError, match='lzma module'): + df.to_csv('foo.csv', compression='xz') + """ + ) + subprocess.check_output(["python", "-c", code]) diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index 076d0c9f947c7..30555508f0998 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -13,7 +13,6 @@ import bz2 import glob import gzip -import lzma import os import pickle import shutil @@ -22,7 +21,7 @@ import pytest -from pandas.compat import is_platform_little_endian +from pandas.compat import _get_lzma_file, _import_lzma, is_platform_little_endian import pandas as pd from pandas import Index @@ -30,6 +29,8 @@ from pandas.tseries.offsets import Day, MonthEnd +lzma = _import_lzma() + @pytest.fixture(scope="module") def current_pickle_data(): @@ -270,7 +271,7 @@ def compress_file(self, src_path, dest_path, compression): with zipfile.ZipFile(dest_path, "w", compression=zipfile.ZIP_DEFLATED) as f: f.write(src_path, os.path.basename(src_path)) elif compression == "xz": - f = lzma.LZMAFile(dest_path, "w") + f = _get_lzma_file(lzma)(dest_path, "w") else: msg = "Unrecognized compression type: {}".format(compression) raise ValueError(msg) diff --git a/pandas/util/testing.py b/pandas/util/testing.py index cf8452cdd0c59..a8f0d0da52e1f 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -5,7 +5,6 @@ from functools import wraps import gzip import http.client -import lzma import os import re from shutil import rmtree @@ -26,7 +25,7 @@ ) import pandas._libs.testing as _testing -from pandas.compat import raise_with_traceback +from pandas.compat import _get_lzma_file, _import_lzma, raise_with_traceback from pandas.core.dtypes.common import ( is_bool, @@ -70,6 +69,8 @@ from pandas.io.common import urlopen from pandas.io.formats.printing import pprint_thing +lzma = _import_lzma() + N = 30 K = 4 _RAISE_NETWORK_ERROR_DEFAULT = False @@ -211,7 +212,7 @@ def decompress_file(path, compression): elif compression == "bz2": f = bz2.BZ2File(path, "rb") elif compression == "xz": - f = lzma.LZMAFile(path, "rb") + f = _get_lzma_file(lzma)(path, "rb") elif compression == "zip": zip_file = zipfile.ZipFile(path) zip_names = zip_file.namelist() @@ -264,9 +265,7 @@ def write_to_compressed(compression, path, data, dest="test"): compress_method = bz2.BZ2File elif compression == "xz": - import lzma - - compress_method = lzma.LZMAFile + compress_method = _get_lzma_file(lzma) else: msg = "Unrecognized compression type: {}".format(compression) raise ValueError(msg)
Importing `lzma` when Python has been compiled without its support (usually due to a lack of `xz` in the system) will raise a warning. Substituted `import lzma` for helper function. - [x] closes #27575 - [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/27882
2019-08-12T21:01:21Z
2019-08-19T13:06:15Z
2019-08-19T13:06:14Z
2021-09-08T17:02:03Z
CLN: use invalid_comparison for incorrect case in Index comparison
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 598c4dca9ce88..0c8169b4818a0 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -112,17 +112,11 @@ def cmp_method(self, other): with np.errstate(all="ignore"): result = op(self.values, np.asarray(other)) - # technically we could support bool dtyped Index - # for now just return the indexing array directly if is_bool_dtype(result): return result - try: - return Index(result) - except TypeError: - return result + return ops.invalid_comparison(self, other, op) name = "__{name}__".format(name=op.__name__) - # TODO: docstring? return set_function_name(cmp_method, name, cls) diff --git a/pandas/tests/indexes/test_numpy_compat.py b/pandas/tests/indexes/test_numpy_compat.py index f9ca1bca04165..645ad19ea4cc9 100644 --- a/pandas/tests/indexes/test_numpy_compat.py +++ b/pandas/tests/indexes/test_numpy_compat.py @@ -118,4 +118,7 @@ def test_elementwise_comparison_warning(): # this test. idx = Index([1, 2]) with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - idx == "a" + result = idx == "a" + + expected = np.array([False, False]) + tm.assert_numpy_array_equal(result, expected)
Only one test reaches this point, and we aren't currently checking for the output, just that a warning is emitted. This fixes the currently-incorrect output and updates the test to check for it.
https://api.github.com/repos/pandas-dev/pandas/pulls/27879
2019-08-12T20:07:29Z
2019-08-13T12:18:36Z
2019-08-13T12:18:36Z
2019-08-13T13:55:52Z
TST: Raise ValueError and suggestion to use header=None if header=-1 is pa…
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index dfa216b1db56e..823064949859f 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -105,7 +105,7 @@ I/O ^^^ - Avoid calling ``S3File.s3`` when reading parquet, as this was removed in s3fs version 0.3.0 (:issue:`27756`) -- +- Better error message when a negative header is passed in :func:`pandas.read_csv` (:issue:`27779`) - Plotting diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index f4b00b0aac5f7..a3ff837bc7f52 100755 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -1393,6 +1393,10 @@ def __init__(self, kwds): if isinstance(self.header, (list, tuple, np.ndarray)): if not all(map(is_integer, self.header)): raise ValueError("header must be integer or list of integers") + if any(i < 0 for i in self.header): + raise ValueError( + "cannot specify multi-index header with negative integers" + ) if kwds.get("usecols"): raise ValueError( "cannot specify usecols when specifying a multi-index header" @@ -1419,6 +1423,13 @@ def __init__(self, kwds): elif self.header is not None and not is_integer(self.header): raise ValueError("header must be integer or list of integers") + # GH 27779 + elif self.header is not None and self.header < 0: + raise ValueError( + "Passing negative integer to header is invalid. " + "For no header, use header=None instead" + ) + self._name_processed = False self._first_chunk = True diff --git a/pandas/tests/io/parser/test_header.py b/pandas/tests/io/parser/test_header.py index 99e0181741998..0ecd8be7ddc78 100644 --- a/pandas/tests/io/parser/test_header.py +++ b/pandas/tests/io/parser/test_header.py @@ -24,6 +24,35 @@ def test_read_with_bad_header(all_parsers): parser.read_csv(s, header=[10]) +def test_negative_header(all_parsers): + # see gh-27779 + parser = all_parsers + data = """1,2,3,4,5 +6,7,8,9,10 +11,12,13,14,15 +""" + with pytest.raises( + ValueError, + match="Passing negative integer to header is invalid. " + "For no header, use header=None instead", + ): + parser.read_csv(StringIO(data), header=-1) + + +@pytest.mark.parametrize("header", [([-1, 2, 4]), ([-5, 0])]) +def test_negative_multi_index_header(all_parsers, header): + # see gh-27779 + parser = all_parsers + data = """1,2,3,4,5 + 6,7,8,9,10 + 11,12,13,14,15 + """ + with pytest.raises( + ValueError, match="cannot specify multi-index header with negative integers" + ): + parser.read_csv(StringIO(data), header=header) + + @pytest.mark.parametrize("header", [True, False]) def test_bool_header_arg(all_parsers, header): # see gh-6114
…ssed - [x] closes #27779 - [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/27878
2019-08-12T20:05:22Z
2019-08-15T20:27:18Z
2019-08-15T20:27:18Z
2019-08-15T21:14:43Z
Backport PR #27777 on branch 0.25.x (Avoid calling S3File.s3)
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 637ac5c9c8bd1..01141122dde0a 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -104,7 +104,7 @@ MultiIndex I/O ^^^ -- +- Avoid calling ``S3File.s3`` when reading parquet, as this was removed in s3fs version 0.3.0 (:issue:`27756`) - - diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index 617f4f44ae8af..c7a8e597ffb41 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -184,12 +184,14 @@ def write( def read(self, path, columns=None, **kwargs): if is_s3_url(path): + from pandas.io.s3 import get_file_and_filesystem + # When path is s3:// an S3File is returned. # We need to retain the original path(str) while also # pass the S3File().open function to fsatparquet impl. - s3, _, _, should_close = get_filepath_or_buffer(path) + s3, filesystem = get_file_and_filesystem(path) try: - parquet_file = self.api.ParquetFile(path, open_with=s3.s3.open) + parquet_file = self.api.ParquetFile(path, open_with=filesystem.open) finally: s3.close() else: diff --git a/pandas/io/s3.py b/pandas/io/s3.py index 0a7c082fec51c..7e0a37e8cba20 100644 --- a/pandas/io/s3.py +++ b/pandas/io/s3.py @@ -1,8 +1,11 @@ """ s3 support for remote file interactivity """ +from typing import IO, Any, Optional, Tuple from urllib.parse import urlparse as parse_url from pandas.compat._optional import import_optional_dependency +from pandas._typing import FilePathOrBuffer + s3fs = import_optional_dependency( "s3fs", extra="The s3fs package is required to handle s3 files." ) @@ -14,9 +17,9 @@ def _strip_schema(url): return result.netloc + result.path -def get_filepath_or_buffer( - filepath_or_buffer, encoding=None, compression=None, mode=None -): +def get_file_and_filesystem( + filepath_or_buffer: FilePathOrBuffer, mode: Optional[str] = None +) -> Tuple[IO, Any]: from botocore.exceptions import NoCredentialsError if mode is None: @@ -24,7 +27,7 @@ def get_filepath_or_buffer( fs = s3fs.S3FileSystem(anon=False) try: - filepath_or_buffer = fs.open(_strip_schema(filepath_or_buffer), mode) + file = fs.open(_strip_schema(filepath_or_buffer), mode) except (FileNotFoundError, NoCredentialsError): # boto3 has troubles when trying to access a public file # when credentialed... @@ -33,5 +36,15 @@ def get_filepath_or_buffer( # A NoCredentialsError is raised if you don't have creds # for that bucket. fs = s3fs.S3FileSystem(anon=True) - filepath_or_buffer = fs.open(_strip_schema(filepath_or_buffer), mode) - return filepath_or_buffer, None, compression, True + file = fs.open(_strip_schema(filepath_or_buffer), mode) + return file, fs + + +def get_filepath_or_buffer( + filepath_or_buffer: FilePathOrBuffer, + encoding: Optional[str] = None, + compression: Optional[str] = None, + mode: Optional[str] = None, +) -> Tuple[IO, Optional[str], Optional[str], bool]: + file, _fs = get_file_and_filesystem(filepath_or_buffer, mode=mode) + return file, None, compression, True
Backport PR #27777: Avoid calling S3File.s3
https://api.github.com/repos/pandas-dev/pandas/pulls/27877
2019-08-12T19:11:06Z
2019-08-13T07:54:42Z
2019-08-13T07:54:42Z
2019-08-13T07:54:42Z
DOC:Use of "Yields" for documentation of DataFrame.iteritems()
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 02241eeaae7b2..aa59dc5de6896 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -775,7 +775,8 @@ def style(self): Iterates over the DataFrame columns, returning a tuple with the column name and the content as a Series. - %s + Yields + ------ label : object The column names for the DataFrame being iterated over. content : Series @@ -816,7 +817,7 @@ def style(self): Name: population, dtype: int64 """ - @Appender(_shared_docs["items"] % "Yields\n ------") + @Appender(_shared_docs["items"]) def items(self): if self.columns.is_unique and hasattr(self, "_item_cache"): for k in self.columns: @@ -825,9 +826,9 @@ def items(self): for i, k in enumerate(self.columns): yield k, self._ixs(i, axis=1) - @Appender(_shared_docs["items"] % "Returns\n -------") + @Appender(_shared_docs["items"]) def iteritems(self): - return self.items() + yield from self.items() def iterrows(self): """
changed `Returns` to `Yields` closes #27860
https://api.github.com/repos/pandas-dev/pandas/pulls/27876
2019-08-12T18:52:46Z
2019-08-14T18:54:49Z
2019-08-14T18:54:49Z
2019-08-15T02:06:23Z
DOC: clarify see also for DataFrame.iterrows()
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 02241eeaae7b2..e3edab117668f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -845,8 +845,8 @@ def iterrows(self): See Also -------- - itertuples : Iterate over DataFrame rows as namedtuples of the values. - items : Iterate over (column name, Series) pairs. + DataFrame.itertuples : Iterate over DataFrame rows as namedtuples of the values. + DataFrame.items : Iterate over (column name, Series) pairs. Notes -----
changed ` .x()` to `Dataframe.x()` in See Also for DataFrame.iterrows.
https://api.github.com/repos/pandas-dev/pandas/pulls/27875
2019-08-12T18:46:56Z
2019-08-13T08:00:15Z
null
2019-08-13T08:15:27Z
COMPAT: unique() should preserve the dtype of the input
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 53041441ba040..4816e6a519884 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -151,6 +151,7 @@ Other API changes - :meth:`pandas.api.types.infer_dtype` will now return "integer-na" for integer and ``np.nan`` mix (:issue:`27283`) - :meth:`MultiIndex.from_arrays` will no longer infer names from arrays if ``names=None`` is explicitly provided (:issue:`27292`) +- The returned dtype of ::func:`pd.unique` now matches the input dtype. (:issue:`27874`) - .. _whatsnew_1000.api.documentation: diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 4073ede84c6f6..2e5ab0d182aff 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -180,13 +180,13 @@ def _reconstruct_data(values, dtype, original): if is_extension_array_dtype(dtype): values = dtype.construct_array_type()._from_sequence(values) elif is_bool_dtype(dtype): - values = values.astype(dtype) + values = values.astype(dtype, copy=False) # we only support object dtypes bool Index if isinstance(original, ABCIndexClass): - values = values.astype(object) + values = values.astype(object, copy=False) elif dtype is not None: - values = values.astype(dtype) + values = values.astype(dtype, copy=False) return values @@ -396,7 +396,7 @@ def unique(values): table = htable(len(values)) uniques = table.unique(values) - uniques = _reconstruct_data(uniques, dtype, original) + uniques = _reconstruct_data(uniques, original.dtype, original) return uniques diff --git a/pandas/tests/test_base.py b/pandas/tests/test_base.py index c760c75e44f6b..483122a0eeaba 100644 --- a/pandas/tests/test_base.py +++ b/pandas/tests/test_base.py @@ -159,8 +159,8 @@ def test_memory_usage(self): class Ops: def _allow_na_ops(self, obj): """Whether to skip test cases including NaN""" - if isinstance(obj, Index) and (obj.is_boolean() or not obj._can_hold_na): - # don't test boolean / int64 index + if (isinstance(obj, Index) and obj.is_boolean()) or not obj._can_hold_na: + # don't test boolean / integer dtypes return False return True @@ -187,7 +187,24 @@ def setup_method(self, method): types = ["bool", "int", "float", "dt", "dt_tz", "period", "string", "unicode"] self.indexes = [getattr(self, "{}_index".format(t)) for t in types] self.series = [getattr(self, "{}_series".format(t)) for t in types] - self.objs = self.indexes + self.series + + # To test narrow dtypes, we use narrower *data* elements, not *index* elements + index = self.int_index + self.float32_series = Series(arr.astype(np.float32), index=index, name="a") + + arr_int = np.random.choice(10, size=10, replace=False) + self.int8_series = Series(arr_int.astype(np.int8), index=index, name="a") + self.int16_series = Series(arr_int.astype(np.int16), index=index, name="a") + self.int32_series = Series(arr_int.astype(np.int32), index=index, name="a") + + self.uint8_series = Series(arr_int.astype(np.uint8), index=index, name="a") + self.uint16_series = Series(arr_int.astype(np.uint16), index=index, name="a") + self.uint32_series = Series(arr_int.astype(np.uint32), index=index, name="a") + + nrw_types = ["float32", "int8", "int16", "int32", "uint8", "uint16", "uint32"] + self.narrow_series = [getattr(self, "{}_series".format(t)) for t in nrw_types] + + self.objs = self.indexes + self.series + self.narrow_series def check_ops_properties(self, props, filter=None, ignore_failures=False): for op in props: @@ -385,6 +402,7 @@ def test_value_counts_unique_nunique(self): if isinstance(o, Index): assert isinstance(result, o.__class__) tm.assert_index_equal(result, orig) + assert result.dtype == orig.dtype elif is_datetime64tz_dtype(o): # datetimetz Series returns array of Timestamp assert result[0] == orig[0] @@ -396,6 +414,7 @@ def test_value_counts_unique_nunique(self): ) else: tm.assert_numpy_array_equal(result, orig.values) + assert result.dtype == orig.dtype assert o.nunique() == len(np.unique(o.values)) @@ -904,7 +923,7 @@ def test_fillna(self): expected = [fill_value] * 2 + list(values[2:]) - expected = klass(expected) + expected = klass(expected, dtype=orig.dtype) o = klass(values) # check values has the same dtype as the original
The behavior of `pd.unique()` is surprising, because -- unlike `np.unique()` -- the result does not have the same `dtype` as the input: ```python In [1]: pd.Series([1,2,3], dtype=np.uint8).unique() Out[1]: array([1, 2, 3], dtype=uint64) ``` This PR just casts the output array to match the input dtype. Supercedes #27869. **Update:** Augmented the tests to cover narrow dtypes. ~I added a new assertion in `test_value_counts_unique_nunique()`, but it may not be sufficient. From what I can see, there isn't good coverage of `Series` whose *data* is not `int`/`float`/ etc. There is only good coverage of various *index* types. Any advice concerning test coverage?~ - [x] closes #27869 - [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/27874
2019-08-12T18:38:24Z
2019-10-07T01:08:25Z
2019-10-07T01:08:25Z
2019-10-07T01:08:28Z
requested edit to comparison method
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index a56521b9c9fec..c243b28aedd3c 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -835,13 +835,12 @@ def wrapper(self, other, axis=None): elif isinstance(other, ABCSeries) and not self._indexed_same(other): raise ValueError("Can only compare identically-labeled Series objects") - elif ( - is_list_like(other) - and len(other) != len(self) - and not isinstance(other, frozenset) - ): - # TODO: why are we treating len-1 frozenset differently? - raise ValueError("Lengths must match to compare") + elif isinstance(other, (np.ndarray, ABCIndexClass, ABCSeries)): + # TODO: make this treatment consistent across ops and classes. + # We are not catching all listlikes here (e.g. frozenset, tuple) + # The ambiguous case is object-dtype. See GH#27803 + if len(self) != len(other): + raise ValueError("Lengths must match to compare") if is_categorical_dtype(self): # Dispatch to Categorical implementation; CategoricalIndex
cc @jorisvandenbossche discussed in #27803
https://api.github.com/repos/pandas-dev/pandas/pulls/27873
2019-08-12T17:20:51Z
2019-08-13T12:17:38Z
2019-08-13T12:17:37Z
2019-08-14T20:09:42Z
Backport PR #27868 on branch 0.25.x (CI: Pin Python to 3.7.3)
diff --git a/ci/deps/azure-37-locale.yaml b/ci/deps/azure-37-locale.yaml index 05adbf0c924dc..6844e929eae78 100644 --- a/ci/deps/azure-37-locale.yaml +++ b/ci/deps/azure-37-locale.yaml @@ -17,7 +17,7 @@ dependencies: - openpyxl - pytables - python-dateutil - - python=3.7.* + - python=3.7.3 - pytz - s3fs - scipy diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml index 5cf897c98da10..3b68a573497e6 100644 --- a/ci/deps/azure-37-numpydev.yaml +++ b/ci/deps/azure-37-numpydev.yaml @@ -2,7 +2,7 @@ name: pandas-dev channels: - defaults dependencies: - - python=3.7.* + - python=3.7.3 - pytz - Cython>=0.28.2 # universal diff --git a/ci/deps/travis-37.yaml b/ci/deps/travis-37.yaml index c9a8c274fb144..2d7f4b483729f 100644 --- a/ci/deps/travis-37.yaml +++ b/ci/deps/travis-37.yaml @@ -4,7 +4,7 @@ channels: - conda-forge - c3i_test dependencies: - - python=3.7.* + - python=3.7.3 - botocore>=1.11 - cython>=0.28.2 - numpy diff --git a/environment.yml b/environment.yml index 93e8302b498a0..d54caf9d013c7 100644 --- a/environment.yml +++ b/environment.yml @@ -5,7 +5,7 @@ channels: dependencies: # required - numpy>=1.15 - - python=3 + - python=3.7.3 - python-dateutil>=2.6.1 - pytz diff --git a/requirements-dev.txt b/requirements-dev.txt index e49ad10bfc99d..9d80a13350579 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,4 +1,5 @@ numpy>=1.15 +python==3.7.3 python-dateutil>=2.6.1 pytz asv
Backport PR #27868: CI: Pin Python to 3.7.3
https://api.github.com/repos/pandas-dev/pandas/pulls/27872
2019-08-12T16:38:19Z
2019-08-12T19:10:35Z
2019-08-12T19:10:35Z
2019-08-12T19:10:35Z
DOC:Standardize use of "Iterate" and "Iterator"
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 02241eeaae7b2..9752af6eb352f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -770,7 +770,7 @@ def style(self): _shared_docs[ "items" ] = r""" - Iterator over (column name, Series) pairs. + Iterate over (column name, Series) pairs. Iterates over the DataFrame columns, returning a tuple with the column name and the content as a Series.
changed `Iterator over` --> `Iterate over` closes #27861
https://api.github.com/repos/pandas-dev/pandas/pulls/27871
2019-08-12T16:20:20Z
2019-08-13T11:57:29Z
2019-08-13T11:57:29Z
2019-08-13T11:57:31Z
DOC: Clarify that unique() promotes dtype to 64-bit
diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 21d12d02c9008..5cc3afbae92d3 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -320,6 +320,7 @@ def unique(values): of appearance. This does NOT sort. Significantly faster than numpy.unique. Includes NA values. + For numeric input, the dtype of the result will be promoted to 64-bit. Parameters ---------- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 598c4dca9ce88..b669475531f10 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2122,6 +2122,7 @@ def dropna(self, how="any"): Returns ------- Index without duplicates + For numeric input, the dtype of the result will be promoted to 64-bit. See Also -------- diff --git a/pandas/core/series.py b/pandas/core/series.py index 4e64a25e430eb..a3f0bfaaf8fd0 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1910,8 +1910,9 @@ def unique(self): Notes ----- - Returns the unique values as a NumPy array. In case of an - extension-array backed Series, a new + Returns the unique values as a NumPy array. + For numeric input, the dtype of the result will be promoted to 64-bit. + In case of an extension-array backed Series, a new :class:`~api.extensions.ExtensionArray` of that type with just the unique values is returned. This includes
I found this behavior surprising: ```python In [1]: pd.Series([1,2,3], dtype=np.uint8).unique() Out[1]: array([1, 2, 3], dtype=uint64) ``` ... because I did not expect a different dtype in the result. This PR adds a sentence to the docs to clarify this. - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - (n/a) closes #xxxx - (n/a) tests added / passed - (n/a) whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27869
2019-08-12T15:39:59Z
2019-08-15T13:42:18Z
null
2019-10-07T00:15:11Z
CI: Pin Python to 3.7.3
diff --git a/ci/deps/azure-37-locale.yaml b/ci/deps/azure-37-locale.yaml index 26dcd213bbfa0..437fbc24b9411 100644 --- a/ci/deps/azure-37-locale.yaml +++ b/ci/deps/azure-37-locale.yaml @@ -17,7 +17,7 @@ dependencies: - openpyxl - pytables - python-dateutil - - python=3.7.* + - python=3.7.3 - pytz - s3fs - scipy diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml index 65c92ec1dcf0d..e1acda7ecf3c7 100644 --- a/ci/deps/azure-37-numpydev.yaml +++ b/ci/deps/azure-37-numpydev.yaml @@ -2,7 +2,7 @@ name: pandas-dev channels: - defaults dependencies: - - python=3.7.* + - python=3.7.3 - pytz - Cython>=0.28.2 # universal diff --git a/ci/deps/travis-37.yaml b/ci/deps/travis-37.yaml index 9e08c41a3d9c0..d7bed9e3f03f2 100644 --- a/ci/deps/travis-37.yaml +++ b/ci/deps/travis-37.yaml @@ -4,7 +4,7 @@ channels: - conda-forge - c3i_test dependencies: - - python=3.7.* + - python=3.7.3 - botocore>=1.11 - cython>=0.28.2 - numpy diff --git a/environment.yml b/environment.yml index 6d2cd701c3854..0cbd500209b6c 100644 --- a/environment.yml +++ b/environment.yml @@ -5,7 +5,7 @@ channels: dependencies: # required - numpy>=1.15 - - python=3 + - python=3.7.3 - python-dateutil>=2.6.1 - pytz diff --git a/requirements-dev.txt b/requirements-dev.txt index cf11a3ee28258..f866f1436edc6 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,4 +1,5 @@ numpy>=1.15 +python==3.7.3 python-dateutil>=2.6.1 pytz asv
https://api.github.com/repos/pandas-dev/pandas/pulls/27868
2019-08-12T13:56:29Z
2019-08-12T16:37:50Z
2019-08-12T16:37:50Z
2019-08-21T14:40:00Z
Added missing space to error description
diff --git a/pandas/io/feather_format.py b/pandas/io/feather_format.py index 6fe22f14c2c5b..25a6db675265d 100644 --- a/pandas/io/feather_format.py +++ b/pandas/io/feather_format.py @@ -39,7 +39,7 @@ def to_feather(df, path): if not isinstance(df.index, Int64Index): raise ValueError( "feather does not support serializing {} " - "for the index; you can .reset_index()" + "for the index; you can .reset_index() " "to make the index into column(s)".format(type(df.index)) )
https://api.github.com/repos/pandas-dev/pandas/pulls/27866
2019-08-12T12:28:32Z
2019-08-13T01:08:38Z
2019-08-13T01:08:38Z
2019-08-13T01:08:46Z
BUG: DataFrameGroupBy.transform and ngroup do not work with cumcount
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 34b149a6b8261..6bf9a3b705527 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -120,7 +120,6 @@ Groupby/resample/rolling - Bug in :meth:`pandas.core.groupby.DataFrameGroupBy.transform` where applying a timezone conversion lambda function would drop timezone information (:issue:`27496`) - Bug in windowing over read-only arrays (:issue:`27766`) - Fixed segfault in `pandas.core.groupby.DataFrameGroupBy.quantile` when an invalid quantile was passed (:issue:`27470`) -- Reshaping ^^^^^^^^^ diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py index fc3bb69afd0cb..889fb2fbb75ae 100644 --- a/pandas/core/groupby/base.py +++ b/pandas/core/groupby/base.py @@ -100,7 +100,9 @@ def _gotitem(self, key, ndim, subset=None): # cythonized transformations or canned "agg+broadcast", which do not # require postprocessing of the result by transform. -cythonized_kernels = frozenset(["cumprod", "cumsum", "shift", "cummin", "cummax"]) +cythonized_kernels = frozenset( + ["cumprod", "cumsum", "shift", "cummin", "cummax", "cumcount"] +) cython_cast_blacklist = frozenset(["rank", "count", "size", "idxmin", "idxmax"]) @@ -120,7 +122,6 @@ def _gotitem(self, key, ndim, subset=None): "mean", "median", "min", - "ngroup", "nth", "nunique", "prod", @@ -158,6 +159,7 @@ def _gotitem(self, key, ndim, subset=None): "rank", "shift", "tshift", + "ngroup", ] ) diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index ea2bd22cccc3d..9f350411084f3 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -583,7 +583,9 @@ def transform(self, func, *args, **kwargs): if not (func in base.transform_kernel_whitelist): msg = "'{func}' is not a valid function name for transform(name)" raise ValueError(msg.format(func=func)) - if func in base.cythonized_kernels: + + # transformation are added as well since they are broadcasted already + if func in base.cythonized_kernels or func in base.transformation_kernels: # cythonized transformation or canned "reduction+broadcast" return getattr(self, func)(*args, **kwargs) else: diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py index d3972e6ba9008..63104e978839f 100644 --- a/pandas/tests/groupby/test_transform.py +++ b/pandas/tests/groupby/test_transform.py @@ -20,7 +20,11 @@ ) from pandas.core.groupby.groupby import DataError from pandas.util import testing as tm -from pandas.util.testing import assert_frame_equal, assert_series_equal +from pandas.util.testing import ( + assert_frame_equal, + assert_index_equal, + assert_series_equal, +) def assert_fp_equal(a, b): @@ -1034,8 +1038,6 @@ def test_transform_agg_by_name(reduction_func, obj): func = reduction_func g = obj.groupby(np.repeat([0, 1], 3)) - if func == "ngroup": # GH#27468 - pytest.xfail("TODO: g.transform('ngroup') doesn't work") if func == "size": # GH#27469 pytest.xfail("TODO: g.transform('size') doesn't work") @@ -1074,3 +1076,58 @@ def test_transform_lambda_with_datetimetz(): name="time", ) assert_series_equal(result, expected) + + +def test_transform_cumcount_ngroup(): + df = DataFrame(dict(a=[0, 0, 0, 1, 1, 1], b=range(6))) + g = df.groupby(np.repeat([0, 1], 3)) + + # GH 27472 + result = g.transform("cumcount") + expected = g.cumcount() + assert_series_equal(result, expected) + + # GH 27468 + result = g.transform("ngroup") + expected = g.ngroup() + assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + "func", + [ + "backfill", + "bfill", + "cumcount", + "cummax", + "cummin", + "cumprod", + "cumsum", + "diff", + "ffill", + "pad", + "pct_change", + "rank", + "shift", + "ngroup", + pytest.param( + "fillna", + marks=pytest.mark.xfail(reason="GH27905: 'fillna' get empty DataFrame now"), + ), + pytest.param( + "tshift", marks=pytest.mark.xfail(reason="GH27905: Should apply to ts data") + ), + pytest.param( + "corrwith", + marks=pytest.mark.xfail(reason="GH27905: Inapplicable to the data"), + ), + ], +) +def test_transformation_kernels_length(func): + # This test is to evaluate if after transformation, the index + # of transformed data is still the same with original DataFrame + df = DataFrame(dict(a=[0, 0, 0, 1, 1, 1], b=range(6))) + g = df.groupby(np.repeat([0, 1], 3)) + + result = g.transform(func) + assert_index_equal(result.index, df.index)
- [ ] closes #27472 - [ ] 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/27858
2019-08-11T15:01:39Z
2019-10-29T00:04:49Z
null
2019-10-29T00:04:49Z
BUG: add back check for MultiIndex case and take_split_path
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 7c2e488b98509..b97f45efbeae9 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -84,7 +84,7 @@ Indexing - Bug in partial-string indexing returning a NumPy array rather than a ``Series`` when indexing with a scalar like ``.loc['2015']`` (:issue:`27516`) - Break reference cycle involving :class:`Index` to allow garbage collection of :class:`Index` objects without running the GC. (:issue:`27585`) -- +- Fix regression in assigning values to a single column of a DataFrame with a ``MultiIndex`` columns (:issue:`27841`). - Missing diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index e308ae03730b3..ea00737f776ee 100755 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -321,6 +321,17 @@ def _setitem_with_indexer(self, indexer, value): val = list(value.values()) if isinstance(value, dict) else value take_split_path = not blk._can_hold_element(val) + # if we have any multi-indexes that have non-trivial slices + # (not null slices) then we must take the split path, xref + # GH 10360, GH 27841 + if isinstance(indexer, tuple) and len(indexer) == len(self.obj.axes): + for i, ax in zip(indexer, self.obj.axes): + if isinstance(ax, MultiIndex) and not ( + is_integer(i) or com.is_null_slice(i) + ): + take_split_path = True + break + if isinstance(indexer, tuple): nindexer = [] for i, idx in enumerate(indexer): diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index a08b2b4c66af2..8b48c2bf7169f 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -390,3 +390,26 @@ def test_loc_getitem_lowerdim_corner(multiindex_dataframe_random_data): expected = 0 result = df.sort_index().loc[("bar", "three"), "B"] assert result == expected + + +def test_loc_setitem_single_column_slice(): + # case from https://github.com/pandas-dev/pandas/issues/27841 + df = DataFrame( + "string", + index=list("abcd"), + columns=MultiIndex.from_product([["Main"], ("another", "one")]), + ) + df["labels"] = "a" + df.loc[:, "labels"] = df.index + tm.assert_numpy_array_equal(np.asarray(df["labels"]), np.asarray(df.index)) + + # test with non-object block + df = DataFrame( + np.nan, + index=range(4), + columns=MultiIndex.from_tuples([("A", "1"), ("A", "2"), ("B", "1")]), + ) + expected = df.copy() + df.loc[:, "B"] = np.arange(4) + expected.iloc[:, 2] = np.arange(4) + tm.assert_frame_equal(df, expected)
Closes #27841
https://api.github.com/repos/pandas-dev/pandas/pulls/27855
2019-08-10T19:42:15Z
2019-08-13T01:04:21Z
2019-08-13T01:04:21Z
2019-08-14T07:08:40Z
DOC:add append example in to_excel documentation
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 5a1b2a5dcd20b..71d5068e2e0fc 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2179,6 +2179,12 @@ def _repr_data_resource_(self): ... df1.to_excel(writer, sheet_name='Sheet_name_1') ... df2.to_excel(writer, sheet_name='Sheet_name_2') + ExcelWriter can also be used to append to an existing Excel file: + + >>> with pd.ExcelWriter('output.xlsx', + ... mode='a') as writer: # doctest: +SKIP + ... df.to_excel(writer, sheet_name='Sheet_name_3') + To set the library that is used to write the Excel file, you can pass the `engine` keyword (the default engine is automatically chosen depending on the file extension):
closes #27051
https://api.github.com/repos/pandas-dev/pandas/pulls/27852
2019-08-10T05:13:15Z
2019-08-13T09:41:59Z
2019-08-13T09:41:59Z
2019-08-13T11:36:30Z
DOC: Add CoC to the README
diff --git a/README.md b/README.md index aeeea1464e1fd..3cde98d3145f2 100644 --- a/README.md +++ b/README.md @@ -233,3 +233,5 @@ You can also triage issues which may include reproducing bug reports, or asking Or maybe through using pandas you have an idea of your own or are looking for something in the documentation and thinking ‘this can be improved’...you can do something about it! Feel free to ask questions on the [mailing list](https://groups.google.com/forum/?fromgroups#!forum/pydata) or on [Gitter](https://gitter.im/pydata/pandas). + +As contributors and maintainers to this project, you are expected to abide by pandas' code of conduct. More information can be found at: [Contributor Code of Conduct](https://github.com/pandas-dev/pandas/blob/master/.github/CODE_OF_CONDUCT.md)
@datapythonista : Add CoC to README file
https://api.github.com/repos/pandas-dev/pandas/pulls/27851
2019-08-10T04:43:03Z
2019-08-13T14:12:45Z
2019-08-13T14:12:45Z
2019-08-13T14:12:48Z
CLN: op-->opname in Categorical _cat_compare_op
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 9862b4b530424..13058882084ff 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -77,7 +77,7 @@ ) -def _cat_compare_op(op): +def _cat_compare_op(opname): def f(self, other): # On python2, you can usually compare any type to any type, and # Categoricals can be seen as a custom type, but having different @@ -90,7 +90,7 @@ def f(self, other): other = lib.item_from_zerodim(other) if not self.ordered: - if op in ["__lt__", "__gt__", "__le__", "__ge__"]: + if opname in ["__lt__", "__gt__", "__le__", "__ge__"]: raise TypeError( "Unordered Categoricals can only compare equality or not" ) @@ -117,7 +117,7 @@ def f(self, other): other_codes = other._codes mask = (self._codes == -1) | (other_codes == -1) - f = getattr(self._codes, op) + f = getattr(self._codes, opname) ret = f(other_codes) if mask.any(): # In other series, the leads to False, so do that here too @@ -127,38 +127,38 @@ def f(self, other): if is_scalar(other): if other in self.categories: i = self.categories.get_loc(other) - ret = getattr(self._codes, op)(i) + ret = getattr(self._codes, opname)(i) # check for NaN in self mask = self._codes == -1 ret[mask] = False return ret else: - if op == "__eq__": + if opname == "__eq__": return np.repeat(False, len(self)) - elif op == "__ne__": + elif opname == "__ne__": return np.repeat(True, len(self)) else: msg = ( "Cannot compare a Categorical for op {op} with a " "scalar, which is not a category." ) - raise TypeError(msg.format(op=op)) + raise TypeError(msg.format(op=opname)) else: # allow categorical vs object dtype array comparisons for equality # these are only positional comparisons - if op in ["__eq__", "__ne__"]: - return getattr(np.array(self), op)(np.array(other)) + if opname in ["__eq__", "__ne__"]: + return getattr(np.array(self), opname)(np.array(other)) msg = ( "Cannot compare a Categorical for op {op} with type {typ}." "\nIf you want to compare values, use 'np.asarray(cat) " "<op> other'." ) - raise TypeError(msg.format(op=op, typ=type(other))) + raise TypeError(msg.format(op=opname, typ=type(other))) - f.__name__ = op + f.__name__ = opname return f
In general we use `op` to refer to operator.foo, and `opname` to refer to the string, which is what is passed in this case.
https://api.github.com/repos/pandas-dev/pandas/pulls/27849
2019-08-10T01:13:28Z
2019-08-12T18:53:36Z
2019-08-12T18:53:36Z
2019-08-12T19:04:48Z
TST: parametrize arithmetic tests
diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 1fb93a182ba0b..5931cd93cc8c5 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -30,6 +30,54 @@ import pandas.util.testing as tm +def assert_invalid_comparison(left, right, box): + """ + Assert that comparison operations with mismatched types behave correctly. + + Parameters + ---------- + left : np.ndarray, ExtensionArray, Index, or Series + right : object + box : {pd.DataFrame, pd.Series, pd.Index, tm.to_array} + """ + # Not for tznaive-tzaware comparison + + # Note: not quite the same as how we do this for tm.box_expected + xbox = box if box is not pd.Index else np.array + + result = left == right + expected = xbox(np.zeros(result.shape, dtype=np.bool_)) + + tm.assert_equal(result, expected) + + result = right == left + tm.assert_equal(result, expected) + + result = left != right + tm.assert_equal(result, ~expected) + + result = right != left + tm.assert_equal(result, ~expected) + + msg = "Invalid comparison between" + with pytest.raises(TypeError, match=msg): + left < right + with pytest.raises(TypeError, match=msg): + left <= right + with pytest.raises(TypeError, match=msg): + left > right + with pytest.raises(TypeError, match=msg): + left >= right + with pytest.raises(TypeError, match=msg): + right < left + with pytest.raises(TypeError, match=msg): + right <= left + with pytest.raises(TypeError, match=msg): + right > left + with pytest.raises(TypeError, match=msg): + right >= left + + def assert_all(obj): """ Test helper to call call obj.all() the appropriate number of times on @@ -47,7 +95,7 @@ def assert_all(obj): class TestDatetime64ArrayLikeComparisons: # Comparison tests for datetime64 vectors fully parametrized over - # DataFrame/Series/DatetimeIndex/DateteimeArray. Ideally all comparison + # DataFrame/Series/DatetimeIndex/DatetimeArray. Ideally all comparison # tests will eventually end up here. def test_compare_zerodim(self, tz_naive_fixture, box_with_array): @@ -59,36 +107,61 @@ def test_compare_zerodim(self, tz_naive_fixture, box_with_array): other = np.array(dti.to_numpy()[0]) - # FIXME: ValueError with transpose on tzaware - dtarr = tm.box_expected(dti, box, transpose=False) + dtarr = tm.box_expected(dti, box) result = dtarr <= other expected = np.array([True, False, False]) - expected = tm.box_expected(expected, xbox, transpose=False) + expected = tm.box_expected(expected, xbox) tm.assert_equal(result, expected) + def test_dt64arr_cmp_date_invalid(self, tz_naive_fixture, box_with_array): + # GH#19800, GH#19301 datetime.date comparison raises to + # match DatetimeIndex/Timestamp. This also matches the behavior + # of stdlib datetime.datetime + tz = tz_naive_fixture -class TestDatetime64DataFrameComparison: - @pytest.mark.parametrize( - "timestamps", - [ - [pd.Timestamp("2012-01-01 13:00:00+00:00")] * 2, - [pd.Timestamp("2012-01-01 13:00:00")] * 2, - ], - ) - def test_tz_aware_scalar_comparison(self, timestamps): - # GH#15966 - df = pd.DataFrame({"test": timestamps}) - expected = pd.DataFrame({"test": [False, False]}) - tm.assert_frame_equal(df == -1, expected) + dti = pd.date_range("20010101", periods=10, tz=tz) + date = dti[0].to_pydatetime().date() + + dtarr = tm.box_expected(dti, box_with_array) + assert_invalid_comparison(dtarr, date, box_with_array) - def test_dt64_nat_comparison(self): + @pytest.mark.parametrize("other", ["foo", -1, 99, 4.0, object(), timedelta(days=2)]) + def test_dt64arr_cmp_scalar_invalid(self, other, tz_naive_fixture, box_with_array): + # GH#22074, GH#15966 + tz = tz_naive_fixture + + rng = date_range("1/1/2000", periods=10, tz=tz) + dtarr = tm.box_expected(rng, box_with_array) + assert_invalid_comparison(dtarr, other, box_with_array) + + @pytest.mark.parametrize("other", [None, np.nan]) + def test_dt64arr_cmp_na_scalar_invalid( + self, other, tz_naive_fixture, box_with_array + ): + # GH#19301 + tz = tz_naive_fixture + dti = pd.date_range("2016-01-01", periods=2, tz=tz) + dtarr = tm.box_expected(dti, box_with_array) + assert_invalid_comparison(dtarr, other, box_with_array) + + def test_dt64arr_nat_comparison(self, tz_naive_fixture, box_with_array): # GH#22242, GH#22163 DataFrame considered NaT == ts incorrectly - ts = pd.Timestamp.now() - df = pd.DataFrame([ts, pd.NaT]) - expected = pd.DataFrame([True, False]) + tz = tz_naive_fixture + box = box_with_array + xbox = box if box is not pd.Index else np.ndarray + + ts = pd.Timestamp.now(tz) + ser = pd.Series([ts, pd.NaT]) + + # FIXME: Can't transpose because that loses the tz dtype on + # the NaT column + obj = tm.box_expected(ser, box, transpose=False) - result = df == ts - tm.assert_frame_equal(result, expected) + expected = pd.Series([True, False], dtype=np.bool_) + expected = tm.box_expected(expected, xbox, transpose=False) + + result = obj == ts + tm.assert_equal(result, expected) class TestDatetime64SeriesComparison: @@ -142,35 +215,17 @@ def test_nat_comparisons(self, dtype, box, reverse, pair): expected = Series([False, False, True]) tm.assert_series_equal(left <= right, expected) - def test_comparison_invalid(self, box_with_array): + def test_comparison_invalid(self, tz_naive_fixture, box_with_array): # GH#4968 # invalid date/int comparisons - xbox = box_with_array if box_with_array is not pd.Index else np.ndarray - + tz = tz_naive_fixture ser = Series(range(5)) - ser2 = Series(pd.date_range("20010101", periods=5)) + ser2 = Series(pd.date_range("20010101", periods=5, tz=tz)) ser = tm.box_expected(ser, box_with_array) ser2 = tm.box_expected(ser2, box_with_array) - for (x, y) in [(ser, ser2), (ser2, ser)]: - - result = x == y - expected = tm.box_expected([False] * 5, xbox) - tm.assert_equal(result, expected) - - result = x != y - expected = tm.box_expected([True] * 5, xbox) - tm.assert_equal(result, expected) - msg = "Invalid comparison between" - with pytest.raises(TypeError, match=msg): - x >= y - with pytest.raises(TypeError, match=msg): - x > y - with pytest.raises(TypeError, match=msg): - x < y - with pytest.raises(TypeError, match=msg): - x <= y + assert_invalid_comparison(ser, ser2, box_with_array) @pytest.mark.parametrize( "data", @@ -227,26 +282,6 @@ def test_series_comparison_scalars(self): expected = Series([x > val for x in series]) tm.assert_series_equal(result, expected) - def test_dt64ser_cmp_date_invalid(self, box_with_array): - # GH#19800 datetime.date comparison raises to - # match DatetimeIndex/Timestamp. This also matches the behavior - # of stdlib datetime.datetime - - ser = pd.date_range("20010101", periods=10) - date = ser[0].to_pydatetime().date() - - ser = tm.box_expected(ser, box_with_array) - assert_all(~(ser == date)) - assert_all(ser != date) - with pytest.raises(TypeError): - ser > date - with pytest.raises(TypeError): - ser < date - with pytest.raises(TypeError): - ser >= date - with pytest.raises(TypeError): - ser <= date - @pytest.mark.parametrize( "left,right", [("lt", "gt"), ("le", "ge"), ("eq", "eq"), ("ne", "ne")] ) @@ -388,57 +423,6 @@ def test_dti_cmp_datetimelike(self, other, tz_naive_fixture): expected = np.array([True, False]) tm.assert_numpy_array_equal(result, expected) - def dt64arr_cmp_non_datetime(self, tz_naive_fixture, box_with_array): - # GH#19301 by convention datetime.date is not considered comparable - # to Timestamp or DatetimeIndex. This may change in the future. - tz = tz_naive_fixture - dti = pd.date_range("2016-01-01", periods=2, tz=tz) - dtarr = tm.box_expected(dti, box_with_array) - - other = datetime(2016, 1, 1).date() - assert not (dtarr == other).any() - assert (dtarr != other).all() - with pytest.raises(TypeError): - dtarr < other - with pytest.raises(TypeError): - dtarr <= other - with pytest.raises(TypeError): - dtarr > other - with pytest.raises(TypeError): - dtarr >= other - - @pytest.mark.parametrize("other", [None, np.nan, pd.NaT]) - def test_dti_eq_null_scalar(self, other, tz_naive_fixture): - # GH#19301 - tz = tz_naive_fixture - dti = pd.date_range("2016-01-01", periods=2, tz=tz) - assert not (dti == other).any() - - @pytest.mark.parametrize("other", [None, np.nan, pd.NaT]) - def test_dti_ne_null_scalar(self, other, tz_naive_fixture): - # GH#19301 - tz = tz_naive_fixture - dti = pd.date_range("2016-01-01", periods=2, tz=tz) - assert (dti != other).all() - - @pytest.mark.parametrize("other", [None, np.nan]) - def test_dti_cmp_null_scalar_inequality( - self, tz_naive_fixture, other, box_with_array - ): - # GH#19301 - tz = tz_naive_fixture - dti = pd.date_range("2016-01-01", periods=2, tz=tz) - dtarr = tm.box_expected(dti, box_with_array) - msg = "Invalid comparison between" - with pytest.raises(TypeError, match=msg): - dtarr < other - with pytest.raises(TypeError, match=msg): - dtarr <= other - with pytest.raises(TypeError, match=msg): - dtarr > other - with pytest.raises(TypeError, match=msg): - dtarr >= other - @pytest.mark.parametrize("dtype", [None, object]) def test_dti_cmp_nat(self, dtype, box_with_array): if box_with_array is tm.to_array and dtype is object: @@ -728,34 +712,6 @@ def test_dti_cmp_str(self, tz_naive_fixture): expected = np.array([True] * 10) tm.assert_numpy_array_equal(result, expected) - @pytest.mark.parametrize("other", ["foo", 99, 4.0, object(), timedelta(days=2)]) - def test_dt64arr_cmp_scalar_invalid(self, other, tz_naive_fixture, box_with_array): - # GH#22074 - tz = tz_naive_fixture - xbox = box_with_array if box_with_array is not pd.Index else np.ndarray - - rng = date_range("1/1/2000", periods=10, tz=tz) - rng = tm.box_expected(rng, box_with_array) - - result = rng == other - expected = np.array([False] * 10) - expected = tm.box_expected(expected, xbox) - tm.assert_equal(result, expected) - - result = rng != other - expected = np.array([True] * 10) - expected = tm.box_expected(expected, xbox) - tm.assert_equal(result, expected) - msg = "Invalid comparison between" - with pytest.raises(TypeError, match=msg): - rng < other - with pytest.raises(TypeError, match=msg): - rng <= other - with pytest.raises(TypeError, match=msg): - rng > other - with pytest.raises(TypeError, match=msg): - rng >= other - def test_dti_cmp_list(self): rng = date_range("1/1/2000", periods=10) @@ -2576,24 +2532,3 @@ def test_shift_months(years, months): raw = [x + pd.offsets.DateOffset(years=years, months=months) for x in dti] expected = DatetimeIndex(raw) tm.assert_index_equal(actual, expected) - - -# FIXME: this belongs in scalar tests -class SubDatetime(datetime): - pass - - -@pytest.mark.parametrize( - "lh,rh", - [ - (SubDatetime(2000, 1, 1), Timedelta(hours=1)), - (Timedelta(hours=1), SubDatetime(2000, 1, 1)), - ], -) -def test_dt_subclass_add_timedelta(lh, rh): - # GH 25851 - # ensure that subclassed datetime works for - # Timedelta operations - result = lh + rh - expected = SubDatetime(2000, 1, 1, 1) - assert result == expected diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index 4b58c290c3cea..ed693d873efb8 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -573,12 +573,19 @@ def test_parr_add_sub_float_raises(self, op, other, box_with_array): @pytest.mark.parametrize( "other", [ + # datetime scalars pd.Timestamp.now(), pd.Timestamp.now().to_pydatetime(), pd.Timestamp.now().to_datetime64(), + # datetime-like arrays + pd.date_range("2016-01-01", periods=3, freq="H"), + pd.date_range("2016-01-01", periods=3, tz="Europe/Brussels"), + pd.date_range("2016-01-01", periods=3, freq="S")._data, + pd.date_range("2016-01-01", periods=3, tz="Asia/Tokyo")._data, + # Miscellaneous invalid types ], ) - def test_parr_add_sub_datetime_scalar(self, other, box_with_array): + def test_parr_add_sub_invalid(self, other, box_with_array): # GH#23215 rng = pd.period_range("1/1/2000", freq="D", periods=3) rng = tm.box_expected(rng, box_with_array) @@ -595,23 +602,6 @@ def test_parr_add_sub_datetime_scalar(self, other, box_with_array): # ----------------------------------------------------------------- # __add__/__sub__ with ndarray[datetime64] and ndarray[timedelta64] - def test_parr_add_sub_dt64_array_raises(self, box_with_array): - rng = pd.period_range("1/1/2000", freq="D", periods=3) - dti = pd.date_range("2016-01-01", periods=3) - dtarr = dti.values - - rng = tm.box_expected(rng, box_with_array) - - with pytest.raises(TypeError): - rng + dtarr - with pytest.raises(TypeError): - dtarr + rng - - with pytest.raises(TypeError): - rng - dtarr - with pytest.raises(TypeError): - dtarr - rng - def test_pi_add_sub_td64_array_non_tick_raises(self): rng = pd.period_range("1/1/2000", freq="Q", periods=3) tdi = pd.TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"]) diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 4f5e00bc5a37d..6af4ea18e63ca 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -18,6 +18,7 @@ Timestamp, timedelta_range, ) +from pandas.tests.arithmetic.test_datetime64 import assert_invalid_comparison import pandas.util.testing as tm @@ -61,42 +62,33 @@ def test_compare_timedelta64_zerodim(self, box_with_array): # zero-dim of wrong dtype should still raise tdi >= np.array(4) - -class TestTimedelta64ArrayComparisons: - # TODO: All of these need to be parametrized over box - - def test_compare_timedelta_series(self): + @pytest.mark.parametrize( + "td_scalar", + [timedelta(days=1), Timedelta(days=1), Timedelta(days=1).to_timedelta64()], + ) + def test_compare_timedeltalike_scalar(self, box_with_array, td_scalar): # regression test for GH#5963 - s = pd.Series([timedelta(days=1), timedelta(days=2)]) - actual = s > timedelta(days=1) + box = box_with_array + xbox = box if box is not pd.Index else np.ndarray + ser = pd.Series([timedelta(days=1), timedelta(days=2)]) + ser = tm.box_expected(ser, box) + actual = ser > td_scalar expected = pd.Series([False, True]) - tm.assert_series_equal(actual, expected) + expected = tm.box_expected(expected, xbox) + tm.assert_equal(actual, expected) - def test_tdi_cmp_str_invalid(self, box_with_array): - # GH#13624 - xbox = box_with_array if box_with_array is not pd.Index else np.ndarray - tdi = TimedeltaIndex(["1 day", "2 days"]) - tdarr = tm.box_expected(tdi, box_with_array) + @pytest.mark.parametrize("invalid", [345600000000000, "a"]) + def test_td64_comparisons_invalid(self, box_with_array, invalid): + # GH#13624 for str + box = box_with_array + rng = timedelta_range("1 days", periods=10) + obj = tm.box_expected(rng, box) - for left, right in [(tdarr, "a"), ("a", tdarr)]: - with pytest.raises(TypeError): - left > right - with pytest.raises(TypeError): - left >= right - with pytest.raises(TypeError): - left < right - with pytest.raises(TypeError): - left <= right - - result = left == right - expected = np.array([False, False], dtype=bool) - expected = tm.box_expected(expected, xbox) - tm.assert_equal(result, expected) + assert_invalid_comparison(obj, invalid, box) - result = left != right - expected = np.array([True, True], dtype=bool) - expected = tm.box_expected(expected, xbox) - tm.assert_equal(result, expected) + +class TestTimedelta64ArrayComparisons: + # TODO: All of these need to be parametrized over box @pytest.mark.parametrize("dtype", [None, object]) def test_comp_nat(self, dtype): @@ -191,10 +183,6 @@ def test_comparisons_coverage(self): expected = np.array([True, True, True] + [False] * 7) tm.assert_numpy_array_equal(result, expected) - # raise TypeError for now - with pytest.raises(TypeError): - rng < rng[3].value - result = rng == list(rng) exp = rng == rng tm.assert_numpy_array_equal(result, exp) @@ -835,19 +823,10 @@ def test_timedelta64_ops_nat(self): # ------------------------------------------------------------- # Invalid Operations - def test_td64arr_add_str_invalid(self, box_with_array): - # GH#13624 + @pytest.mark.parametrize("other", ["a", 3.14, np.array([2.0, 3.0])]) + def test_td64arr_add_sub_invalid(self, box_with_array, other): + # GH#13624 for str tdi = TimedeltaIndex(["1 day", "2 days"]) - tdi = tm.box_expected(tdi, box_with_array) - - with pytest.raises(TypeError): - tdi + "a" - with pytest.raises(TypeError): - "a" + tdi - - @pytest.mark.parametrize("other", [3.14, np.array([2.0, 3.0])]) - def test_td64arr_add_sub_float(self, box_with_array, other): - tdi = TimedeltaIndex(["-1 days", "-1 days"]) tdarr = tm.box_expected(tdi, box_with_array) with pytest.raises(TypeError): diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 401fc285424fe..652dd34ca7ce2 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -1047,3 +1047,23 @@ def test_to_numpy_alias(self): # GH 24653: alias .to_numpy() for scalars ts = Timestamp(datetime.now()) assert ts.to_datetime64() == ts.to_numpy() + + +class SubDatetime(datetime): + pass + + +@pytest.mark.parametrize( + "lh,rh", + [ + (SubDatetime(2000, 1, 1), Timedelta(hours=1)), + (Timedelta(hours=1), SubDatetime(2000, 1, 1)), + ], +) +def test_dt_subclass_add_timedelta(lh, rh): + # GH#25851 + # ensure that subclassed datetime works for + # Timedelta operations + result = lh + rh + expected = SubDatetime(2000, 1, 1, 1) + assert result == expected
https://api.github.com/repos/pandas-dev/pandas/pulls/27847
2019-08-09T21:19:09Z
2019-08-15T12:39:57Z
2019-08-15T12:39:57Z
2019-08-15T14:20:52Z
BUG: boxplot does not work when data has datetime column
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 974d14a4b424c..b35f230100f8d 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -165,6 +165,7 @@ Plotting - Bug in :meth:`Series.plot` not able to plot boolean values (:issue:`23719`) - +- Bug in :meth:`DataFrame.plot` when ``kind='box'`` and data contains datetime or timedelta data. These types are now automatically dropped (:issue:`22799`) Groupby/resample/rolling ^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 50f0d16631a15..a262f89dcc79c 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -402,12 +402,20 @@ def _compute_plot_data(self): # GH16953, _convert is needed as fallback, for ``Series`` # with ``dtype == object`` data = data._convert(datetime=True, timedelta=True) - select_include_type = [np.number, "datetime", "datetimetz", "timedelta"] + 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) + include_type.append(np.bool_) + + # GH22799, exclude datatime-like type for boxplot + exclude_type = None + if self._kind == "box": + # TODO: change after solving issue 27881 + include_type = [np.number] + exclude_type = ["timedelta"] + + numeric_data = data.select_dtypes(include=include_type, exclude=exclude_type) try: is_empty = numeric_data.empty diff --git a/pandas/tests/plotting/test_boxplot_method.py b/pandas/tests/plotting/test_boxplot_method.py index cab0efe53f1fc..5bbaff580c356 100644 --- a/pandas/tests/plotting/test_boxplot_method.py +++ b/pandas/tests/plotting/test_boxplot_method.py @@ -9,7 +9,7 @@ import pandas.util._test_decorators as td -from pandas import DataFrame, MultiIndex, Series +from pandas import DataFrame, MultiIndex, Series, date_range, timedelta_range from pandas.tests.plotting.common import TestPlotBase, _check_plot_works import pandas.util.testing as tm @@ -160,6 +160,21 @@ def test_fontsize(self): df.boxplot("a", fontsize=16), xlabelsize=16, ylabelsize=16 ) + def test_boxplot_numeric_data(self): + # GH 22799 + df = DataFrame( + { + "a": date_range("2012-01-01", periods=100), + "b": np.random.randn(100), + "c": np.random.randn(100) + 2, + "d": date_range("2012-01-01", periods=100).astype(str), + "e": date_range("2012-01-01", periods=100, tz="UTC"), + "f": timedelta_range("1 days", periods=100), + } + ) + ax = df.plot(kind="box") + assert [x.get_text() for x in ax.get_xticklabels()] == ["b", "c"] + @td.skip_if_no_mpl class TestDataFrameGroupByPlots(TestPlotBase):
- [ ] closes #22799 - [ ] 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/27846
2019-08-09T19:19:08Z
2019-08-13T12:44:11Z
2019-08-13T12:44:10Z
2019-08-13T12:44:11Z
CI: pytest, xdist versions
diff --git a/ci/deps/azure-37-locale.yaml b/ci/deps/azure-37-locale.yaml index 05adbf0c924dc..26dcd213bbfa0 100644 --- a/ci/deps/azure-37-locale.yaml +++ b/ci/deps/azure-37-locale.yaml @@ -26,8 +26,8 @@ dependencies: - xlsxwriter - xlwt # universal - - pytest>=4.0.2 - - pytest-xdist + - pytest>=5.0.1 + - pytest-xdist>=1.29.0 - pytest-mock - pytest-azurepipelines - pip diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml index 5cf897c98da10..65c92ec1dcf0d 100644 --- a/ci/deps/azure-37-numpydev.yaml +++ b/ci/deps/azure-37-numpydev.yaml @@ -6,7 +6,8 @@ dependencies: - pytz - Cython>=0.28.2 # universal - - pytest>=4.0.2 + # pytest < 5 until defaults has pytest-xdist>=1.29.0 + - pytest>=4.0.2,<5.0 - pytest-xdist - pytest-mock - hypothesis>=3.58.0 diff --git a/ci/deps/azure-macos-35.yaml b/ci/deps/azure-macos-35.yaml index 98859b596ab2a..cb2ac08cbf758 100644 --- a/ci/deps/azure-macos-35.yaml +++ b/ci/deps/azure-macos-35.yaml @@ -25,8 +25,8 @@ dependencies: - pip: - pyreadstat # universal - - pytest==4.5.0 - - pytest-xdist + - pytest>=5.0.1 + - pytest-xdist>=1.29.0 - pytest-mock - hypothesis>=3.58.0 # https://github.com/pandas-dev/pandas/issues/27421 diff --git a/ci/deps/azure-windows-36.yaml b/ci/deps/azure-windows-36.yaml index b0f3f5389ac85..ff9264a36cb12 100644 --- a/ci/deps/azure-windows-36.yaml +++ b/ci/deps/azure-windows-36.yaml @@ -23,8 +23,8 @@ dependencies: - xlwt # universal - cython>=0.28.2 - - pytest>=4.0.2 - - pytest-xdist + - pytest>=5.0.1 + - pytest-xdist>=1.29.0 - pytest-mock - pytest-azurepipelines - hypothesis>=3.58.0 diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml index 08208d1e2d59a..075234a937035 100644 --- a/ci/deps/azure-windows-37.yaml +++ b/ci/deps/azure-windows-37.yaml @@ -26,8 +26,8 @@ dependencies: - xlwt # universal - cython>=0.28.2 - - pytest>=4.0.2 - - pytest-xdist + - pytest>=5.0.0 + - pytest-xdist>=1.29.0 - pytest-mock - pytest-azurepipelines - hypothesis>=3.58.0 diff --git a/ci/deps/travis-36-cov.yaml b/ci/deps/travis-36-cov.yaml index a3f6d5b30f3e1..19002cbb8575e 100644 --- a/ci/deps/travis-36-cov.yaml +++ b/ci/deps/travis-36-cov.yaml @@ -39,8 +39,8 @@ dependencies: - xlsxwriter - xlwt # universal - - pytest - - pytest-xdist + - pytest>=5.0.1 + - pytest-xdist>=1.29.0 - pytest-cov - pytest-mock - hypothesis>=3.58.0 diff --git a/ci/deps/travis-37.yaml b/ci/deps/travis-37.yaml index c9a8c274fb144..9e08c41a3d9c0 100644 --- a/ci/deps/travis-37.yaml +++ b/ci/deps/travis-37.yaml @@ -13,8 +13,8 @@ dependencies: - pyarrow - pytz # universal - - pytest>=4.0.2 - - pytest-xdist + - pytest>=5.0.0 + - pytest-xdist>=1.29.0 - pytest-mock - hypothesis>=3.58.0 - s3fs
https://api.github.com/repos/pandas-dev/pandas/pulls/27845
2019-08-09T18:57:36Z
2019-08-12T02:29:48Z
2019-08-12T02:29:48Z
2019-08-21T21:09:15Z
DOC: GroupBy.head()/tail() documentation
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index c5e81e21e9fd5..d1da298412751 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -2326,8 +2326,9 @@ def head(self, n=5): """ Return first n rows of each group. - Essentially equivalent to ``.apply(lambda x: x.head(n))``, - except ignores as_index flag. + Similar to ``.apply(lambda x: x.head(n))``, but it returns a subset of rows + from the original DataFrame with original index and order preserved + (``as_index`` flag is ignored). Returns ------- @@ -2338,10 +2339,6 @@ def head(self, n=5): >>> df = pd.DataFrame([[1, 2], [1, 4], [5, 6]], ... columns=['A', 'B']) - >>> df.groupby('A', as_index=False).head(1) - A B - 0 1 2 - 2 5 6 >>> df.groupby('A').head(1) A B 0 1 2 @@ -2357,8 +2354,9 @@ def tail(self, n=5): """ Return last n rows of each group. - Essentially equivalent to ``.apply(lambda x: x.tail(n))``, - except ignores as_index flag. + Similar to ``.apply(lambda x: x.tail(n))``, but it returns a subset of rows + from the original DataFrame with original index and order preserved + (``as_index`` flag is ignored). Returns ------- @@ -2373,10 +2371,6 @@ def tail(self, n=5): A B 1 a 2 3 b 2 - >>> df.groupby('A').head(1) - A B - 0 a 1 - 2 b 1 """ self._reset_group_selection() mask = self._cumcount_array(ascending=False) < n
- [x] closes #6721 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Update DOC to make it consistent with actual behavior
https://api.github.com/repos/pandas-dev/pandas/pulls/27844
2019-08-09T18:57:21Z
2019-08-23T08:06:04Z
2019-08-23T08:06:04Z
2019-08-23T08:06:04Z
PERF: Break reference cycle for all Index types
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index dfa216b1db56e..21f1fa7ddec1f 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -83,7 +83,7 @@ Indexing ^^^^^^^^ - Bug in partial-string indexing returning a NumPy array rather than a ``Series`` when indexing with a scalar like ``.loc['2015']`` (:issue:`27516`) -- Break reference cycle involving :class:`Index` to allow garbage collection of :class:`Index` objects without running the GC. (:issue:`27585`) +- Break reference cycle involving :class:`Index` and other index classes to allow garbage collection of index objects without running the GC. (:issue:`27585`, :issue:`27840`) - Fix regression in assigning values to a single column of a DataFrame with a ``MultiIndex`` columns (:issue:`27841`). - diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 7272d4e2752be..d13e41eed7ad0 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -665,7 +665,7 @@ def _cleanup(self): def _engine(self): # property, for now, slow to look up - # to avoid a refernce cycle, bind `_ndarray_values` to a local variable, so + # to avoid a reference cycle, bind `_ndarray_values` to a local variable, so # `self` is not passed into the lambda. _ndarray_values = self._ndarray_values return self._engine_type(lambda: _ndarray_values, len(self)) diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 8bfa7e8d20b4f..82806c7351db6 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -446,9 +446,11 @@ def argsort(self, *args, **kwargs): @cache_readonly def _engine(self): - - # we are going to look things up with the codes themselves - return self._engine_type(lambda: self.codes, len(self)) + # we are going to look things up with the codes themselves. + # To avoid a reference cycle, bind `codes` to a local variable, so + # `self` is not passed into the lambda. + codes = self.codes + return self._engine_type(lambda: codes, len(self)) # introspection @cache_readonly diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index b0cc386f7783d..5a2ca109597e8 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -1,5 +1,6 @@ from datetime import datetime, timedelta import warnings +import weakref import numpy as np @@ -441,7 +442,9 @@ def _formatter_func(self): @cache_readonly def _engine(self): - return self._engine_type(lambda: self, len(self)) + # To avoid a reference cycle, pass a weakref of self to _engine_type. + period = weakref.ref(self) + return self._engine_type(period, len(self)) @Appender(_index_shared_docs["contains"]) def __contains__(self, key): diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 9459069f0ea2d..0e74c87388682 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -1,3 +1,5 @@ +import gc + import numpy as np import pytest @@ -908,3 +910,10 @@ def test_is_unique(self): # multiple NA should not be unique index_na_dup = index_na.insert(0, np.nan) assert index_na_dup.is_unique is False + + def test_engine_reference_cycle(self): + # GH27585 + index = self.create_index() + nrefs_pre = len(gc.get_referrers(index)) + index._engine + assert len(gc.get_referrers(index)) == nrefs_pre diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index fe1eb96df1e97..d1ed79118d2fa 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1,6 +1,5 @@ from collections import defaultdict from datetime import datetime, timedelta -import gc from io import StringIO import math import operator @@ -2425,13 +2424,6 @@ def test_deprecated_contains(self): with tm.assert_produces_warning(FutureWarning): index.contains(1) - def test_engine_reference_cycle(self): - # https://github.com/pandas-dev/pandas/issues/27585 - index = pd.Index([1, 2, 3]) - nrefs_pre = len(gc.get_referrers(index)) - index._engine - assert len(gc.get_referrers(index)) == nrefs_pre - class TestMixedIntIndex(Base): # Mostly the tests from common.py for which the results differ
- [x] xref #27585 & #27607 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Generalizes the test in #27607 to be used for all index types. This finds ref cycle issues for ``PeriodIndex`` and ``CategoricalIndex`` which are solved in this PR.
https://api.github.com/repos/pandas-dev/pandas/pulls/27840
2019-08-09T10:11:28Z
2019-08-14T20:11:35Z
2019-08-14T20:11:35Z
2019-08-14T21:52:31Z
Parametrize JSON tests
diff --git a/pandas/tests/io/json/conftest.py b/pandas/tests/io/json/conftest.py new file mode 100644 index 0000000000000..4e848cd48b42d --- /dev/null +++ b/pandas/tests/io/json/conftest.py @@ -0,0 +1,9 @@ +import pytest + + +@pytest.fixture(params=["split", "records", "index", "columns", "values"]) +def orient(request): + """ + Fixture for orients excluding the table format. + """ + return request.param diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 9842a706f43d7..2ef8244f488ae 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -7,16 +7,14 @@ import numpy as np import pytest -from pandas.compat import is_platform_32bit +from pandas.compat import PY35, is_platform_32bit import pandas.util._test_decorators as td import pandas as pd from pandas import DataFrame, DatetimeIndex, Series, Timestamp, read_json import pandas.util.testing as tm from pandas.util.testing import ( - assert_almost_equal, assert_frame_equal, - assert_index_equal, assert_series_equal, ensure_clean, network, @@ -82,76 +80,79 @@ def setup(self, datapath): del self.tsframe del self.mixed_frame - def test_frame_double_encoded_labels(self): + def test_frame_double_encoded_labels(self, orient): df = DataFrame( [["a", "b"], ["c", "d"]], index=['index " 1', "index / 2"], columns=["a \\ b", "y / z"], ) - assert_frame_equal(df, read_json(df.to_json(orient="split"), orient="split")) - assert_frame_equal( - df, read_json(df.to_json(orient="columns"), orient="columns") - ) - assert_frame_equal(df, read_json(df.to_json(orient="index"), orient="index")) - df_unser = read_json(df.to_json(orient="records"), orient="records") - assert_index_equal(df.columns, df_unser.columns) - tm.assert_numpy_array_equal(df.values, df_unser.values) - - def test_frame_non_unique_index(self): - df = DataFrame([["a", "b"], ["c", "d"]], index=[1, 1], columns=["x", "y"]) - - msg = "DataFrame index must be unique for orient='index'" - with pytest.raises(ValueError, match=msg): - df.to_json(orient="index") - msg = "DataFrame index must be unique for orient='columns'" - with pytest.raises(ValueError, match=msg): - df.to_json(orient="columns") + result = read_json(df.to_json(orient=orient), orient=orient) + expected = df.copy() - assert_frame_equal(df, read_json(df.to_json(orient="split"), orient="split")) - unser = read_json(df.to_json(orient="records"), orient="records") - tm.assert_index_equal(df.columns, unser.columns) - tm.assert_almost_equal(df.values, unser.values) - unser = read_json(df.to_json(orient="values"), orient="values") - tm.assert_numpy_array_equal(df.values, unser.values) + if orient == "records" or orient == "values": + expected = expected.reset_index(drop=True) + if orient == "values": + expected.columns = range(len(expected.columns)) - def test_frame_non_unique_columns(self): - df = DataFrame([["a", "b"], ["c", "d"]], index=[1, 2], columns=["x", "x"]) + assert_frame_equal(result, expected) - msg = "DataFrame columns must be unique for orient='index'" - with pytest.raises(ValueError, match=msg): - df.to_json(orient="index") - msg = "DataFrame columns must be unique for orient='columns'" - with pytest.raises(ValueError, match=msg): - df.to_json(orient="columns") - msg = "DataFrame columns must be unique for orient='records'" - with pytest.raises(ValueError, match=msg): - df.to_json(orient="records") + @pytest.mark.parametrize("orient", ["split", "records", "values"]) + def test_frame_non_unique_index(self, orient): + df = DataFrame([["a", "b"], ["c", "d"]], index=[1, 1], columns=["x", "y"]) + result = read_json(df.to_json(orient=orient), orient=orient) + expected = df.copy() - assert_frame_equal( - df, read_json(df.to_json(orient="split"), orient="split", dtype=False) - ) - unser = read_json(df.to_json(orient="values"), orient="values") - tm.assert_numpy_array_equal(df.values, unser.values) + if orient == "records" or orient == "values": + expected = expected.reset_index(drop=True) + if orient == "values": + expected.columns = range(len(expected.columns)) - # GH4377; duplicate columns not processing correctly - df = DataFrame([["a", "b"], ["c", "d"]], index=[1, 2], columns=["x", "y"]) - result = read_json(df.to_json(orient="split"), orient="split") - assert_frame_equal(result, df) + assert_frame_equal(result, expected) - def _check(df): - result = read_json( - df.to_json(orient="split"), orient="split", convert_dates=["x"] - ) - assert_frame_equal(result, df) + @pytest.mark.parametrize("orient", ["index", "columns"]) + def test_frame_non_unique_index_raises(self, orient): + df = DataFrame([["a", "b"], ["c", "d"]], index=[1, 1], columns=["x", "y"]) + msg = "DataFrame index must be unique for orient='{}'".format(orient) + with pytest.raises(ValueError, match=msg): + df.to_json(orient=orient) - for o in [ + @pytest.mark.parametrize("orient", ["split", "values"]) + @pytest.mark.parametrize( + "data", + [ [["a", "b"], ["c", "d"]], [[1.5, 2.5], [3.5, 4.5]], [[1, 2.5], [3, 4.5]], [[Timestamp("20130101"), 3.5], [Timestamp("20130102"), 4.5]], - ]: - _check(DataFrame(o, index=[1, 2], columns=["x", "x"])) + ], + ) + def test_frame_non_unique_columns(self, orient, data): + df = DataFrame(data, index=[1, 2], columns=["x", "x"]) + + result = read_json( + df.to_json(orient=orient), orient=orient, convert_dates=["x"] + ) + if orient == "values": + expected = pd.DataFrame(data) + if expected.iloc[:, 0].dtype == "datetime64[ns]": + # orient == "values" by default will write Timestamp objects out + # in milliseconds; these are internally stored in nanosecond, + # so divide to get where we need + # TODO: a to_epoch method would also solve; see GH 14772 + expected.iloc[:, 0] = expected.iloc[:, 0].astype(np.int64) // 1000000 + elif orient == "split": + expected = df + + assert_frame_equal(result, expected) + + @pytest.mark.parametrize("orient", ["index", "columns", "records"]) + def test_frame_non_unique_columns_raises(self, orient): + df = DataFrame([["a", "b"], ["c", "d"]], index=[1, 2], columns=["x", "x"]) + + msg = "DataFrame columns must be unique for orient='{}'".format(orient) + with pytest.raises(ValueError, match=msg): + df.to_json(orient=orient) def test_frame_from_json_to_json(self): def _check_orient( @@ -470,101 +471,93 @@ def _check_all_orients( # force everything to have object dtype beforehand _check_orient(df.transpose().transpose(), "index", dtype=False) - def test_frame_from_json_bad_data(self): - with pytest.raises(ValueError, match="Expected object or value"): - read_json(StringIO('{"key":b:a:d}')) - - # too few indices - json = StringIO( - '{"columns":["A","B"],' - '"index":["2","3"],' - '"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}' - ) - msg = r"Shape of passed values is \(3, 2\), indices imply \(2, 2\)" + @pytest.mark.parametrize( + "data,msg,orient", + [ + ('{"key":b:a:d}', "Expected object or value", "columns"), + # too few indices + ( + '{"columns":["A","B"],' + '"index":["2","3"],' + '"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}', + r"Shape of passed values is \(3, 2\), indices imply \(2, 2\)", + "split", + ), + # too many columns + ( + '{"columns":["A","B","C"],' + '"index":["1","2","3"],' + '"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}', + "3 columns passed, passed data had 2 columns", + "split", + ), + # bad key + ( + '{"badkey":["A","B"],' + '"index":["2","3"],' + '"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}', + r"unexpected key\(s\): badkey", + "split", + ), + ], + ) + def test_frame_from_json_bad_data_raises(self, data, msg, orient): with pytest.raises(ValueError, match=msg): - read_json(json, orient="split") + read_json(StringIO(data), orient=orient) - # too many columns - json = StringIO( - '{"columns":["A","B","C"],' - '"index":["1","2","3"],' - '"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}' + @pytest.mark.parametrize("dtype", [True, False]) + @pytest.mark.parametrize("convert_axes", [True, False]) + @pytest.mark.parametrize("numpy", [True, False]) + def test_frame_from_json_missing_data(self, orient, convert_axes, numpy, dtype): + num_df = DataFrame([[1, 2], [4, 5, 6]]) + result = read_json( + num_df.to_json(orient=orient), + orient=orient, + convert_axes=convert_axes, + dtype=dtype, ) - msg = "3 columns passed, passed data had 2 columns" - with pytest.raises(ValueError, match=msg): - read_json(json, orient="split") + assert np.isnan(result.iloc[0, 2]) - # bad key - json = StringIO( - '{"badkey":["A","B"],' - '"index":["2","3"],' - '"data":[[1.0,"1"],[2.0,"2"],[null,"3"]]}' + obj_df = DataFrame([["1", "2"], ["4", "5", "6"]]) + result = read_json( + obj_df.to_json(orient=orient), + orient=orient, + convert_axes=convert_axes, + dtype=dtype, ) - with pytest.raises(ValueError, match=r"unexpected key\(s\): badkey"): - read_json(json, orient="split") - - def test_frame_from_json_nones(self): - df = DataFrame([[1, 2], [4, 5, 6]]) - unser = read_json(df.to_json()) - assert np.isnan(unser[2][0]) - - df = DataFrame([["1", "2"], ["4", "5", "6"]]) - unser = read_json(df.to_json()) - assert np.isnan(unser[2][0]) - unser = read_json(df.to_json(), dtype=False) - assert unser[2][0] is None - unser = read_json(df.to_json(), convert_axes=False, dtype=False) - assert unser["2"]["0"] is None - - unser = read_json(df.to_json(), numpy=False) - assert np.isnan(unser[2][0]) - unser = read_json(df.to_json(), numpy=False, dtype=False) - assert unser[2][0] is None - unser = read_json(df.to_json(), numpy=False, convert_axes=False, dtype=False) - assert unser["2"]["0"] is None + if not dtype: # TODO: Special case for object data; maybe a bug? + assert result.iloc[0, 2] is None + else: + assert np.isnan(result.iloc[0, 2]) + @pytest.mark.parametrize("inf", [np.inf, np.NINF]) + @pytest.mark.parametrize("dtype", [True, False]) + def test_frame_infinity(self, orient, inf, dtype): # infinities get mapped to nulls which get mapped to NaNs during # deserialisation df = DataFrame([[1, 2], [4, 5, 6]]) - df.loc[0, 2] = np.inf - unser = read_json(df.to_json()) - assert np.isnan(unser[2][0]) - unser = read_json(df.to_json(), dtype=False) - assert np.isnan(unser[2][0]) - - df.loc[0, 2] = np.NINF - unser = read_json(df.to_json()) - assert np.isnan(unser[2][0]) - unser = read_json(df.to_json(), dtype=False) - assert np.isnan(unser[2][0]) + df.loc[0, 2] = inf + result = read_json(df.to_json(), dtype=dtype) + assert np.isnan(result.iloc[0, 2]) @pytest.mark.skipif( is_platform_32bit(), reason="not compliant on 32-bit, xref #15865" ) - def test_frame_to_json_float_precision(self): - df = pd.DataFrame([dict(a_float=0.95)]) - encoded = df.to_json(double_precision=1) - assert encoded == '{"a_float":{"0":1.0}}' - - df = pd.DataFrame([dict(a_float=1.95)]) - encoded = df.to_json(double_precision=1) - assert encoded == '{"a_float":{"0":2.0}}' - - df = pd.DataFrame([dict(a_float=-1.95)]) - encoded = df.to_json(double_precision=1) - assert encoded == '{"a_float":{"0":-2.0}}' - - df = pd.DataFrame([dict(a_float=0.995)]) - encoded = df.to_json(double_precision=2) - assert encoded == '{"a_float":{"0":1.0}}' - - df = pd.DataFrame([dict(a_float=0.9995)]) - encoded = df.to_json(double_precision=3) - assert encoded == '{"a_float":{"0":1.0}}' - - df = pd.DataFrame([dict(a_float=0.99999999999999944)]) - encoded = df.to_json(double_precision=15) - assert encoded == '{"a_float":{"0":1.0}}' + @pytest.mark.parametrize( + "value,precision,expected_val", + [ + (0.95, 1, 1.0), + (1.95, 1, 2.0), + (-1.95, 1, -2.0), + (0.995, 2, 1.0), + (0.9995, 3, 1.0), + (0.99999999999999944, 15, 1.0), + ], + ) + def test_frame_to_json_float_precision(self, value, precision, expected_val): + df = pd.DataFrame([dict(a_float=value)]) + encoded = df.to_json(double_precision=precision) + assert encoded == '{{"a_float":{{"0":{}}}}}'.format(expected_val) def test_frame_to_json_except(self): df = DataFrame([1, 2, 3]) @@ -799,107 +792,92 @@ def test_series_non_unique_index(self): unser = read_json(s.to_json(orient="records"), orient="records", typ="series") tm.assert_numpy_array_equal(s.values, unser.values) - def test_series_from_json_to_json(self): - def _check_orient( - series, orient, dtype=None, numpy=False, check_index_type=True - ): - series = series.sort_index() - unser = read_json( - series.to_json(orient=orient), - typ="series", - orient=orient, - numpy=numpy, - dtype=dtype, - ) - unser = unser.sort_index() - if orient == "records" or orient == "values": - assert_almost_equal(series.values, unser.values) - else: - if orient == "split": - assert_series_equal( - series, unser, check_index_type=check_index_type - ) - else: - assert_series_equal( - series, - unser, - check_names=False, - check_index_type=check_index_type, - ) - - def _check_all_orients(series, dtype=None, check_index_type=True): - _check_orient( - series, "columns", dtype=dtype, check_index_type=check_index_type - ) - _check_orient( - series, "records", dtype=dtype, check_index_type=check_index_type - ) - _check_orient( - series, "split", dtype=dtype, check_index_type=check_index_type - ) - _check_orient( - series, "index", dtype=dtype, check_index_type=check_index_type - ) - _check_orient(series, "values", dtype=dtype) - - _check_orient( - series, - "columns", - dtype=dtype, - numpy=True, - check_index_type=check_index_type, - ) - _check_orient( - series, - "records", - dtype=dtype, - numpy=True, - check_index_type=check_index_type, - ) - _check_orient( - series, - "split", - dtype=dtype, - numpy=True, - check_index_type=check_index_type, - ) - _check_orient( - series, - "index", - dtype=dtype, - numpy=True, - check_index_type=check_index_type, - ) - _check_orient( - series, - "values", - dtype=dtype, - numpy=True, - check_index_type=check_index_type, - ) - - # basic - _check_all_orients(self.series) + def test_series_default_orient(self): assert self.series.to_json() == self.series.to_json(orient="index") - objSeries = Series( + @pytest.mark.parametrize("numpy", [True, False]) + def test_series_roundtrip_simple(self, orient, numpy): + data = self.series.to_json(orient=orient) + result = pd.read_json(data, typ="series", orient=orient, numpy=numpy) + expected = self.series.copy() + + if not numpy and PY35 and orient in ("index", "columns"): + expected = expected.sort_index() + if orient in ("values", "records"): + expected = expected.reset_index(drop=True) + if orient != "split": + expected.name = None + + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("dtype", [False, None]) + @pytest.mark.parametrize("numpy", [True, False]) + def test_series_roundtrip_object(self, orient, numpy, dtype): + # TODO: see why tm.makeObjectSeries provides back DTA + dtSeries = Series( [str(d) for d in self.objSeries], index=self.objSeries.index, name=self.objSeries.name, ) - _check_all_orients(objSeries, dtype=False) + data = dtSeries.to_json(orient=orient) + result = pd.read_json( + data, typ="series", orient=orient, numpy=numpy, dtype=dtype + ) + if dtype is False: + expected = dtSeries.copy() + else: + expected = self.objSeries.copy() + + if not numpy and PY35 and orient in ("index", "columns"): + expected = expected.sort_index() + if orient in ("values", "records"): + expected = expected.reset_index(drop=True) + if orient != "split": + expected.name = None + + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("numpy", [True, False]) + def test_series_roundtrip_empty(self, orient, numpy): + data = self.empty_series.to_json(orient=orient) + result = pd.read_json(data, typ="series", orient=orient, numpy=numpy) + expected = self.empty_series.copy() + + # TODO: see what causes inconsistency + if not numpy and PY35 and orient == "index": + expected = expected.sort_index() + if orient in ("values", "records"): + expected = expected.reset_index(drop=True) + else: + expected.index = expected.index.astype(float) + + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("numpy", [True, False]) + def test_series_roundtrip_timeseries(self, orient, numpy): + data = self.ts.to_json(orient=orient) + result = pd.read_json(data, typ="series", orient=orient, numpy=numpy) + expected = self.ts.copy() - # empty_series has empty index with object dtype - # which cannot be revert - assert self.empty_series.index.dtype == np.object_ - _check_all_orients(self.empty_series, check_index_type=False) + if orient in ("values", "records"): + expected = expected.reset_index(drop=True) + if orient != "split": + expected.name = None - _check_all_orients(self.ts) + tm.assert_series_equal(result, expected) - # dtype + @pytest.mark.parametrize("dtype", [np.float64, np.int]) + @pytest.mark.parametrize("numpy", [True, False]) + def test_series_roundtrip_numeric(self, orient, numpy, dtype): s = Series(range(6), index=["a", "b", "c", "d", "e", "f"]) - _check_all_orients(Series(s, dtype=np.float64), dtype=np.float64) - _check_all_orients(Series(s, dtype=np.int), dtype=np.int) + data = s.to_json(orient=orient) + result = pd.read_json(data, typ="series", orient=orient, numpy=numpy) + + expected = s.copy() + if orient in ("values", "records"): + expected = expected.reset_index(drop=True) + + tm.assert_series_equal(result, expected) def test_series_to_json_except(self): s = Series([1, 2, 3]) @@ -991,11 +969,9 @@ def test_convert_dates(self): result = read_json(json, typ="series") assert_series_equal(result, ts) - def test_convert_dates_infer(self): - # GH10747 - from pandas.io.json import dumps - - infer_words = [ + @pytest.mark.parametrize( + "infer_word", + [ "trade_time", "date", "datetime", @@ -1003,14 +979,18 @@ def test_convert_dates_infer(self): "modified", "timestamp", "timestamps", - ] - for infer_word in infer_words: - data = [{"id": 1, infer_word: 1036713600000}, {"id": 2}] - expected = DataFrame( - [[1, Timestamp("2002-11-08")], [2, pd.NaT]], columns=["id", infer_word] - ) - result = read_json(dumps(data))[["id", infer_word]] - assert_frame_equal(result, expected) + ], + ) + def test_convert_dates_infer(self, infer_word): + # GH10747 + from pandas.io.json import dumps + + data = [{"id": 1, infer_word: 1036713600000}, {"id": 2}] + expected = DataFrame( + [[1, Timestamp("2002-11-08")], [2, pd.NaT]], columns=["id", infer_word] + ) + result = read_json(dumps(data))[["id", infer_word]] + assert_frame_equal(result, expected) @pytest.mark.parametrize( "date,date_unit", @@ -1315,27 +1295,32 @@ def test_sparse(self): expected = s.to_json() assert expected == ss.to_json() - def test_tz_is_utc(self): + @pytest.mark.parametrize( + "ts", + [ + Timestamp("2013-01-10 05:00:00Z"), + Timestamp("2013-01-10 00:00:00", tz="US/Eastern"), + Timestamp("2013-01-10 00:00:00-0500"), + ], + ) + def test_tz_is_utc(self, ts): from pandas.io.json import dumps exp = '"2013-01-10T05:00:00.000Z"' - ts = Timestamp("2013-01-10 05:00:00Z") - assert dumps(ts, iso_dates=True) == exp - dt = ts.to_pydatetime() - assert dumps(dt, iso_dates=True) == exp - - ts = Timestamp("2013-01-10 00:00:00", tz="US/Eastern") assert dumps(ts, iso_dates=True) == exp dt = ts.to_pydatetime() assert dumps(dt, iso_dates=True) == exp - ts = Timestamp("2013-01-10 00:00:00-0500") - assert dumps(ts, iso_dates=True) == exp - dt = ts.to_pydatetime() - assert dumps(dt, iso_dates=True) == exp - - def test_tz_range_is_utc(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), + ], + ) + def test_tz_range_is_utc(self, tz_range): from pandas.io.json import dumps exp = '["2013-01-01T05:00:00.000Z","2013-01-02T05:00:00.000Z"]' @@ -1345,7 +1330,6 @@ def test_tz_range_is_utc(self): '"1":"2013-01-02T05:00:00.000Z"}}' ) - tz_range = pd.date_range("2013-01-01 05:00:00Z", periods=2) assert dumps(tz_range, iso_dates=True) == exp dti = pd.DatetimeIndex(tz_range) assert dumps(dti, iso_dates=True) == exp @@ -1353,20 +1337,6 @@ def test_tz_range_is_utc(self): result = dumps(df, iso_dates=True) assert result == dfexp - tz_range = pd.date_range("2013-01-01 00:00:00", periods=2, tz="US/Eastern") - assert dumps(tz_range, iso_dates=True) == exp - dti = pd.DatetimeIndex(tz_range) - assert dumps(dti, iso_dates=True) == exp - df = DataFrame({"DT": dti}) - assert dumps(df, iso_dates=True) == dfexp - - tz_range = pd.date_range("2013-01-01 00:00:00-0500", periods=2) - assert dumps(tz_range, iso_dates=True) == exp - dti = pd.DatetimeIndex(tz_range) - assert dumps(dti, iso_dates=True) == exp - df = DataFrame({"DT": dti}) - assert dumps(df, iso_dates=True) == dfexp - def test_read_inline_jsonl(self): # GH9180 result = read_json('{"a": 1, "b": 2}\n{"b":2, "a" :1}\n', lines=True) @@ -1458,14 +1428,10 @@ def test_latin_encoding(self): [b"A\xf8\xfc", np.nan, b"", b"b", b"c"], ] - def _try_decode(x, encoding="latin-1"): - try: - return x.decode(encoding) - except AttributeError: - return x - - # not sure how to remove latin-1 from code in python 2 and 3 - values = [[_try_decode(x) for x in y] for y in values] + values = [ + [x.decode("latin-1") if isinstance(x, bytes) else x for x in y] + for y in values + ] examples = [] for dtype in ["category", object]:
lot more to be done here but split these up as some of the large functions are difficult to highlight failures while working on extension module. Improved coverage and identified some inconsistencies in process (marked with TODOs) which can be tackled as follow ups
https://api.github.com/repos/pandas-dev/pandas/pulls/27838
2019-08-09T08:56:09Z
2019-09-17T21:49:45Z
2019-09-17T21:49:45Z
2020-01-16T00:33:52Z
Backport PR #27818 on branch 0.25.x (COMPAT: restore shape for 'invalid' Index with nd array)
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index f1d3f152e503d..d48a003d56e4f 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -111,7 +111,7 @@ Plotting ^^^^^^^^ - Added a pandas_plotting_backends entrypoint group for registering plot backends. See :ref:`extending.plotting-backends` for more (:issue:`26747`). -- +- Fix compatibility issue with matplotlib when passing a pandas ``Index`` to a plot call (:issue:`27775`). - Groupby/resample/rolling diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 17122d0981995..1d70232d08c94 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -5648,7 +5648,10 @@ def shape(self): """ Return a tuple of the shape of the underlying data. """ - return (len(self),) + # not using "(len(self), )" to return "correct" shape if the values + # consists of a >1 D array (see GH-27775) + # overridden in MultiIndex.shape to avoid materializing the values + return self._values.shape Index._add_numeric_methods_disabled() diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index b673c119c0498..1acaa4ef5ecdc 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -616,6 +616,15 @@ def _values(self): # We override here, since our parent uses _data, which we dont' use. return self.values + @property + def shape(self): + """ + Return a tuple of the shape of the underlying data. + """ + # overriding the base Index.shape definition to avoid materializing + # the values (GH-27384, GH-27775) + return (len(self),) + @property def array(self): """ diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index c40a9bce9385b..d1ed79118d2fa 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2805,3 +2805,17 @@ def test_deprecated_fastpath(): expected = pd.CategoricalIndex(["a", "b", "c"], name="test") tm.assert_index_equal(idx, expected) + + +def test_shape_of_invalid_index(): + # Currently, it is possible to create "invalid" index objects backed by + # a multi-dimensional array (see https://github.com/pandas-dev/pandas/issues/27125 + # about this). However, as long as this is not solved in general,this test ensures + # that the returned shape is consistent with this underlying array for + # compat with matplotlib (see https://github.com/pandas-dev/pandas/issues/27775) + a = np.arange(8).reshape(2, 2, 2) + idx = pd.Index(a) + assert idx.shape == a.shape + + idx = pd.Index([0, 1, 2, 3]) + assert idx[:, None].shape == (4, 1)
Backport PR #27818: COMPAT: restore shape for 'invalid' Index with nd array
https://api.github.com/repos/pandas-dev/pandas/pulls/27836
2019-08-09T07:37:36Z
2019-08-09T08:20:19Z
2019-08-09T08:20:19Z
2019-08-09T08:20:19Z
DOC: Add examples to Series.str.slice() with negative arguments GH27802
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 169a3a24c254d..8901da19082c2 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -1454,6 +1454,36 @@ def str_slice(arr, start=None, stop=None, step=None): 2 caeen dtype: object + Negative values can be used for any of the three parameters. For start or stop, a + value of -1 will be the last character of the string, -2 the second to last, and + so on. Examples: + + >>> s.str.slice(start=-3) + 0 ala + 1 fox + 2 eon + dtype: object + + >>> s.str.slice(stop=-2) + 0 koa + 1 f + 2 chamele + dtype: object + + A negative value for step will simply step in the other direction. + + >>> s.str.slice(step=-1) + 0 alaok + 1 xof + 2 noelemahc + dtype: object + + >>> s.str.slice(stop=1, step=-1) + 0 ala + 1 x + 2 noelema + dtype: object + >>> s.str.slice(start=0, stop=5, step=3) 0 kl 1 f
- [x] closes #27802 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [N/A] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/27834
2019-08-09T04:29:56Z
2019-08-09T17:07:40Z
null
2019-08-09T17:07:40Z
Update sample() documentation
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c38489c7b85ef..5a1b2a5dcd20b 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4786,7 +4786,7 @@ def sample( frac : float, optional Fraction of axis items to return. Cannot be used with `n`. replace : bool, default False - Sample with or without replacement. + Allow or disallow sampling of the same row more than once. weights : str or ndarray-like, optional Default 'None' results in equal probability weighting. If passed a Series, will align with target object on index. Index
Clarify the definition of replace parameter - [ ] 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/27833
2019-08-09T04:13:16Z
2019-08-09T12:33:49Z
2019-08-09T12:33:49Z
2019-08-09T13:16:22Z
Add example for Series.str.slice()
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 169a3a24c254d..25350119f9df5 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -1442,6 +1442,12 @@ def str_slice(arr, start=None, stop=None, step=None): 2 hameleon dtype: object + >>> s.str.slice(start=-1) + 0 a + 1 x + 2 n + dtype: object + >>> s.str.slice(stop=2) 0 ko 1 fo
Add example to show that negative values for start are allowed for Series.str.slice(). - [ X] closes #27802 - [ ] 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/27832
2019-08-09T03:26:12Z
2019-08-09T12:55:23Z
2019-08-09T12:55:23Z
2019-08-09T13:16:10Z
CLN: match standardized dispatch logic in IntegerArray
diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 1f14bd169a228..069d661e6af34 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -21,7 +21,7 @@ is_scalar, ) from pandas.core.dtypes.dtypes import register_extension_dtype -from pandas.core.dtypes.generic import ABCIndexClass, ABCSeries +from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass, ABCSeries from pandas.core.dtypes.missing import isna, notna from pandas.core import nanops, ops @@ -592,25 +592,29 @@ def _values_for_argsort(self) -> np.ndarray: @classmethod def _create_comparison_method(cls, op): - def cmp_method(self, other): + op_name = op.__name__ - op_name = op.__name__ - mask = None + def cmp_method(self, other): - if isinstance(other, (ABCSeries, ABCIndexClass)): + if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)): # Rely on pandas to unbox and dispatch to us. return NotImplemented + other = lib.item_from_zerodim(other) + mask = None + if isinstance(other, IntegerArray): other, mask = other._data, other._mask elif is_list_like(other): other = np.asarray(other) - if other.ndim > 0 and len(self) != len(other): + if other.ndim > 1: + raise NotImplementedError( + "can only perform ops with 1-d structures" + ) + if len(self) != len(other): raise ValueError("Lengths must match to compare") - other = lib.item_from_zerodim(other) - # numpy will show a DeprecationWarning on invalid elementwise # comparisons, this will raise in the future with warnings.catch_warnings(): @@ -683,31 +687,31 @@ def _maybe_mask_result(self, result, mask, other, op_name): @classmethod def _create_arithmetic_method(cls, op): - def integer_arithmetic_method(self, other): + op_name = op.__name__ - op_name = op.__name__ - mask = None + def integer_arithmetic_method(self, other): - if isinstance(other, (ABCSeries, ABCIndexClass)): + if isinstance(other, (ABCDataFrame, ABCSeries, ABCIndexClass)): # Rely on pandas to unbox and dispatch to us. return NotImplemented - if getattr(other, "ndim", 0) > 1: - raise NotImplementedError("can only perform ops with 1-d structures") + other = lib.item_from_zerodim(other) + mask = None if isinstance(other, IntegerArray): other, mask = other._data, other._mask - elif getattr(other, "ndim", None) == 0: - other = other.item() - elif is_list_like(other): other = np.asarray(other) - if not other.ndim: - other = other.item() - elif other.ndim == 1: - if not (is_float_dtype(other) or is_integer_dtype(other)): - raise TypeError("can only perform ops with numeric values") + if other.ndim > 1: + raise NotImplementedError( + "can only perform ops with 1-d structures" + ) + if len(self) != len(other): + raise ValueError("Lengths must match") + if not (is_float_dtype(other) or is_integer_dtype(other)): + raise TypeError("can only perform ops with numeric values") + else: if not (is_float(other) or is_integer(other)): raise TypeError("can only perform ops with numeric values") diff --git a/pandas/tests/arrays/test_integer.py b/pandas/tests/arrays/test_integer.py index 50cd1469e5196..31a9a0483081e 100644 --- a/pandas/tests/arrays/test_integer.py +++ b/pandas/tests/arrays/test_integer.py @@ -280,7 +280,7 @@ def test_arith_coerce_scalar(self, data, all_arithmetic_operators): other = 0.01 self._check_op(s, op, other) - @pytest.mark.parametrize("other", [1.0, 1.0, np.array(1.0), np.array([1.0])]) + @pytest.mark.parametrize("other", [1.0, np.array(1.0)]) def test_arithmetic_conversion(self, all_arithmetic_operators, other): # if we have a float operand we should have a float result # if that is equal to an integer @@ -290,6 +290,15 @@ def test_arithmetic_conversion(self, all_arithmetic_operators, other): result = op(s, other) assert result.dtype is np.dtype("float") + def test_arith_len_mismatch(self, all_arithmetic_operators): + # operating with a list-like with non-matching length raises + op = self.get_op_from_name(all_arithmetic_operators) + other = np.array([1.0]) + + s = pd.Series([1, 2, 3], dtype="Int64") + with pytest.raises(ValueError, match="Lengths must match"): + op(s, other) + @pytest.mark.parametrize("other", [0, 0.5]) def test_arith_zero_dim_ndarray(self, other): arr = integer_array([1, None, 2]) @@ -322,8 +331,9 @@ def test_error(self, data, all_arithmetic_operators): ops(pd.Series(pd.date_range("20180101", periods=len(s)))) # 2d - with pytest.raises(NotImplementedError): - opa(pd.DataFrame({"A": s})) + result = opa(pd.DataFrame({"A": s})) + assert result is NotImplemented + with pytest.raises(NotImplementedError): opa(np.arange(len(s)).reshape(-1, len(s)))
Actual logic changes: - return NotImplemented when operating with DataFrame (instead of raising NotImplementError) - raise ValueError when operating with mismatched-length listlike Everything else is just rearranging to use patterns that are more standard around the codebase, leading up to #23853
https://api.github.com/repos/pandas-dev/pandas/pulls/27830
2019-08-08T21:47:05Z
2019-08-13T12:13:17Z
2019-08-13T12:13:16Z
2019-08-13T13:59:35Z
Backport PR #27607 on branch 0.25.x (BUG: break reference cycle in Index._engine)
diff --git a/asv_bench/benchmarks/index_object.py b/asv_bench/benchmarks/index_object.py index 6541ddcb0397d..49834ae94cc38 100644 --- a/asv_bench/benchmarks/index_object.py +++ b/asv_bench/benchmarks/index_object.py @@ -1,3 +1,4 @@ +import gc import numpy as np import pandas.util.testing as tm from pandas import ( @@ -225,4 +226,21 @@ def time_intersection_both_duplicate(self, N): self.intv.intersection(self.intv2) +class GC: + params = [1, 2, 5] + + def create_use_drop(self): + idx = Index(list(range(1000 * 1000))) + idx._engine + + def peakmem_gc_instances(self, N): + try: + gc.disable() + + for _ in range(N): + self.create_use_drop() + finally: + gc.enable() + + from .pandas_vb_common import setup # noqa: F401 diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index f1d3f152e503d..443baa56374ca 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -83,6 +83,7 @@ Indexing ^^^^^^^^ - Bug in partial-string indexing returning a NumPy array rather than a ``Series`` when indexing with a scalar like ``.loc['2015']`` (:issue:`27516`) +- Break reference cycle involving :class:`Index` to allow garbage collection of :class:`Index` objects without running the GC. (:issue:`27585`) - - diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 17122d0981995..9297d02282a23 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -710,7 +710,11 @@ def _cleanup(self): @cache_readonly def _engine(self): # property, for now, slow to look up - return self._engine_type(lambda: self._ndarray_values, len(self)) + + # to avoid a refernce cycle, bind `_ndarray_values` to a local variable, so + # `self` is not passed into the lambda. + _ndarray_values = self._ndarray_values + return self._engine_type(lambda: _ndarray_values, len(self)) # -------------------------------------------------------------------- # Array-Like Methods diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index c40a9bce9385b..34d82525495fc 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1,5 +1,6 @@ from collections import defaultdict from datetime import datetime, timedelta +import gc from io import StringIO import math import operator @@ -2424,6 +2425,13 @@ def test_deprecated_contains(self): with tm.assert_produces_warning(FutureWarning): index.contains(1) + def test_engine_reference_cycle(self): + # https://github.com/pandas-dev/pandas/issues/27585 + index = pd.Index([1, 2, 3]) + nrefs_pre = len(gc.get_referrers(index)) + index._engine + assert len(gc.get_referrers(index)) == nrefs_pre + class TestMixedIntIndex(Base): # Mostly the tests from common.py for which the results differ
Backport PR #27607: BUG: break reference cycle in Index._engine
https://api.github.com/repos/pandas-dev/pandas/pulls/27828
2019-08-08T20:43:36Z
2019-08-09T20:24:13Z
2019-08-09T20:24:13Z
2019-08-09T20:24:18Z
BUG: Fixed groupby quantile for listlike q
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 94770a7aae676..4d385ef0ec166 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -117,6 +117,7 @@ Plotting Groupby/resample/rolling ^^^^^^^^^^^^^^^^^^^^^^^^ +- Fixed regression in :meth:`pands.core.groupby.DataFrameGroupBy.quantile` raising when multiple quantiles are given (:issue:`27526`) - Bug in :meth:`pandas.core.groupby.DataFrameGroupBy.transform` where applying a timezone conversion lambda function would drop timezone information (:issue:`27496`) - Bug in windowing over read-only arrays (:issue:`27766`) - Fixed segfault in `pandas.core.groupby.DataFrameGroupBy.quantile` when an invalid quantile was passed (:issue:`27470`) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index c5e81e21e9fd5..35c2dac3901a2 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1870,6 +1870,7 @@ def quantile(self, q=0.5, interpolation="linear"): a 2.0 b 3.0 """ + from pandas import concat def pre_processor(vals: np.ndarray) -> Tuple[np.ndarray, Optional[Type]]: if is_object_dtype(vals): @@ -1897,18 +1898,57 @@ def post_processor(vals: np.ndarray, inference: Optional[Type]) -> np.ndarray: return vals - return self._get_cythonized_result( - "group_quantile", - self.grouper, - aggregate=True, - needs_values=True, - needs_mask=True, - cython_dtype=np.float64, - pre_processing=pre_processor, - post_processing=post_processor, - q=q, - interpolation=interpolation, - ) + if is_scalar(q): + return self._get_cythonized_result( + "group_quantile", + self.grouper, + aggregate=True, + needs_values=True, + needs_mask=True, + cython_dtype=np.float64, + pre_processing=pre_processor, + post_processing=post_processor, + q=q, + interpolation=interpolation, + ) + else: + results = [ + self._get_cythonized_result( + "group_quantile", + self.grouper, + aggregate=True, + needs_values=True, + needs_mask=True, + cython_dtype=np.float64, + pre_processing=pre_processor, + post_processing=post_processor, + q=qi, + interpolation=interpolation, + ) + for qi in q + ] + result = concat(results, axis=0, keys=q) + # fix levels to place quantiles on the inside + # TODO(GH-10710): Ideally, we could write this as + # >>> result.stack(0).loc[pd.IndexSlice[:, ..., q], :] + # but this hits https://github.com/pandas-dev/pandas/issues/10710 + # which doesn't reorder the list-like `q` on the inner level. + order = np.roll(list(range(result.index.nlevels)), -1) + result = result.reorder_levels(order) + result = result.reindex(q, level=-1) + + # fix order. + hi = len(q) * self.ngroups + arr = np.arange(0, hi, self.ngroups) + arrays = [] + + for i in range(self.ngroups): + arr = arr + i + arrays.append(arr) + + indices = np.concatenate(arrays) + assert len(indices) == len(result) + return result.take(indices) @Substitution(name="groupby") def ngroup(self, ascending=True): diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 3794120281e1f..509d7c33b643b 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -1238,6 +1238,57 @@ def test_quantile(interpolation, a_vals, b_vals, q): tm.assert_frame_equal(result, expected) +def test_quantile_array(): + # https://github.com/pandas-dev/pandas/issues/27526 + df = pd.DataFrame({"A": [0, 1, 2, 3, 4]}) + result = df.groupby([0, 0, 1, 1, 1]).quantile([0.25]) + + index = pd.MultiIndex.from_product([[0, 1], [0.25]]) + expected = pd.DataFrame({"A": [0.25, 2.50]}, index=index) + tm.assert_frame_equal(result, expected) + + df = pd.DataFrame({"A": [0, 1, 2, 3], "B": [4, 5, 6, 7]}) + index = pd.MultiIndex.from_product([[0, 1], [0.25, 0.75]]) + + result = df.groupby([0, 0, 1, 1]).quantile([0.25, 0.75]) + expected = pd.DataFrame( + {"A": [0.25, 0.75, 2.25, 2.75], "B": [4.25, 4.75, 6.25, 6.75]}, index=index + ) + tm.assert_frame_equal(result, expected) + + +def test_quantile_array_no_sort(): + df = pd.DataFrame({"A": [0, 1, 2], "B": [3, 4, 5]}) + result = df.groupby([1, 0, 1], sort=False).quantile([0.25, 0.5, 0.75]) + expected = pd.DataFrame( + {"A": [0.5, 1.0, 1.5, 1.0, 1.0, 1.0], "B": [3.5, 4.0, 4.5, 4.0, 4.0, 4.0]}, + index=pd.MultiIndex.from_product([[1, 0], [0.25, 0.5, 0.75]]), + ) + tm.assert_frame_equal(result, expected) + + result = df.groupby([1, 0, 1], sort=False).quantile([0.75, 0.25]) + expected = pd.DataFrame( + {"A": [1.5, 0.5, 1.0, 1.0], "B": [4.5, 3.5, 4.0, 4.0]}, + index=pd.MultiIndex.from_product([[1, 0], [0.75, 0.25]]), + ) + tm.assert_frame_equal(result, expected) + + +def test_quantile_array_multiple_levels(): + df = pd.DataFrame( + {"A": [0, 1, 2], "B": [3, 4, 5], "c": ["a", "a", "a"], "d": ["a", "a", "b"]} + ) + result = df.groupby(["c", "d"]).quantile([0.25, 0.75]) + index = pd.MultiIndex.from_tuples( + [("a", "a", 0.25), ("a", "a", 0.75), ("a", "b", 0.25), ("a", "b", 0.75)], + names=["c", "d", None], + ) + expected = pd.DataFrame( + {"A": [0.25, 0.75, 2.0, 2.0], "B": [3.25, 3.75, 5.0, 5.0]}, index=index + ) + tm.assert_frame_equal(result, expected) + + def test_quantile_raises(): df = pd.DataFrame( [["foo", "a"], ["foo", "b"], ["foo", "c"]], columns=["key", "val"]
Closes #27526 Just a WIP right now. This is under tested for - [ ] `groupby(sort=False)` - [ ] non-sorted `q` - [ ] `groupby(multiple levels)`
https://api.github.com/repos/pandas-dev/pandas/pulls/27827
2019-08-08T20:36:24Z
2019-08-22T11:28:37Z
2019-08-22T11:28:37Z
2019-08-22T11:28:40Z
BUG: Fix groupby quantile segfault
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 637ac5c9c8bd1..7b39810a2cf49 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -120,7 +120,7 @@ Groupby/resample/rolling - Bug in :meth:`pandas.core.groupby.DataFrameGroupBy.transform` where applying a timezone conversion lambda function would drop timezone information (:issue:`27496`) - Bug in windowing over read-only arrays (:issue:`27766`) -- +- Fixed segfault in `pandas.core.groupby.DataFrameGroupBy.quantile` when an invalid quantile was passed (:issue:`27470`) - Reshaping diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index e3f18572abca1..3069bbbf34bb7 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -719,6 +719,11 @@ def group_quantile(ndarray[float64_t] out, ndarray[int64_t] counts, non_na_counts, sort_arr assert values.shape[0] == N + + if not (0 <= q <= 1): + raise ValueError("'q' must be between 0 and 1. Got" + " '{}' instead".format(q)) + inter_methods = { 'linear': INTERPOLATION_LINEAR, 'lower': INTERPOLATION_LOWER, diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index efc3142b25b82..3794120281e1f 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -1247,6 +1247,17 @@ def test_quantile_raises(): df.groupby("key").quantile() +def test_quantile_out_of_bounds_q_raises(): + # https://github.com/pandas-dev/pandas/issues/27470 + df = pd.DataFrame(dict(a=[0, 0, 0, 1, 1, 1], b=range(6))) + g = df.groupby([0, 0, 0, 1, 1, 1]) + with pytest.raises(ValueError, match="Got '50.0' instead"): + g.quantile(50) + + with pytest.raises(ValueError, match="Got '-1.0' instead"): + g.quantile(-1) + + # pipe # --------------------------------
Validate that q is between 0 and 1. Closes #27470
https://api.github.com/repos/pandas-dev/pandas/pulls/27826
2019-08-08T19:49:31Z
2019-08-12T17:56:47Z
2019-08-12T17:56:47Z
2019-10-31T01:19:37Z
Add tidelift sponsor to FUNDING
diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml index 6912d15abf3d6..944ce9b4fb1f6 100644 --- a/.github/FUNDING.yml +++ b/.github/FUNDING.yml @@ -1 +1,2 @@ custom: https://pandas.pydata.org/donate.html +tidelift: pypi/pandas
https://api.github.com/repos/pandas-dev/pandas/pulls/27823
2019-08-08T16:51:00Z
2019-08-09T14:19:03Z
2019-08-09T14:19:03Z
2019-08-09T14:19:06Z
Add security policy
diff --git a/.github/SECURITY.md b/.github/SECURITY.md new file mode 100644 index 0000000000000..f3b059a5d4f13 --- /dev/null +++ b/.github/SECURITY.md @@ -0,0 +1 @@ +To report a security vulnerability to pandas, please go to https://tidelift.com/security and see the instructions there.
Closes #27821
https://api.github.com/repos/pandas-dev/pandas/pulls/27822
2019-08-08T16:50:46Z
2019-08-09T14:18:54Z
2019-08-09T14:18:54Z
2019-08-09T14:19:09Z
Backport PR #27809 on branch 0.25.x (CI: remove pytest pins)
diff --git a/ci/deps/azure-36-locale.yaml b/ci/deps/azure-36-locale.yaml index 8f8273f57c3fe..6a77b5dbedc61 100644 --- a/ci/deps/azure-36-locale.yaml +++ b/ci/deps/azure-36-locale.yaml @@ -20,8 +20,8 @@ dependencies: - xlsxwriter=0.9.8 - xlwt=1.2.0 # universal - - pytest>=4.0.2,<5.0.0 - - pytest-xdist + - pytest>=5.0.0 + - pytest-xdist>=1.29.0 - pytest-mock - pytest-azurepipelines - hypothesis>=3.58.0 diff --git a/ci/deps/travis-36-slow.yaml b/ci/deps/travis-36-slow.yaml index 538a82f66e4c8..9564bf5bb3a9f 100644 --- a/ci/deps/travis-36-slow.yaml +++ b/ci/deps/travis-36-slow.yaml @@ -25,8 +25,8 @@ dependencies: - xlsxwriter - xlwt # universal - - pytest>=4.0.2,<5.0.0 - - pytest-xdist + - pytest>=5.0.0 + - pytest-xdist>=1.29.0 - pytest-mock - moto - hypothesis>=3.58.0
Backport PR #27809: CI: remove pytest pins
https://api.github.com/repos/pandas-dev/pandas/pulls/27819
2019-08-08T11:00:57Z
2019-08-08T12:13:54Z
2019-08-08T12:13:54Z
2019-08-08T12:13:54Z
COMPAT: restore shape for 'invalid' Index with nd array
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index f1d3f152e503d..d48a003d56e4f 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -111,7 +111,7 @@ Plotting ^^^^^^^^ - Added a pandas_plotting_backends entrypoint group for registering plot backends. See :ref:`extending.plotting-backends` for more (:issue:`26747`). -- +- Fix compatibility issue with matplotlib when passing a pandas ``Index`` to a plot call (:issue:`27775`). - Groupby/resample/rolling diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 356ae20b2240a..2ed9b91f9426d 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -5600,7 +5600,10 @@ def shape(self): """ Return a tuple of the shape of the underlying data. """ - return (len(self),) + # not using "(len(self), )" to return "correct" shape if the values + # consists of a >1 D array (see GH-27775) + # overridden in MultiIndex.shape to avoid materializing the values + return self._values.shape Index._add_numeric_methods_disabled() diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 488107690fbd6..b614952ba1e04 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -622,6 +622,15 @@ def _values(self): # We override here, since our parent uses _data, which we dont' use. return self.values + @property + def shape(self): + """ + Return a tuple of the shape of the underlying data. + """ + # overriding the base Index.shape definition to avoid materializing + # the values (GH-27384, GH-27775) + return (len(self),) + @property def array(self): """ diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index c40a9bce9385b..d1ed79118d2fa 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2805,3 +2805,17 @@ def test_deprecated_fastpath(): expected = pd.CategoricalIndex(["a", "b", "c"], name="test") tm.assert_index_equal(idx, expected) + + +def test_shape_of_invalid_index(): + # Currently, it is possible to create "invalid" index objects backed by + # a multi-dimensional array (see https://github.com/pandas-dev/pandas/issues/27125 + # about this). However, as long as this is not solved in general,this test ensures + # that the returned shape is consistent with this underlying array for + # compat with matplotlib (see https://github.com/pandas-dev/pandas/issues/27775) + a = np.arange(8).reshape(2, 2, 2) + idx = pd.Index(a) + assert idx.shape == a.shape + + idx = pd.Index([0, 1, 2, 3]) + assert idx[:, None].shape == (4, 1)
closes #27775
https://api.github.com/repos/pandas-dev/pandas/pulls/27818
2019-08-08T09:54:09Z
2019-08-09T07:36:58Z
2019-08-09T07:36:58Z
2019-08-09T07:56:16Z
REF: implement should_extension_dispatch
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 7229b3de4e9f0..843f12c20b07b 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -47,7 +47,7 @@ import pandas as pd from pandas._typing import ArrayLike -from pandas.core.construction import extract_array +from pandas.core.construction import array, extract_array from pandas.core.ops import missing from pandas.core.ops.docstrings import ( _arith_doc_FRAME, @@ -460,6 +460,33 @@ def masked_arith_op(x, y, op): # Dispatch logic +def should_extension_dispatch(left: ABCSeries, right: Any) -> bool: + """ + Identify cases where Series operation should use dispatch_to_extension_op. + + Parameters + ---------- + left : Series + right : object + + Returns + ------- + bool + """ + if ( + is_extension_array_dtype(left.dtype) + or is_datetime64_dtype(left.dtype) + or is_timedelta64_dtype(left.dtype) + ): + return True + + if is_extension_array_dtype(right) and not is_scalar(right): + # GH#22378 disallow scalar to exclude e.g. "category", "Int64" + return True + + return False + + def should_series_dispatch(left, right, op): """ Identify cases where a DataFrame operation should dispatch to its @@ -564,19 +591,18 @@ def dispatch_to_extension_op(op, left, right): apply the operator defined by op. """ + if left.dtype.kind in "mM": + # We need to cast datetime64 and timedelta64 ndarrays to + # DatetimeArray/TimedeltaArray. But we avoid wrapping others in + # PandasArray as that behaves poorly with e.g. IntegerArray. + left = array(left) + # The op calls will raise TypeError if the op is not defined # on the ExtensionArray # unbox Series and Index to arrays - if isinstance(left, (ABCSeries, ABCIndexClass)): - new_left = left._values - else: - new_left = left - - if isinstance(right, (ABCSeries, ABCIndexClass)): - new_right = right._values - else: - new_right = right + new_left = extract_array(left, extract_numpy=True) + new_right = extract_array(right, extract_numpy=True) try: res_values = op(new_left, new_right) @@ -684,56 +710,27 @@ def wrapper(left, right): res_name = get_op_result_name(left, right) right = maybe_upcast_for_op(right, left.shape) - if is_categorical_dtype(left): - raise TypeError( - "{typ} cannot perform the operation " - "{op}".format(typ=type(left).__name__, op=str_rep) - ) - - elif is_datetime64_dtype(left) or is_datetime64tz_dtype(left): - from pandas.core.arrays import DatetimeArray - - result = dispatch_to_extension_op(op, DatetimeArray(left), right) - return construct_result(left, result, index=left.index, name=res_name) - - elif is_extension_array_dtype(left) or ( - is_extension_array_dtype(right) and not is_scalar(right) - ): - # GH#22378 disallow scalar to exclude e.g. "category", "Int64" + if should_extension_dispatch(left, right): result = dispatch_to_extension_op(op, left, right) - return construct_result(left, result, index=left.index, name=res_name) - elif is_timedelta64_dtype(left): - from pandas.core.arrays import TimedeltaArray - - result = dispatch_to_extension_op(op, TimedeltaArray(left), right) - return construct_result(left, result, index=left.index, name=res_name) - - elif is_timedelta64_dtype(right): - # We should only get here with non-scalar values for right - # upcast by maybe_upcast_for_op + elif is_timedelta64_dtype(right) or isinstance( + right, (ABCDatetimeArray, ABCDatetimeIndex) + ): + # We should only get here with td64 right with non-scalar values + # for right upcast by maybe_upcast_for_op assert not isinstance(right, (np.timedelta64, np.ndarray)) - result = op(left._values, right) - # We do not pass dtype to ensure that the Series constructor - # 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, ABCDatetimeIndex)): - result = op(left._values, right) - return construct_result(left, result, index=left.index, name=res_name) + else: + lvalues = extract_array(left, extract_numpy=True) + rvalues = extract_array(right, extract_numpy=True) - lvalues = left.values - rvalues = right - if isinstance(rvalues, (ABCSeries, ABCIndexClass)): - rvalues = rvalues._values + with np.errstate(all="ignore"): + result = na_op(lvalues, rvalues) - with np.errstate(all="ignore"): - result = na_op(lvalues, rvalues) - return construct_result( - left, result, index=left.index, name=res_name, dtype=None - ) + # We do not pass dtype to ensure that the Series constructor + # does inference in the case where `result` has object-dtype. + return construct_result(left, result, index=left.index, name=res_name) wrapper.__name__ = op_name return wrapper diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py index 9a09ea8422b1f..22c1d5373372a 100644 --- a/pandas/tests/arrays/categorical/test_operators.py +++ b/pandas/tests/arrays/categorical/test_operators.py @@ -349,7 +349,9 @@ def test_numeric_like_ops(self): ("__mul__", r"\*"), ("__truediv__", "/"), ]: - msg = r"Series cannot perform the operation {}".format(str_rep) + msg = r"Series cannot perform the operation {}|unsupported operand".format( + str_rep + ) with pytest.raises(TypeError, match=msg): getattr(df, op)(df) @@ -375,7 +377,9 @@ def test_numeric_like_ops(self): ("__mul__", r"\*"), ("__truediv__", "/"), ]: - msg = r"Series cannot perform the operation {}".format(str_rep) + msg = r"Series cannot perform the operation {}|unsupported operand".format( + str_rep + ) with pytest.raises(TypeError, match=msg): getattr(s, op)(2) diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py index f7456d24ad6d3..0c0e8b0123c03 100644 --- a/pandas/tests/extension/test_categorical.py +++ b/pandas/tests/extension/test_categorical.py @@ -211,7 +211,7 @@ def test_arith_series_with_scalar(self, data, all_arithmetic_operators): def test_add_series_with_extension_array(self, data): ser = pd.Series(data) - with pytest.raises(TypeError, match="cannot perform"): + with pytest.raises(TypeError, match="cannot perform|unsupported operand"): ser + data def test_divmod_series_array(self):
This uses should_extension_dispatch in _arith_method_SERIES. We'll be able to use it in _comp_method_SERIES after #27803. (this is orthogonal to 27803 so doesn't matter what order they go in)
https://api.github.com/repos/pandas-dev/pandas/pulls/27815
2019-08-08T03:20:05Z
2019-08-14T20:39:15Z
2019-08-14T20:39:15Z
2019-08-14T21:34:32Z
BUG: Series.rename raises error on values accepted by Series construc…
diff --git a/doc/source/whatsnew/v0.25.1.rst b/doc/source/whatsnew/v0.25.1.rst index 680d69a9862cd..b307fae4fbdc1 100644 --- a/doc/source/whatsnew/v0.25.1.rst +++ b/doc/source/whatsnew/v0.25.1.rst @@ -108,6 +108,7 @@ Other ^^^^^ - Bug in :meth:`Series.replace` and :meth:`DataFrame.replace` when replacing timezone-aware timestamps using a dict-like replacer (:issue:`27720`) +- Bug in :meth:`Series.rename` when using a custom type indexer. Now any value that isn't callable or dict-like is treated as a scalar. (:issue:`27814`) .. _whatsnew_0.251.contributors: diff --git a/pandas/core/series.py b/pandas/core/series.py index 3f04970ee4e58..8b6c963e40e9d 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4165,12 +4165,10 @@ def rename(self, index=None, **kwargs): """ kwargs["inplace"] = validate_bool_kwarg(kwargs.get("inplace", False), "inplace") - non_mapping = is_scalar(index) or ( - is_list_like(index) and not is_dict_like(index) - ) - if non_mapping: + if callable(index) or is_dict_like(index): + return super().rename(index=index, **kwargs) + else: return self._set_name(index, inplace=kwargs.get("inplace")) - return super().rename(index=index, **kwargs) @Substitution(**_shared_doc_kwargs) @Appender(generic.NDFrame.reindex.__doc__) diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py index 0a25d6ba203cb..5d74ad95be90d 100644 --- a/pandas/tests/series/test_alter_axes.py +++ b/pandas/tests/series/test_alter_axes.py @@ -267,6 +267,25 @@ def test_rename_axis_none(self, kwargs): expected = Series([1, 2, 3], index=expected_index) tm.assert_series_equal(result, expected) + def test_rename_with_custom_indexer(self): + # GH 27814 + class MyIndexer: + pass + + ix = MyIndexer() + s = Series([1, 2, 3]).rename(ix) + assert s.name is ix + + def test_rename_with_custom_indexer_inplace(self): + # GH 27814 + class MyIndexer: + pass + + ix = MyIndexer() + s = Series([1, 2, 3]) + s.rename(ix, inplace=True) + assert s.name is ix + def test_set_axis_inplace_axes(self, axis_series): # GH14636 ser = Series(np.arange(4), index=[1, 3, 5, 7], dtype="int64")
- closes #27813
https://api.github.com/repos/pandas-dev/pandas/pulls/27814
2019-08-08T02:04:10Z
2019-08-22T13:07:47Z
2019-08-22T13:07:47Z
2019-08-22T13:07:48Z
REF: separate method-pinning functions
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 4ab1941e3493f..01de1428e290c 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -41,7 +41,6 @@ ABCIndex, ABCIndexClass, ABCSeries, - ABCSparseArray, ABCSparseSeries, ) from pandas.core.dtypes.missing import isna, notna @@ -57,6 +56,10 @@ _op_descriptions, ) from pandas.core.ops.invalid import invalid_comparison +from pandas.core.ops.methods import ( # noqa:F401 + add_flex_arithmetic_methods, + add_special_arithmetic_methods, +) from pandas.core.ops.roperator import ( # noqa:F401 radd, rand_, @@ -587,224 +590,6 @@ def dispatch_to_extension_op(op, left, right): return res_values -# ----------------------------------------------------------------------------- -# Functions that add arithmetic methods to objects, given arithmetic factory -# methods - - -def _get_method_wrappers(cls): - """ - Find the appropriate operation-wrappers to use when defining flex/special - arithmetic, boolean, and comparison operations with the given class. - - Parameters - ---------- - cls : class - - Returns - ------- - arith_flex : function or None - comp_flex : function or None - arith_special : function - comp_special : function - bool_special : function - - Notes - ----- - None is only returned for SparseArray - """ - if issubclass(cls, ABCSparseSeries): - # Be sure to catch this before ABCSeries and ABCSparseArray, - # as they will both come see SparseSeries as a subclass - arith_flex = _flex_method_SERIES - comp_flex = _flex_method_SERIES - arith_special = _arith_method_SPARSE_SERIES - comp_special = _arith_method_SPARSE_SERIES - bool_special = _bool_method_SERIES - # TODO: I don't think the functions defined by bool_method are tested - elif issubclass(cls, ABCSeries): - # Just Series; SparseSeries is caught above - arith_flex = _flex_method_SERIES - comp_flex = _flex_method_SERIES - arith_special = _arith_method_SERIES - comp_special = _comp_method_SERIES - bool_special = _bool_method_SERIES - elif issubclass(cls, ABCDataFrame): - # Same for DataFrame and SparseDataFrame - arith_flex = _arith_method_FRAME - comp_flex = _flex_comp_method_FRAME - arith_special = _arith_method_FRAME - comp_special = _comp_method_FRAME - bool_special = _arith_method_FRAME - return arith_flex, comp_flex, arith_special, comp_special, bool_special - - -def _create_methods(cls, arith_method, comp_method, bool_method, special): - # creates actual methods based upon arithmetic, comp and bool method - # constructors. - - have_divmod = issubclass(cls, ABCSeries) - # divmod is available for Series and SparseSeries - - # yapf: disable - new_methods = dict( - add=arith_method(cls, operator.add, special), - radd=arith_method(cls, radd, special), - sub=arith_method(cls, operator.sub, special), - mul=arith_method(cls, operator.mul, special), - truediv=arith_method(cls, operator.truediv, special), - floordiv=arith_method(cls, operator.floordiv, special), - # Causes a floating point exception in the tests when numexpr enabled, - # so for now no speedup - mod=arith_method(cls, operator.mod, special), - pow=arith_method(cls, operator.pow, special), - # not entirely sure why this is necessary, but previously was included - # so it's here to maintain compatibility - rmul=arith_method(cls, rmul, special), - rsub=arith_method(cls, rsub, special), - rtruediv=arith_method(cls, rtruediv, special), - rfloordiv=arith_method(cls, rfloordiv, special), - rpow=arith_method(cls, rpow, special), - rmod=arith_method(cls, rmod, special)) - # yapf: enable - new_methods["div"] = new_methods["truediv"] - new_methods["rdiv"] = new_methods["rtruediv"] - if have_divmod: - # divmod doesn't have an op that is supported by numexpr - new_methods["divmod"] = arith_method(cls, divmod, special) - new_methods["rdivmod"] = arith_method(cls, rdivmod, special) - - new_methods.update( - dict( - eq=comp_method(cls, operator.eq, special), - ne=comp_method(cls, operator.ne, special), - lt=comp_method(cls, operator.lt, special), - gt=comp_method(cls, operator.gt, special), - le=comp_method(cls, operator.le, special), - ge=comp_method(cls, operator.ge, special), - ) - ) - - if bool_method: - new_methods.update( - dict( - and_=bool_method(cls, operator.and_, special), - or_=bool_method(cls, operator.or_, special), - # For some reason ``^`` wasn't used in original. - xor=bool_method(cls, operator.xor, special), - rand_=bool_method(cls, rand_, special), - ror_=bool_method(cls, ror_, special), - rxor=bool_method(cls, rxor, special), - ) - ) - - if special: - dunderize = lambda x: "__{name}__".format(name=x.strip("_")) - else: - dunderize = lambda x: x - new_methods = {dunderize(k): v for k, v in new_methods.items()} - return new_methods - - -def add_methods(cls, new_methods): - for name, method in new_methods.items(): - # For most methods, if we find that the class already has a method - # of the same name, it is OK to over-write it. The exception is - # inplace methods (__iadd__, __isub__, ...) for SparseArray, which - # retain the np.ndarray versions. - force = not (issubclass(cls, ABCSparseArray) and name.startswith("__i")) - if force or name not in cls.__dict__: - setattr(cls, name, method) - - -# ---------------------------------------------------------------------- -# Arithmetic -def add_special_arithmetic_methods(cls): - """ - Adds the full suite of special arithmetic methods (``__add__``, - ``__sub__``, etc.) to the class. - - Parameters - ---------- - cls : class - special methods will be defined and pinned to this class - """ - _, _, arith_method, comp_method, bool_method = _get_method_wrappers(cls) - new_methods = _create_methods( - cls, arith_method, comp_method, bool_method, special=True - ) - # inplace operators (I feel like these should get passed an `inplace=True` - # or just be removed - - def _wrap_inplace_method(method): - """ - return an inplace wrapper for this method - """ - - def f(self, other): - result = method(self, other) - - # this makes sure that we are aligned like the input - # we are updating inplace so we want to ignore is_copy - self._update_inplace( - result.reindex_like(self, copy=False)._data, verify_is_copy=False - ) - - return self - - f.__name__ = "__i{name}__".format(name=method.__name__.strip("__")) - return f - - new_methods.update( - dict( - __iadd__=_wrap_inplace_method(new_methods["__add__"]), - __isub__=_wrap_inplace_method(new_methods["__sub__"]), - __imul__=_wrap_inplace_method(new_methods["__mul__"]), - __itruediv__=_wrap_inplace_method(new_methods["__truediv__"]), - __ifloordiv__=_wrap_inplace_method(new_methods["__floordiv__"]), - __imod__=_wrap_inplace_method(new_methods["__mod__"]), - __ipow__=_wrap_inplace_method(new_methods["__pow__"]), - ) - ) - - new_methods.update( - dict( - __iand__=_wrap_inplace_method(new_methods["__and__"]), - __ior__=_wrap_inplace_method(new_methods["__or__"]), - __ixor__=_wrap_inplace_method(new_methods["__xor__"]), - ) - ) - - add_methods(cls, new_methods=new_methods) - - -def add_flex_arithmetic_methods(cls): - """ - Adds the full suite of flex arithmetic methods (``pow``, ``mul``, ``add``) - to the class. - - Parameters - ---------- - cls : class - flex methods will be defined and pinned to this class - """ - flex_arith_method, flex_comp_method, _, _, _ = _get_method_wrappers(cls) - new_methods = _create_methods( - cls, flex_arith_method, flex_comp_method, bool_method=None, special=False - ) - new_methods.update( - dict( - multiply=new_methods["mul"], - subtract=new_methods["sub"], - divide=new_methods["div"], - ) - ) - # opt out of bool flex methods for now - assert not any(kname in new_methods for kname in ("ror_", "rxor", "rand_")) - - add_methods(cls, new_methods=new_methods) - - # ----------------------------------------------------------------------------- # Series diff --git a/pandas/core/ops/methods.py b/pandas/core/ops/methods.py new file mode 100644 index 0000000000000..eba0a797a791f --- /dev/null +++ b/pandas/core/ops/methods.py @@ -0,0 +1,249 @@ +""" +Functions to generate methods and pin them to the appropriate classes. +""" +import operator + +from pandas.core.dtypes.generic import ( + ABCDataFrame, + ABCSeries, + ABCSparseArray, + ABCSparseSeries, +) + +from pandas.core.ops.roperator import ( + radd, + rand_, + rdivmod, + rfloordiv, + rmod, + rmul, + ror_, + rpow, + rsub, + rtruediv, + rxor, +) + + +def _get_method_wrappers(cls): + """ + Find the appropriate operation-wrappers to use when defining flex/special + arithmetic, boolean, and comparison operations with the given class. + + Parameters + ---------- + cls : class + + Returns + ------- + arith_flex : function or None + comp_flex : function or None + arith_special : function + comp_special : function + bool_special : function + + Notes + ----- + None is only returned for SparseArray + """ + # TODO: make these non-runtime imports once the relevant functions + # are no longer in __init__ + from pandas.core.ops import ( + _arith_method_FRAME, + _arith_method_SERIES, + _arith_method_SPARSE_SERIES, + _bool_method_SERIES, + _comp_method_FRAME, + _comp_method_SERIES, + _flex_comp_method_FRAME, + _flex_method_SERIES, + ) + + if issubclass(cls, ABCSparseSeries): + # Be sure to catch this before ABCSeries and ABCSparseArray, + # as they will both come see SparseSeries as a subclass + arith_flex = _flex_method_SERIES + comp_flex = _flex_method_SERIES + arith_special = _arith_method_SPARSE_SERIES + comp_special = _arith_method_SPARSE_SERIES + bool_special = _bool_method_SERIES + # TODO: I don't think the functions defined by bool_method are tested + elif issubclass(cls, ABCSeries): + # Just Series; SparseSeries is caught above + arith_flex = _flex_method_SERIES + comp_flex = _flex_method_SERIES + arith_special = _arith_method_SERIES + comp_special = _comp_method_SERIES + bool_special = _bool_method_SERIES + elif issubclass(cls, ABCDataFrame): + # Same for DataFrame and SparseDataFrame + arith_flex = _arith_method_FRAME + comp_flex = _flex_comp_method_FRAME + arith_special = _arith_method_FRAME + comp_special = _comp_method_FRAME + bool_special = _arith_method_FRAME + return arith_flex, comp_flex, arith_special, comp_special, bool_special + + +def add_special_arithmetic_methods(cls): + """ + Adds the full suite of special arithmetic methods (``__add__``, + ``__sub__``, etc.) to the class. + + Parameters + ---------- + cls : class + special methods will be defined and pinned to this class + """ + _, _, arith_method, comp_method, bool_method = _get_method_wrappers(cls) + new_methods = _create_methods( + cls, arith_method, comp_method, bool_method, special=True + ) + # inplace operators (I feel like these should get passed an `inplace=True` + # or just be removed + + def _wrap_inplace_method(method): + """ + return an inplace wrapper for this method + """ + + def f(self, other): + result = method(self, other) + + # this makes sure that we are aligned like the input + # we are updating inplace so we want to ignore is_copy + self._update_inplace( + result.reindex_like(self, copy=False)._data, verify_is_copy=False + ) + + return self + + f.__name__ = "__i{name}__".format(name=method.__name__.strip("__")) + return f + + new_methods.update( + dict( + __iadd__=_wrap_inplace_method(new_methods["__add__"]), + __isub__=_wrap_inplace_method(new_methods["__sub__"]), + __imul__=_wrap_inplace_method(new_methods["__mul__"]), + __itruediv__=_wrap_inplace_method(new_methods["__truediv__"]), + __ifloordiv__=_wrap_inplace_method(new_methods["__floordiv__"]), + __imod__=_wrap_inplace_method(new_methods["__mod__"]), + __ipow__=_wrap_inplace_method(new_methods["__pow__"]), + ) + ) + + new_methods.update( + dict( + __iand__=_wrap_inplace_method(new_methods["__and__"]), + __ior__=_wrap_inplace_method(new_methods["__or__"]), + __ixor__=_wrap_inplace_method(new_methods["__xor__"]), + ) + ) + + _add_methods(cls, new_methods=new_methods) + + +def add_flex_arithmetic_methods(cls): + """ + Adds the full suite of flex arithmetic methods (``pow``, ``mul``, ``add``) + to the class. + + Parameters + ---------- + cls : class + flex methods will be defined and pinned to this class + """ + flex_arith_method, flex_comp_method, _, _, _ = _get_method_wrappers(cls) + new_methods = _create_methods( + cls, flex_arith_method, flex_comp_method, bool_method=None, special=False + ) + new_methods.update( + dict( + multiply=new_methods["mul"], + subtract=new_methods["sub"], + divide=new_methods["div"], + ) + ) + # opt out of bool flex methods for now + assert not any(kname in new_methods for kname in ("ror_", "rxor", "rand_")) + + _add_methods(cls, new_methods=new_methods) + + +def _create_methods(cls, arith_method, comp_method, bool_method, special): + # creates actual methods based upon arithmetic, comp and bool method + # constructors. + + have_divmod = issubclass(cls, ABCSeries) + # divmod is available for Series and SparseSeries + + # yapf: disable + new_methods = dict( + add=arith_method(cls, operator.add, special), + radd=arith_method(cls, radd, special), + sub=arith_method(cls, operator.sub, special), + mul=arith_method(cls, operator.mul, special), + truediv=arith_method(cls, operator.truediv, special), + floordiv=arith_method(cls, operator.floordiv, special), + # Causes a floating point exception in the tests when numexpr enabled, + # so for now no speedup + mod=arith_method(cls, operator.mod, special), + pow=arith_method(cls, operator.pow, special), + # not entirely sure why this is necessary, but previously was included + # so it's here to maintain compatibility + rmul=arith_method(cls, rmul, special), + rsub=arith_method(cls, rsub, special), + rtruediv=arith_method(cls, rtruediv, special), + rfloordiv=arith_method(cls, rfloordiv, special), + rpow=arith_method(cls, rpow, special), + rmod=arith_method(cls, rmod, special)) + # yapf: enable + new_methods["div"] = new_methods["truediv"] + new_methods["rdiv"] = new_methods["rtruediv"] + if have_divmod: + # divmod doesn't have an op that is supported by numexpr + new_methods["divmod"] = arith_method(cls, divmod, special) + new_methods["rdivmod"] = arith_method(cls, rdivmod, special) + + new_methods.update( + dict( + eq=comp_method(cls, operator.eq, special), + ne=comp_method(cls, operator.ne, special), + lt=comp_method(cls, operator.lt, special), + gt=comp_method(cls, operator.gt, special), + le=comp_method(cls, operator.le, special), + ge=comp_method(cls, operator.ge, special), + ) + ) + + if bool_method: + new_methods.update( + dict( + and_=bool_method(cls, operator.and_, special), + or_=bool_method(cls, operator.or_, special), + # For some reason ``^`` wasn't used in original. + xor=bool_method(cls, operator.xor, special), + rand_=bool_method(cls, rand_, special), + ror_=bool_method(cls, ror_, special), + rxor=bool_method(cls, rxor, special), + ) + ) + + if special: + dunderize = lambda x: "__{name}__".format(name=x.strip("_")) + else: + dunderize = lambda x: x + new_methods = {dunderize(k): v for k, v in new_methods.items()} + return new_methods + + +def _add_methods(cls, new_methods): + for name, method in new_methods.items(): + # For most methods, if we find that the class already has a method + # of the same name, it is OK to over-write it. The exception is + # inplace methods (__iadd__, __isub__, ...) for SparseArray, which + # retain the np.ndarray versions. + force = not (issubclass(cls, ABCSparseArray) and name.startswith("__i")) + if force or name not in cls.__dict__: + setattr(cls, name, method)
These are the ones that are executed at import-time and then never needed again.
https://api.github.com/repos/pandas-dev/pandas/pulls/27811
2019-08-07T22:26:00Z
2019-08-08T12:33:12Z
2019-08-08T12:33:12Z
2019-08-08T13:33:55Z
TST: skip test if running non-installed
diff --git a/pandas/tests/plotting/test_backend.py b/pandas/tests/plotting/test_backend.py index e79e7b6239eb3..d126407cfd823 100644 --- a/pandas/tests/plotting/test_backend.py +++ b/pandas/tests/plotting/test_backend.py @@ -46,14 +46,18 @@ def test_backend_is_correct(monkeypatch): @td.skip_if_no_mpl def test_register_entrypoint(): + + dist = pkg_resources.get_distribution("pandas") + if dist.module_path not in pandas.__file__: + # We are running from a non-installed pandas, and this test is invalid + pytest.skip("Testing a non-installed pandas") + mod = types.ModuleType("my_backend") mod.plot = lambda *args, **kwargs: 1 backends = pkg_resources.get_entry_map("pandas") my_entrypoint = pkg_resources.EntryPoint( - "pandas_plotting_backend", - mod.__name__, - dist=pkg_resources.get_distribution("pandas"), + "pandas_plotting_backend", mod.__name__, dist=dist ) backends["pandas_plotting_backends"]["my_backend"] = my_entrypoint # TODO: the docs recommend importlib.util.module_from_spec. But this works for now.
If running the tests without the branch installed, this test fails. Skip it instead.
https://api.github.com/repos/pandas-dev/pandas/pulls/27810
2019-08-07T21:33:24Z
2019-08-13T12:06:27Z
2019-08-13T12:06:27Z
2019-08-13T13:57:29Z
CI: remove pytest pins
diff --git a/ci/deps/azure-36-locale.yaml b/ci/deps/azure-36-locale.yaml index 8f8273f57c3fe..6a77b5dbedc61 100644 --- a/ci/deps/azure-36-locale.yaml +++ b/ci/deps/azure-36-locale.yaml @@ -20,8 +20,8 @@ dependencies: - xlsxwriter=0.9.8 - xlwt=1.2.0 # universal - - pytest>=4.0.2,<5.0.0 - - pytest-xdist + - pytest>=5.0.0 + - pytest-xdist>=1.29.0 - pytest-mock - pytest-azurepipelines - hypothesis>=3.58.0 diff --git a/ci/deps/travis-36-slow.yaml b/ci/deps/travis-36-slow.yaml index 538a82f66e4c8..9564bf5bb3a9f 100644 --- a/ci/deps/travis-36-slow.yaml +++ b/ci/deps/travis-36-slow.yaml @@ -25,8 +25,8 @@ dependencies: - xlsxwriter - xlwt # universal - - pytest>=4.0.2,<5.0.0 - - pytest-xdist + - pytest>=5.0.0 + - pytest-xdist>=1.29.0 - pytest-mock - moto - hypothesis>=3.58.0
https://api.github.com/repos/pandas-dev/pandas/pulls/27809
2019-08-07T21:20:42Z
2019-08-08T11:00:23Z
2019-08-08T11:00:23Z
2019-08-08T16:22:48Z
VIS: Fix DataFrame.plot() produces incorrect legend markers when plotting multiple series on the same axis
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index b35f230100f8d..82bba1ae22bf2 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -165,6 +165,7 @@ Plotting - Bug in :meth:`Series.plot` not able to plot boolean values (:issue:`23719`) - +- Bug in :meth:`DataFrame.plot` producing incorrect legend markers when plotting multiple series on the same axis (:issue:`18222`) - Bug in :meth:`DataFrame.plot` when ``kind='box'`` and data contains datetime or timedelta data. These types are now automatically dropped (:issue:`22799`) Groupby/resample/rolling diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index a262f89dcc79c..287cc2f4130f4 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -562,7 +562,7 @@ def _add_legend_handle(self, handle, label, index=None): self.legend_labels.append(label) def _make_legend(self): - ax, leg = self._get_ax_legend(self.axes[0]) + ax, leg, handle = self._get_ax_legend_handle(self.axes[0]) handles = [] labels = [] @@ -571,7 +571,8 @@ def _make_legend(self): if not self.subplots: if leg is not None: title = leg.get_title().get_text() - handles = leg.legendHandles + # Replace leg.LegendHandles because it misses marker info + handles.extend(handle) labels = [x.get_text() for x in leg.get_texts()] if self.legend: @@ -581,6 +582,7 @@ def _make_legend(self): handles += self.legend_handles labels += self.legend_labels + if self.legend_title is not None: title = self.legend_title @@ -592,8 +594,14 @@ def _make_legend(self): if ax.get_visible(): ax.legend(loc="best") - def _get_ax_legend(self, ax): + def _get_ax_legend_handle(self, ax): + """ + Take in axes and return ax, legend and handle under different scenarios + """ leg = ax.get_legend() + + # Get handle from axes + handle, _ = ax.get_legend_handles_labels() other_ax = getattr(ax, "left_ax", None) or getattr(ax, "right_ax", None) other_leg = None if other_ax is not None: @@ -601,7 +609,7 @@ def _get_ax_legend(self, ax): if leg is None and other_leg is not None: leg = other_leg ax = other_ax - return ax, leg + return ax, leg, handle @cache_readonly def plt(self): diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index 4929422d20e8a..5a591f72d7361 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -103,6 +103,28 @@ def _check_legend_labels(self, axes, labels=None, visible=True): else: assert ax.get_legend() is None + def _check_legend_marker(self, ax, expected_markers=None, visible=True): + """ + Check ax has expected legend markers + + Parameters + ---------- + ax : matplotlib Axes object + expected_markers : list-like + expected legend markers + visible : bool + expected legend visibility. labels are checked only when visible is + True + """ + if visible and (expected_markers is None): + raise ValueError("Markers must be specified when visible is True") + if visible: + handles, _ = ax.get_legend_handles_labels() + markers = [handle.get_marker() for handle in handles] + assert markers == expected_markers + else: + assert ax.get_legend() is None + def _check_data(self, xp, rs): """ Check each axes has identical lines diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 65815bcedebfc..7fdc0252b71e3 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -1881,6 +1881,31 @@ def test_df_legend_labels(self): self._check_legend_labels(ax, labels=["LABEL_b", "LABEL_c"]) assert df5.columns.tolist() == ["b", "c"] + def test_missing_marker_multi_plots_on_same_ax(self): + # GH 18222 + df = pd.DataFrame( + data=[[1, 1, 1, 1], [2, 2, 4, 8]], columns=["x", "r", "g", "b"] + ) + fig, ax = self.plt.subplots(nrows=1, ncols=3) + # Left plot + df.plot(x="x", y="r", linewidth=0, marker="o", color="r", ax=ax[0]) + df.plot(x="x", y="g", linewidth=1, marker="x", color="g", ax=ax[0]) + df.plot(x="x", y="b", linewidth=1, marker="o", color="b", ax=ax[0]) + self._check_legend_labels(ax[0], labels=["r", "g", "b"]) + self._check_legend_marker(ax[0], expected_markers=["o", "x", "o"]) + # Center plot + df.plot(x="x", y="b", linewidth=1, marker="o", color="b", ax=ax[1]) + df.plot(x="x", y="r", linewidth=0, marker="o", color="r", ax=ax[1]) + df.plot(x="x", y="g", linewidth=1, marker="x", color="g", ax=ax[1]) + self._check_legend_labels(ax[1], labels=["b", "r", "g"]) + self._check_legend_marker(ax[1], expected_markers=["o", "o", "x"]) + # Right plot + df.plot(x="x", y="g", linewidth=1, marker="x", color="g", ax=ax[2]) + df.plot(x="x", y="b", linewidth=1, marker="o", color="b", ax=ax[2]) + df.plot(x="x", y="r", linewidth=0, marker="o", color="r", ax=ax[2]) + self._check_legend_labels(ax[2], labels=["g", "b", "r"]) + self._check_legend_marker(ax[2], expected_markers=["x", "o", "o"]) + def test_legend_name(self): multi = DataFrame( randn(4, 4),
I found out that the reason this happens is because `subplots` is not updated accordingly when `plt.subplots()` is used and assign to `ax`, e.g. `fig, ax = plt.subplots(nrows=1, ncols=3)`. I tested my solution and things all get solved, and figure looks very correct like below: ![Screen Shot 2019-08-07 at 10 03 39 PM](https://user-images.githubusercontent.com/9269816/62654665-95a30a80-b960-11e9-94ad-ab43a0e8a3cf.png) BTW, i am not very sure how to properly test this, and would be nice to know! - [x] closes #18222 - [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/27808
2019-08-07T20:10:10Z
2019-08-16T11:38:47Z
2019-08-16T11:38:47Z
2021-01-31T10:02:37Z
BUG: fix+test op(NaT, ndarray), also simplify
diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index 6fab1b5c02be1..020d1acf0b4ce 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -92,6 +92,9 @@ cdef class _NaT(datetime): # int64_t value # object freq + # higher than np.ndarray and np.matrix + __array_priority__ = 100 + def __hash__(_NaT self): # py3k needs this defined here return hash(self.value) @@ -103,61 +106,102 @@ cdef class _NaT(datetime): if ndim == -1: return _nat_scalar_rules[op] - if ndim == 0: + elif util.is_array(other): + result = np.empty(other.shape, dtype=np.bool_) + result.fill(_nat_scalar_rules[op]) + return result + + elif ndim == 0: if is_datetime64_object(other): return _nat_scalar_rules[op] else: raise TypeError('Cannot compare type %r with type %r' % (type(self).__name__, type(other).__name__)) + # Note: instead of passing "other, self, _reverse_ops[op]", we observe # that `_nat_scalar_rules` is invariant under `_reverse_ops`, # rendering it unnecessary. return PyObject_RichCompare(other, self, op) def __add__(self, other): + if self is not c_NaT: + # cython __radd__ semantics + self, other = other, self + if PyDateTime_Check(other): return c_NaT - + elif PyDelta_Check(other): + return c_NaT + elif is_datetime64_object(other) or is_timedelta64_object(other): + return c_NaT elif hasattr(other, 'delta'): # Timedelta, offsets.Tick, offsets.Week return c_NaT - elif getattr(other, '_typ', None) in ['dateoffset', 'series', - 'period', 'datetimeindex', - 'datetimearray', - 'timedeltaindex', - 'timedeltaarray']: - # Duplicate logic in _Timestamp.__add__ to avoid needing - # to subclass; allows us to @final(_Timestamp.__add__) - return NotImplemented - return c_NaT + + elif is_integer_object(other) or util.is_period_object(other): + # For Period compat + # TODO: the integer behavior is deprecated, remove it + return c_NaT + + elif util.is_array(other): + if other.dtype.kind in 'mM': + # If we are adding to datetime64, we treat NaT as timedelta + # Either way, result dtype is datetime64 + result = np.empty(other.shape, dtype="datetime64[ns]") + result.fill("NaT") + return result + + return NotImplemented def __sub__(self, other): # Duplicate some logic from _Timestamp.__sub__ to avoid needing # to subclass; allows us to @final(_Timestamp.__sub__) + cdef: + bint is_rsub = False + + if self is not c_NaT: + # cython __rsub__ semantics + self, other = other, self + is_rsub = True + if PyDateTime_Check(other): - return NaT + return c_NaT elif PyDelta_Check(other): - return NaT + return c_NaT + elif is_datetime64_object(other) or is_timedelta64_object(other): + return c_NaT + elif hasattr(other, 'delta'): + # offsets.Tick, offsets.Week + return c_NaT - elif getattr(other, '_typ', None) == 'datetimeindex': - # a Timestamp-DatetimeIndex -> yields a negative TimedeltaIndex - return -other.__sub__(self) + elif is_integer_object(other) or util.is_period_object(other): + # For Period compat + # TODO: the integer behavior is deprecated, remove it + return c_NaT - elif getattr(other, '_typ', None) == 'timedeltaindex': - # a Timestamp-TimedeltaIndex -> yields a negative TimedeltaIndex - return (-other).__add__(self) + elif util.is_array(other): + if other.dtype.kind == 'm': + if not is_rsub: + # NaT - timedelta64 we treat NaT as datetime64, so result + # is datetime64 + result = np.empty(other.shape, dtype="datetime64[ns]") + result.fill("NaT") + return result + + # timedelta64 - NaT we have to treat NaT as timedelta64 + # for this to be meaningful, and the result is timedelta64 + result = np.empty(other.shape, dtype="timedelta64[ns]") + result.fill("NaT") + return result + + elif other.dtype.kind == 'M': + # We treat NaT as a datetime, so regardless of whether this is + # NaT - other or other - NaT, the result is timedelta64 + result = np.empty(other.shape, dtype="timedelta64[ns]") + result.fill("NaT") + return result - elif hasattr(other, 'delta'): - # offsets.Tick, offsets.Week - neg_other = -other - return self + neg_other - - elif getattr(other, '_typ', None) in ['period', 'series', - 'periodindex', 'dateoffset', - 'datetimearray', - 'timedeltaarray']: - return NotImplemented - return NaT + return NotImplemented def __pos__(self): return NaT diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 9f2b31f23d2fa..08f2aa68eca9e 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -4,7 +4,7 @@ import numpy as np -from pandas._libs import Timestamp, index as libindex, lib, tslib as libts +from pandas._libs import NaT, Timestamp, index as libindex, lib, tslib as libts import pandas._libs.join as libjoin from pandas._libs.tslibs import ccalendar, fields, parsing, timezones from pandas.util._decorators import Appender, Substitution, cache_readonly @@ -1281,7 +1281,9 @@ def insert(self, loc, item): raise ValueError("Passed item and index have different timezone") # check freq can be preserved on edge cases if self.size and self.freq is not None: - if (loc == 0 or loc == -len(self)) and item + self.freq == self[0]: + if item is NaT: + pass + elif (loc == 0 or loc == -len(self)) and item + self.freq == self[0]: freq = self.freq elif (loc == len(self)) and item - self.freq == self[-1]: freq = self.freq diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 4f5e00bc5a37d..6cf90de86ad14 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -1631,7 +1631,7 @@ def test_td64arr_div_nat_invalid(self, box_with_array): rng = timedelta_range("1 days", "10 days", name="foo") rng = tm.box_expected(rng, box_with_array) - with pytest.raises(TypeError, match="'?true_divide'? cannot use operands"): + with pytest.raises(TypeError, match="unsupported operand type"): rng / pd.NaT with pytest.raises(TypeError, match="Cannot divide NaTType by"): pd.NaT / rng diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index b57b817461788..6da4d556ea07e 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -1298,23 +1298,13 @@ def test_add_offset_nat(self): timedelta(365), ]: assert p + o is NaT - - if isinstance(o, np.timedelta64): - with pytest.raises(TypeError): - o + p - else: - assert o + p is NaT + assert o + p is NaT for freq in ["M", "2M", "3M"]: p = Period("NaT", freq=freq) for o in [offsets.MonthEnd(2), offsets.MonthEnd(12)]: assert p + o is NaT - - if isinstance(o, np.timedelta64): - with pytest.raises(TypeError): - o + p - else: - assert o + p is NaT + assert o + p is NaT for o in [ offsets.YearBegin(2), @@ -1324,12 +1314,7 @@ def test_add_offset_nat(self): timedelta(365), ]: assert p + o is NaT - - if isinstance(o, np.timedelta64): - with pytest.raises(TypeError): - o + p - else: - assert o + p is NaT + assert o + p is NaT # freq is Tick for freq in ["D", "2D", "3D"]: @@ -1343,12 +1328,7 @@ def test_add_offset_nat(self): timedelta(hours=48), ]: assert p + o is NaT - - if isinstance(o, np.timedelta64): - with pytest.raises(TypeError): - o + p - else: - assert o + p is NaT + assert o + p is NaT for o in [ offsets.YearBegin(2), @@ -1358,12 +1338,7 @@ def test_add_offset_nat(self): timedelta(hours=23), ]: assert p + o is NaT - - if isinstance(o, np.timedelta64): - with pytest.raises(TypeError): - o + p - else: - assert o + p is NaT + assert o + p is NaT for freq in ["H", "2H", "3H"]: p = Period("NaT", freq=freq) @@ -1376,9 +1351,7 @@ def test_add_offset_nat(self): timedelta(days=4, minutes=180), ]: assert p + o is NaT - - if not isinstance(o, np.timedelta64): - assert o + p is NaT + assert o + p is NaT for o in [ offsets.YearBegin(2), @@ -1388,12 +1361,7 @@ def test_add_offset_nat(self): timedelta(hours=23, minutes=30), ]: assert p + o is NaT - - if isinstance(o, np.timedelta64): - with pytest.raises(TypeError): - o + p - else: - assert o + p is NaT + assert o + p is NaT def test_sub_offset(self): # freq is DateOffset diff --git a/pandas/tests/scalar/test_nat.py b/pandas/tests/scalar/test_nat.py index e7ad76cf95ba0..5b1c4f92bf341 100644 --- a/pandas/tests/scalar/test_nat.py +++ b/pandas/tests/scalar/test_nat.py @@ -1,4 +1,5 @@ from datetime import datetime, timedelta +import operator import numpy as np import pytest @@ -21,6 +22,7 @@ isna, ) from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray +from pandas.core.ops import roperator from pandas.util import testing as tm @@ -333,8 +335,9 @@ def test_nat_doc_strings(compare): "value,val_type", [ (2, "scalar"), - (1.5, "scalar"), - (np.nan, "scalar"), + (1.5, "floating"), + (np.nan, "floating"), + ("foo", "str"), (timedelta(3600), "timedelta"), (Timedelta("5s"), "timedelta"), (datetime(2014, 1, 1), "timestamp"), @@ -348,6 +351,14 @@ def test_nat_arithmetic_scalar(op_name, value, val_type): # see gh-6873 invalid_ops = { "scalar": {"right_div_left"}, + "floating": { + "right_div_left", + "left_minus_right", + "right_minus_left", + "left_plus_right", + "right_plus_left", + }, + "str": set(_ops.keys()), "timedelta": {"left_times_right", "right_times_left"}, "timestamp": { "left_times_right", @@ -366,6 +377,16 @@ def test_nat_arithmetic_scalar(op_name, value, val_type): and isinstance(value, Timedelta) ): msg = "Cannot multiply" + elif val_type == "str": + # un-specific check here because the message comes from str + # and varies by method + msg = ( + "can only concatenate str|" + "unsupported operand type|" + "can't multiply sequence|" + "Can't convert 'NaTType'|" + "must be str, not NaTType" + ) else: msg = "unsupported operand type" @@ -435,6 +456,28 @@ def test_nat_arithmetic_td64_vector(op_name, box): tm.assert_equal(_ops[op_name](vec, NaT), box_nat) +@pytest.mark.parametrize( + "dtype,op,out_dtype", + [ + ("datetime64[ns]", operator.add, "datetime64[ns]"), + ("datetime64[ns]", roperator.radd, "datetime64[ns]"), + ("datetime64[ns]", operator.sub, "timedelta64[ns]"), + ("datetime64[ns]", roperator.rsub, "timedelta64[ns]"), + ("timedelta64[ns]", operator.add, "datetime64[ns]"), + ("timedelta64[ns]", roperator.radd, "datetime64[ns]"), + ("timedelta64[ns]", operator.sub, "datetime64[ns]"), + ("timedelta64[ns]", roperator.rsub, "timedelta64[ns]"), + ], +) +def test_nat_arithmetic_ndarray(dtype, op, out_dtype): + other = np.arange(10).astype(dtype) + result = op(NaT, other) + + expected = np.empty(other.shape, dtype=out_dtype) + expected.fill("NaT") + tm.assert_numpy_array_equal(result, expected) + + def test_nat_pinned_docstrings(): # see gh-17327 assert NaT.ctime.__doc__ == datetime.ctime.__doc__
https://api.github.com/repos/pandas-dev/pandas/pulls/27807
2019-08-07T18:06:42Z
2019-08-15T12:41:33Z
2019-08-15T12:41:33Z
2019-08-15T14:19:41Z
BUG: fix construction of NonConsolidatableBlock with inconsistent ndim (#27786)
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 26aca34f20594..33517087c5d76 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -274,6 +274,8 @@ def make_block_same_class(self, values, placement=None, ndim=None, dtype=None): ) if placement is None: placement = self.mgr_locs + if ndim is None: + ndim = self.ndim return make_block( values, placement=placement, ndim=ndim, klass=self.__class__, dtype=dtype ) diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index e02586eacfea7..d56cc50f4739c 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -260,3 +260,9 @@ def test_reindex_non_na_fill_value(self, data_missing): expected = pd.Series(data_missing._from_sequence([na, valid, valid])) self.assert_series_equal(result, expected) + + def test_loc_len1(self, data): + # see GH-27785 take_nd with indexer of len 1 resulting in wrong ndim + df = pd.DataFrame({"A": data}) + res = df.loc[[0], "A"] + assert res._data._block.ndim == 1
Manual backport of https://github.com/pandas-dev/pandas/pull/27786, meeseeksdev seemed to be inactive for a moment (PR was properly milestoned).
https://api.github.com/repos/pandas-dev/pandas/pulls/27806
2019-08-07T18:02:30Z
2019-08-07T21:08:37Z
2019-08-07T21:08:37Z
2019-08-07T21:08:37Z
[WIP] Improve CI/CD pipeline performance
diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 263a87176a9c9..5abf809a2d924 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -122,7 +122,7 @@ jobs: - script: | source activate pandas-dev # Next we should simply have `doc/make.py --warnings-are-errors`, everything else is required because the ipython directive doesn't fail the build on errors (https://github.com/ipython/ipython/issues/11547) - doc/make.py --warnings-are-errors | tee sphinx.log ; SPHINX_RET=${PIPESTATUS[0]} + doc/make.py --num-jobs=4 --warnings-are-errors | tee sphinx.log ; SPHINX_RET=${PIPESTATUS[0]} grep -B1 "^<<<-------------------------------------------------------------------------$" sphinx.log ; IPY_RET=$(( $? != 1 )) exit $(( $SPHINX_RET + $IPY_RET )) displayName: 'Build documentation' diff --git a/ci/setup_env.sh b/ci/setup_env.sh index 88742e0483c7e..3cdffc788a99b 100755 --- a/ci/setup_env.sh +++ b/ci/setup_env.sh @@ -116,7 +116,7 @@ conda list pandas # Make sure any error below is reported as such echo "Build extensions and install pandas" -python setup.py build_ext -q --inplace +python setup.py build_ext -q --inplace -j 4 python -m pip install -e . echo diff --git a/doc/source/whatsnew/v0.9.1.rst b/doc/source/whatsnew/v0.9.1.rst index b8932ae2ae522..043c024b72cb0 100644 --- a/doc/source/whatsnew/v0.9.1.rst +++ b/doc/source/whatsnew/v0.9.1.rst @@ -59,7 +59,7 @@ New features .. ipython:: python - df = DataFrame(np.random.randn(5, 3), columns = ['A','B','C']) + df = pd.DataFrame(np.random.randn(5, 3), columns = ['A','B','C']) df
- [X] closes #24028 - [ ] 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/27804
2019-08-07T17:57:37Z
2019-10-22T01:48:03Z
null
2019-10-22T01:48:03Z
REF: Simplify _comp_method_SERIES
diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 4ab1941e3493f..92698fdaccead 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -1029,6 +1029,15 @@ def wrapper(self, other, axis=None): self._get_axis_number(axis) res_name = get_op_result_name(self, other) + other = lib.item_from_zerodim(other) + + # TODO: shouldn't we be applying finalize whenever + # not isinstance(other, ABCSeries)? + finalizer = ( + lambda x: x.__finalize__(self) + if isinstance(other, (np.ndarray, ABCIndexClass)) + else x + ) if isinstance(other, list): # TODO: same for tuples? @@ -1041,11 +1050,18 @@ def wrapper(self, other, axis=None): elif isinstance(other, ABCSeries) and not self._indexed_same(other): raise ValueError("Can only compare identically-labeled Series objects") - elif is_categorical_dtype(self): + elif ( + is_list_like(other) + and len(other) != len(self) + and not isinstance(other, frozenset) + ): + # TODO: why are we treating len-1 frozenset differently? + raise ValueError("Lengths must match to compare") + + if is_categorical_dtype(self): # Dispatch to Categorical implementation; CategoricalIndex # behavior is non-canonical GH#19513 res_values = dispatch_to_extension_op(op, self, other) - return self._constructor(res_values, index=self.index, name=res_name) elif is_datetime64_dtype(self) or is_datetime64tz_dtype(self): # Dispatch to DatetimeIndex to ensure identical @@ -1053,42 +1069,18 @@ def wrapper(self, other, axis=None): from pandas.core.arrays import DatetimeArray res_values = dispatch_to_extension_op(op, DatetimeArray(self), other) - return self._constructor(res_values, index=self.index, name=res_name) elif is_timedelta64_dtype(self): from pandas.core.arrays import TimedeltaArray res_values = dispatch_to_extension_op(op, TimedeltaArray(self), other) - return self._constructor(res_values, index=self.index, name=res_name) elif is_extension_array_dtype(self) or ( is_extension_array_dtype(other) and not is_scalar(other) ): # Note: the `not is_scalar(other)` condition rules out - # e.g. other == "category" + # e.g. other == "category" res_values = dispatch_to_extension_op(op, self, other) - return self._constructor(res_values, index=self.index).rename(res_name) - - elif isinstance(other, ABCSeries): - # By this point we have checked that self._indexed_same(other) - res_values = na_op(self.values, other.values) - # rename is needed in case res_name is None and res_values.name - # is not. - return self._constructor( - res_values, index=self.index, name=res_name - ).rename(res_name) - - elif isinstance(other, (np.ndarray, ABCIndexClass)): - # do not check length of zerodim array - # as it will broadcast - if other.ndim != 0 and len(self) != len(other): - raise ValueError("Lengths must match to compare") - - res_values = na_op(self.values, np.asarray(other)) - result = self._constructor(res_values, index=self.index) - # rename is needed in case res_name is None and self.name - # is not. - return result.__finalize__(self).rename(res_name) elif is_scalar(other) and isna(other): # numpy does not like comparisons vs None @@ -1096,25 +1088,22 @@ def wrapper(self, other, axis=None): res_values = np.ones(len(self), dtype=bool) else: res_values = np.zeros(len(self), dtype=bool) - return self._constructor( - res_values, index=self.index, name=res_name, dtype="bool" - ) else: - values = self.to_numpy() + lvalues = extract_array(self, extract_numpy=True) + rvalues = extract_array(other, extract_numpy=True) with np.errstate(all="ignore"): - res = na_op(values, other) - if is_scalar(res): + res_values = na_op(lvalues, rvalues) + if is_scalar(res_values): raise TypeError( "Could not compare {typ} type with Series".format(typ=type(other)) ) - # always return a full value series here - res_values = extract_array(res, extract_numpy=True) - return self._constructor( - res_values, index=self.index, name=res_name, dtype="bool" - ) + result = self._constructor(res_values, index=self.index) + # rename is needed in case res_name is None and result.name + # is not. + return finalizer(result).rename(res_name) wrapper.__name__ = op_name return wrapper
- Do raising checks earlier on, matching how this is done elsewhere (moving towards #23853) - Comment on line 1034 notes possibly-inconsistent behavior that we should either change or add an explanatory comment for. - Ditto line 1058 - Before long we'll be able to collapse all of the dispatch_to_extension_op cases into one case; I'm still troubleshooting some corner cases of this on another branch. - After this, `na_op` is only called in one place, meaning it will be easier to make further de-nesting/de-closuring simplifications in follow-ups. - Putting all the finalize/_constructor business at the end will make it easier to separate out the array-specific middle and apply it to a) PandasArray and b) Block-wise.
https://api.github.com/repos/pandas-dev/pandas/pulls/27803
2019-08-07T16:04:41Z
2019-08-08T12:35:31Z
2019-08-08T12:35:31Z
2019-08-09T15:39:54Z
ENH: Add argmax and argmin to ExtensionArray
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index cee41f248fc60..38ef1115988b5 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -280,6 +280,7 @@ Other enhancements - :meth:`Styler.highlight_null` now accepts ``subset`` argument (:issue:`31345`) - When writing directly to a sqlite connection :func:`to_sql` now supports the ``multi`` method (:issue:`29921`) - `OptionError` is now exposed in `pandas.errors` (:issue:`27553`) +- Add :meth:`ExtensionArray.argmax` and :meth:`ExtensionArray.argmin` (:issue:`24382`) - :func:`timedelta_range` will now infer a frequency when passed ``start``, ``stop``, and ``periods`` (:issue:`32377`) - Positional slicing on a :class:`IntervalIndex` now supports slices with ``step > 1`` (:issue:`31658`) - :class:`Series.str` now has a `fullmatch` method that matches a regular expression against the entire string in each row of the series, similar to `re.fullmatch` (:issue:`32806`). diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 5565b85f8d59a..32a2a30fcfd43 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -28,7 +28,7 @@ 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 +from pandas.core.sorting import nargminmax, nargsort _extension_array_shared_docs: Dict[str, str] = dict() @@ -533,6 +533,40 @@ def argsort( result = nargsort(self, kind=kind, ascending=ascending, na_position="last") return result + def argmin(self): + """ + Return the index of minimum value. + + In case of multiple occurrences of the minimum value, the index + corresponding to the first occurrence is returned. + + Returns + ------- + int + + See Also + -------- + ExtensionArray.argmax + """ + return nargminmax(self, "argmin") + + def argmax(self): + """ + Return the index of maximum value. + + In case of multiple occurrences of the maximum value, the index + corresponding to the first occurrence is returned. + + Returns + ------- + int + + See Also + -------- + ExtensionArray.argmin + """ + return nargminmax(self, "argmax") + def fillna(self, value=None, method=None, limit=None): """ Fill NA/NaN values using the specified method. diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index da9cbe1023599..ee73aa42701b0 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -319,6 +319,33 @@ def nargsort( return indexer +def nargminmax(values, method: str): + """ + Implementation of np.argmin/argmax but for ExtensionArray and which + handles missing values. + + Parameters + ---------- + values : ExtensionArray + method : {"argmax", "argmin"} + + Returns + ------- + int + """ + assert method in {"argmax", "argmin"} + func = np.argmax if method == "argmax" else np.argmin + + mask = np.asarray(isna(values)) + values = values._values_for_argsort() + + idx = np.arange(len(values)) + non_nans = values[~mask] + non_nan_idx = idx[~mask] + + return non_nan_idx[func(non_nans)] + + def ensure_key_mapped_multiindex(index, key: Callable, level=None): """ Returns a new MultiIndex in which key has been applied diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index 874a8dfd4253f..5e1cf30efd534 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -75,6 +75,42 @@ def test_argsort_missing(self, data_missing_for_sorting): expected = pd.Series(np.array([1, -1, 0], dtype=np.int64)) self.assert_series_equal(result, expected) + def test_argmin_argmax(self, data_for_sorting, data_missing_for_sorting, na_value): + # GH 24382 + + # data_for_sorting -> [B, C, A] with A < B < C + assert data_for_sorting.argmax() == 1 + assert data_for_sorting.argmin() == 2 + + # with repeated values -> first occurence + data = data_for_sorting.take([2, 0, 0, 1, 1, 2]) + assert data.argmax() == 3 + assert data.argmin() == 0 + + # with missing values + # data_missing_for_sorting -> [B, NA, A] with A < B and NA missing. + assert data_missing_for_sorting.argmax() == 0 + assert data_missing_for_sorting.argmin() == 2 + + @pytest.mark.parametrize( + "method", ["argmax", "argmin"], + ) + def test_argmin_argmax_empty_array(self, method, data): + # GH 24382 + err_msg = "attempt to get" + with pytest.raises(ValueError, match=err_msg): + getattr(data[:0], method)() + + @pytest.mark.parametrize( + "method", ["argmax", "argmin"], + ) + def test_argmin_argmax_all_na(self, method, data, na_value): + # all missing with skipna=True is the same as emtpy + err_msg = "attempt to get" + data_na = type(data)._from_sequence([na_value, na_value], dtype=data.dtype) + with pytest.raises(ValueError, match=err_msg): + getattr(data_na, method)() + @pytest.mark.parametrize( "na_position, expected", [ diff --git a/pandas/tests/extension/test_boolean.py b/pandas/tests/extension/test_boolean.py index 725067951eeef..8acbeaf0b8170 100644 --- a/pandas/tests/extension/test_boolean.py +++ b/pandas/tests/extension/test_boolean.py @@ -235,6 +235,23 @@ def test_searchsorted(self, data_for_sorting, as_series): def test_value_counts(self, all_data, dropna): return super().test_value_counts(all_data, dropna) + def test_argmin_argmax(self, data_for_sorting, data_missing_for_sorting): + # override because there are only 2 unique values + + # data_for_sorting -> [B, C, A] with A < B < C -> here True, True, False + assert data_for_sorting.argmax() == 0 + assert data_for_sorting.argmin() == 2 + + # with repeated values -> first occurence + data = data_for_sorting.take([2, 0, 0, 1, 1, 2]) + assert data.argmax() == 1 + assert data.argmin() == 0 + + # with missing values + # data_missing_for_sorting -> [B, NA, A] with A < B and NA missing. + assert data_missing_for_sorting.argmax() == 0 + assert data_missing_for_sorting.argmin() == 2 + class TestCasting(base.BaseCastingTests): pass diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index f318934ef5e52..68e521b005c02 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -321,6 +321,14 @@ def test_shift_0_periods(self, data): data._sparse_values[0] = data._sparse_values[1] assert result._sparse_values[0] != result._sparse_values[1] + @pytest.mark.parametrize( + "method", ["argmax", "argmin"], + ) + def test_argmin_argmax_all_na(self, method, data, na_value): + # overriding because Sparse[int64, 0] cannot handle na_value + self._check_unsupported(data) + super().test_argmin_argmax_all_na(method, data, na_value) + @pytest.mark.parametrize("box", [pd.array, pd.Series, pd.DataFrame]) def test_equals(self, data, na_value, as_series, box): self._check_unsupported(data)
- closes #24382 - tests added - passes `black pandas` - passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - whatsnew entry The methods added in this PR ignore `nan` ,i.e., `skipna=True`. The existing `categorical.min` return `nan` if `categorical` contain any `nan`. This behavior is expected in `test_min_max` (tests/arrays/categorical/test_analytics.py).
https://api.github.com/repos/pandas-dev/pandas/pulls/27801
2019-08-07T14:45:47Z
2020-07-08T14:38:16Z
2020-07-08T14:38:16Z
2020-07-08T14:47:45Z
DOC: add print statement in to_latex example
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 1b39f9225a0ed..0ddb863fa9402 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2993,10 +2993,15 @@ def to_latex( >>> df = pd.DataFrame({'name': ['Raphael', 'Donatello'], ... 'mask': ['red', 'purple'], ... 'weapon': ['sai', 'bo staff']}) - >>> df.to_latex(index=False) # doctest: +NORMALIZE_WHITESPACE - '\\begin{tabular}{lll}\n\\toprule\n name & mask & weapon - \\\\\n\\midrule\n Raphael & red & sai \\\\\n Donatello & - purple & bo staff \\\\\n\\bottomrule\n\\end{tabular}\n' + >>> print(df.to_latex(index=False)) # doctest: +NORMALIZE_WHITESPACE + \begin{tabular}{lll} + \toprule + name & mask & weapon \\ + \midrule + Raphael & red & sai \\ + Donatello & purple & bo staff \\ + \bottomrule + \end{tabular} """ # Get defaults from the pandas config if self.ndim == 1:
changed `df.to_latex` to `print(df.to_latex)` closes #27789
https://api.github.com/repos/pandas-dev/pandas/pulls/27798
2019-08-07T10:05:05Z
2019-08-08T11:42:55Z
2019-08-08T11:42:54Z
2019-08-08T11:43:06Z
DEPR: Remove previously deprecated IntervalIndex.from_intervals
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index bca7bf8cbefbd..f5ca843e1a6f7 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -66,6 +66,7 @@ Removal of prior version deprecations/changes - :meth:`pandas.Series.str.cat` now defaults to aligning ``others``, using ``join='left'`` (:issue:`27611`) - :meth:`pandas.Series.str.cat` does not accept list-likes *within* list-likes anymore (:issue:`27611`) - Removed the previously deprecated :meth:`ExtensionArray._formatting_values`. Use :attr:`ExtensionArray._formatter` instead. (:issue:`23601`) +- Removed the previously deprecated ``IntervalIndex.from_intervals`` in favor of the :class:`IntervalIndex` constructor (:issue:`19263`) .. _whatsnew_1000.performance: diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 2b3c02bd1cade..4ab75090c34d0 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -358,50 +358,6 @@ def from_arrays(cls, left, right, closed="right", copy=False, dtype=None): left, right, closed, copy=copy, dtype=dtype, verify_integrity=True ) - _interval_shared_docs[ - "from_intervals" - ] = """ - Construct an %(klass)s from a 1d array of Interval objects - - .. deprecated:: 0.23.0 - - Parameters - ---------- - data : array-like (1-dimensional) - Array of Interval objects. All intervals must be closed on the same - sides. - copy : boolean, default False - by-default copy the data, this is compat only and ignored - dtype : dtype or None, default None - If None, dtype will be inferred - - ..versionadded:: 0.23.0 - - See Also - -------- - interval_range : Function to create a fixed frequency IntervalIndex. - %(klass)s.from_arrays : Construct an %(klass)s from a left and - right array. - %(klass)s.from_breaks : Construct an %(klass)s from an array of - splits. - %(klass)s.from_tuples : Construct an %(klass)s from an - array-like of tuples. - - Examples - -------- - >>> pd.%(qualname)s.from_intervals([pd.Interval(0, 1), - ... pd.Interval(1, 2)]) - %(klass)s([(0, 1], (1, 2]], - closed='right', dtype='interval[int64]') - - The generic Index constructor work identically when it infers an array - of all intervals: - - >>> pd.Index([pd.Interval(0, 1), pd.Interval(1, 2)]) - %(klass)s([(0, 1], (1, 2]], - closed='right', dtype='interval[int64]') - """ - _interval_shared_docs[ "from_tuples" ] = """ diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 7a444683ffcb2..9361408290bb1 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -269,22 +269,6 @@ def from_arrays( ) return cls._simple_new(array, name=name) - @classmethod - @Appender(_interval_shared_docs["from_intervals"] % _index_doc_kwargs) - def from_intervals(cls, data, closed=None, name=None, copy=False, dtype=None): - msg = ( - "IntervalIndex.from_intervals is deprecated and will be " - "removed in a future version; Use IntervalIndex(...) instead" - ) - warnings.warn(msg, FutureWarning, stacklevel=2) - with rewrite_exception("IntervalArray", cls.__name__): - array = IntervalArray(data, closed=closed, copy=copy, dtype=dtype) - - if name is None and isinstance(data, cls): - name = data.name - - return cls._simple_new(array, name=name) - @classmethod @Appender(_interval_shared_docs["from_tuples"] % _index_doc_kwargs) def from_tuples(cls, data, closed="right", name=None, copy=False, dtype=None): diff --git a/pandas/tests/indexes/interval/test_construction.py b/pandas/tests/indexes/interval/test_construction.py index e2abb4531525a..82a10d24dad30 100644 --- a/pandas/tests/indexes/interval/test_construction.py +++ b/pandas/tests/indexes/interval/test_construction.py @@ -421,32 +421,3 @@ def test_index_mixed_closed(self): result = Index(intervals) expected = Index(intervals, dtype=object) tm.assert_index_equal(result, expected) - - -class TestFromIntervals(TestClassConstructors): - """ - Tests for IntervalIndex.from_intervals, which is deprecated in favor of the - IntervalIndex constructor. Same tests as the IntervalIndex constructor, - plus deprecation test. Should only need to delete this class when removed. - """ - - @pytest.fixture - def constructor(self): - def from_intervals_ignore_warnings(*args, **kwargs): - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - return IntervalIndex.from_intervals(*args, **kwargs) - - return from_intervals_ignore_warnings - - def test_deprecated(self): - ivs = [Interval(0, 1), Interval(1, 2)] - with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): - IntervalIndex.from_intervals(ivs) - - @pytest.mark.skip(reason="parent class test that is not applicable") - def test_index_object_dtype(self): - pass - - @pytest.mark.skip(reason="parent class test that is not applicable") - def test_index_mixed_closed(self): - pass
Didn't see any references to `IntervalIndex.from_intervals` in the docs. We deprecated this before `IntervalArray` was implemented, so no `from_intervals` to worry about there; `IntervalArray` file just has a "shared" docstring for `from_intervals` that isn't actually shared.
https://api.github.com/repos/pandas-dev/pandas/pulls/27793
2019-08-07T05:36:32Z
2019-08-07T13:16:50Z
2019-08-07T13:16:50Z
2019-08-07T14:35:51Z
CLN: remove nested error handling
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 8eea46af2c353..c035e1174bb27 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1366,20 +1366,8 @@ def func(cond, values, other): # np.where will cast integer array to floats in this case other = self._try_coerce_args(other) - try: - fastres = expressions.where(cond, values, other) - return fastres - except Exception as detail: - if errors == "raise": - raise TypeError( - "Could not operate [{other!r}] with block values " - "[{detail!s}]".format(other=other, detail=detail) - ) - else: - # return the values - result = np.empty(values.shape, dtype="float64") - result.fill(np.nan) - return result + fastres = expressions.where(cond, values, other) + return fastres if cond.ravel().all(): result = values
The removed code is not covered in the test suite, so this makes for a nice little simplification. Moreover, since the condition above on 1369-1373 is an ugly one, de-nesting this function will give us a good shot and further simplifying this code. That said, this could be considered an API change, since now the "errors" kwarg doesn't actually do anything.
https://api.github.com/repos/pandas-dev/pandas/pulls/27792
2019-08-07T02:24:52Z
2019-08-07T16:54:43Z
2019-08-07T16:54:43Z
2019-08-07T17:18:46Z
CLN: Assorted Cleanups
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index d22b4bd4d3f2b..69fa956b73f28 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -22,7 +22,6 @@ ensure_int64, ensure_object, ensure_platform_int, - is_categorical, is_categorical_dtype, is_datetime64_dtype, is_datetimelike, @@ -2659,18 +2658,18 @@ def _get_codes_for_values(values, categories): return coerce_indexer_dtype(t.lookup(vals), cats) -def _recode_for_categories(codes, old_categories, new_categories): +def _recode_for_categories(codes: np.ndarray, old_categories, new_categories): """ Convert a set of codes for to a new set of categories Parameters ---------- - codes : array + codes : np.ndarray old_categories, new_categories : Index Returns ------- - new_codes : array + new_codes : np.ndarray[np.int64] Examples -------- @@ -2725,17 +2724,15 @@ def _factorize_from_iterable(values): If `values` has a categorical dtype, then `categories` is a CategoricalIndex keeping the categories and order of `values`. """ - from pandas.core.indexes.category import CategoricalIndex - if not is_list_like(values): raise TypeError("Input must be list-like") - if is_categorical(values): - values = CategoricalIndex(values) - # The CategoricalIndex level we want to build has the same categories + if is_categorical_dtype(values): + values = extract_array(values) + # The Categorical we want to build has the same categories # as values but its codes are by def [0, ..., len(n_categories) - 1] cat_codes = np.arange(len(values.categories), dtype=values.codes.dtype) - categories = values._create_from_codes(cat_codes) + categories = Categorical.from_codes(cat_codes, dtype=values.dtype) codes = values.codes else: # The value of ordered is irrelevant since we don't use cat as such, diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 770870a466aa9..b3548a1dc20d6 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -161,8 +161,8 @@ def strftime(self, date_format): Returns ------- - Index - Index of formatted strings. + ndarray + NumPy ndarray of formatted strings. See Also -------- @@ -180,9 +180,7 @@ def strftime(self, date_format): 'March 10, 2018, 09:00:02 AM'], dtype='object') """ - from pandas import Index - - return Index(self._format_native_types(date_format=date_format)) + return self._format_native_types(date_format=date_format).astype(object) class TimelikeOps: @@ -1018,9 +1016,9 @@ def _add_delta_tdi(self, other): if isinstance(other, np.ndarray): # ndarray[timedelta64]; wrap in TimedeltaIndex for op - from pandas import TimedeltaIndex + from pandas.core.arrays import TimedeltaArray - other = TimedeltaIndex(other) + other = TimedeltaArray._from_sequence(other) self_i8 = self.asi8 other_i8 = other.asi8 diff --git a/pandas/core/arrays/sparse.py b/pandas/core/arrays/sparse.py index 47c7c72051150..476e2aa223d03 100644 --- a/pandas/core/arrays/sparse.py +++ b/pandas/core/arrays/sparse.py @@ -1781,11 +1781,11 @@ def sparse_arithmetic_method(self, other): @classmethod def _create_comparison_method(cls, op): - def cmp_method(self, other): - op_name = op.__name__ + op_name = op.__name__ + if op_name in {"and_", "or_"}: + op_name = op_name[:-1] - if op_name in {"and_", "or_"}: - op_name = op_name[:-1] + def cmp_method(self, other): if isinstance(other, (ABCSeries, ABCIndexClass)): # Rely on pandas to unbox and dispatch to us. diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 67de7b0196b8e..9f2b31f23d2fa 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -69,7 +69,7 @@ class DatetimeDelegateMixin(DatetimelikeDelegateMixin): # Some are "raw" methods, the result is not not re-boxed in an Index # We also have a few "extra" attrs, which may or may not be raw, # which we we dont' want to expose in the .dt accessor. - _extra_methods = ["to_period", "to_perioddelta", "to_julian_date"] + _extra_methods = ["to_period", "to_perioddelta", "to_julian_date", "strftime"] _extra_raw_methods = ["to_pydatetime", "_local_timestamps", "_has_same_tz"] _extra_raw_properties = ["_box_func", "tz", "tzinfo"] _delegated_properties = DatetimeArray._datetimelike_ops + _extra_raw_properties @@ -1184,7 +1184,6 @@ def slice_indexer(self, start=None, end=None, step=None, kind=None): is_normalized = cache_readonly(DatetimeArray.is_normalized.fget) # type: ignore _resolution = cache_readonly(DatetimeArray._resolution.fget) # type: ignore - strftime = ea_passthrough(DatetimeArray.strftime) _has_same_tz = ea_passthrough(DatetimeArray._has_same_tz) @property diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index f6b3d1076043e..b0cc386f7783d 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -63,7 +63,10 @@ class PeriodDelegateMixin(DatetimelikeDelegateMixin): _delegate_class = PeriodArray _delegated_properties = PeriodArray._datetimelike_ops - _delegated_methods = set(PeriodArray._datetimelike_methods) | {"_addsub_int_array"} + _delegated_methods = set(PeriodArray._datetimelike_methods) | { + "_addsub_int_array", + "strftime", + } _raw_properties = {"is_leap_year"} diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index abc8a414eb37a..6af5dd6f1bf37 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -3202,7 +3202,9 @@ def read(self, start=None, stop=None, **kwargs): values = self.read_array( "block{idx}_values".format(idx=i), start=_start, stop=_stop ) - blk = make_block(values, placement=items.get_indexer(blk_items)) + blk = make_block( + values, placement=items.get_indexer(blk_items), ndim=len(axes) + ) blocks.append(blk) return self.obj_type(BlockManager(blocks, axes)) @@ -4462,7 +4464,7 @@ def read(self, where=None, columns=None, **kwargs): if values.ndim == 1 and isinstance(values, np.ndarray): values = values.reshape((1, values.shape[0])) - block = make_block(values, placement=np.arange(len(cols_))) + block = make_block(values, placement=np.arange(len(cols_)), ndim=2) mgr = BlockManager([block], [cols_, index_]) frames.append(DataFrame(mgr)) diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index ffda2f4de2700..0b3ccc0ae0e2d 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -462,6 +462,13 @@ def test_concat_same_type_different_freq(self): tm.assert_datetime_array_equal(result, expected) + def test_strftime(self, datetime_index): + arr = DatetimeArray(datetime_index) + + result = arr.strftime("%Y %b") + expected = np.array(datetime_index.strftime("%Y %b")) + tm.assert_numpy_array_equal(result, expected) + class TestTimedeltaArray(SharedTests): index_cls = pd.TimedeltaIndex @@ -652,6 +659,13 @@ def test_array_interface(self, period_index): expected = np.asarray(arr).astype("S20") tm.assert_numpy_array_equal(result, expected) + def test_strftime(self, period_index): + arr = PeriodArray(period_index) + + result = arr.strftime("%Y") + expected = np.array(period_index.strftime("%Y")) + tm.assert_numpy_array_equal(result, expected) + @pytest.mark.parametrize( "array,casting_nats", diff --git a/pandas/tests/arrays/test_integer.py b/pandas/tests/arrays/test_integer.py index 8fbfb4c12f4b2..50cd1469e5196 100644 --- a/pandas/tests/arrays/test_integer.py +++ b/pandas/tests/arrays/test_integer.py @@ -379,8 +379,6 @@ def test_compare_array(self, data, all_compare_operators): class TestCasting: - pass - @pytest.mark.parametrize("dropna", [True, False]) def test_construct_index(self, all_data, dropna): # ensure that we do not coerce to Float64Index, rather diff --git a/pandas/tests/series/test_period.py b/pandas/tests/series/test_period.py index 9b34b52bf39b9..4aeb211170d8f 100644 --- a/pandas/tests/series/test_period.py +++ b/pandas/tests/series/test_period.py @@ -71,10 +71,9 @@ def test_NaT_scalar(self): series[2] = val assert pd.isna(series[2]) - @pytest.mark.xfail(reason="PeriodDtype Series not supported yet") def test_NaT_cast(self): result = Series([np.nan]).astype("period[D]") - expected = Series([pd.NaT]) + expected = Series([pd.NaT], dtype="period[D]") tm.assert_series_equal(result, expected) def test_set_none(self):
- make PTA/DTA strftime() return ndarray instead of Index - fix a xfailed Series[Period] test - avoid imports of Index subclass in arrays.categorical and arrays.datetimelike - some typing
https://api.github.com/repos/pandas-dev/pandas/pulls/27791
2019-08-06T23:23:59Z
2019-08-08T12:37:41Z
2019-08-08T12:37:41Z
2019-08-08T13:33:19Z
BUG: Increase range of dates for holiday calculations
diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 48c1173a372a7..78ebdb985edad 100644 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -409,6 +409,9 @@ Other - Bug in :meth:`Series.diff` where a boolean series would incorrectly raise a ``TypeError`` (:issue:`17294`) - :meth:`Series.append` will no longer raise a ``TypeError`` when passed a tuple of ``Series`` (:issue:`28410`) - Fix corrupted error message when calling ``pandas.libs._json.encode()`` on a 0d array (:issue:`18878`) +- Fix :class:`AbstractHolidayCalendar` to return correct results for + years after 2030 (now goes up to 2200) (:issue:`27790`) + .. _whatsnew_1000.contributors: diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 5391cb5ce821f..0e30b104bf9d2 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -784,7 +784,8 @@ def test_categorical_no_compress(): def test_sort(): - # http://stackoverflow.com/questions/23814368/sorting-pandas-categorical-labels-after-groupby # noqa: E501 + # http://stackoverflow.com/questions/23814368/sorting-pandas- + # categorical-labels-after-groupby # This should result in a properly sorted Series so that the plot # has a sorted x axis # self.cat.groupby(['value_group'])['value_group'].count().plot(kind='bar') diff --git a/pandas/tests/tseries/holiday/test_calendar.py b/pandas/tests/tseries/holiday/test_calendar.py index 79c28942769f0..c122f92ed228c 100644 --- a/pandas/tests/tseries/holiday/test_calendar.py +++ b/pandas/tests/tseries/holiday/test_calendar.py @@ -2,7 +2,7 @@ import pytest -from pandas import DatetimeIndex +from pandas import DatetimeIndex, offsets, to_datetime import pandas.util.testing as tm from pandas.tseries.holiday import ( @@ -10,6 +10,7 @@ Holiday, Timestamp, USFederalHolidayCalendar, + USLaborDay, USThanksgivingDay, get_calendar, ) @@ -81,3 +82,19 @@ def test_calendar_observance_dates(): def test_rule_from_name(): us_fed_cal = get_calendar("USFederalHolidayCalendar") assert us_fed_cal.rule_from_name("Thanksgiving") == USThanksgivingDay + + +def test_calendar_2031(): + # See gh-27790 + # + # Labor Day 2031 is on September 1. Saturday before is August 30. + # Next working day after August 30 ought to be Tuesday, September 2. + + class testCalendar(AbstractHolidayCalendar): + rules = [USLaborDay] + + cal = testCalendar() + workDay = offsets.CustomBusinessDay(calendar=cal) + Sat_before_Labor_Day_2031 = to_datetime("2031-08-30") + next_working_day = Sat_before_Labor_Day_2031 + 0 * workDay + assert next_working_day == to_datetime("2031-09-02") diff --git a/pandas/tseries/holiday.py b/pandas/tseries/holiday.py index 1654163d2a9e0..eb8600031439f 100644 --- a/pandas/tseries/holiday.py +++ b/pandas/tseries/holiday.py @@ -346,7 +346,7 @@ class AbstractHolidayCalendar(metaclass=HolidayCalendarMetaClass): rules = [] # type: List[Holiday] start_date = Timestamp(datetime(1970, 1, 1)) - end_date = Timestamp(datetime(2030, 12, 31)) + end_date = Timestamp(datetime(2200, 12, 31)) _cache = None def __init__(self, name=None, rules=None):
- [x] closes #27761 - [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/27790
2019-08-06T20:39:12Z
2019-10-24T00:04:13Z
2019-10-24T00:04:13Z
2019-10-24T01:58:44Z
TST: Add tests for groupby categorical values with axis=1
diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index ce724f5a60beb..756de3edd33dd 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -1163,3 +1163,13 @@ def test_seriesgroupby_observed_apply_dict(df_cat, observed, index, data): lambda x: OrderedDict([("min", x.min()), ("max", x.max())]) ) assert_series_equal(result, expected) + + +@pytest.mark.parametrize("code", [([1, 0, 0]), ([0, 0, 0])]) +def test_groupby_categorical_axis_1(code): + # GH 13420 + df = DataFrame({"a": [1, 2, 3, 4], "b": [-1, -2, -3, -4], "c": [5, 6, 7, 8]}) + cat = pd.Categorical.from_codes(code, categories=list("abc")) + result = df.groupby(cat, axis=1).mean() + expected = df.T.groupby(cat, axis=0).mean().T + assert_frame_equal(result, expected)
This is xref https://github.com/pandas-dev/pandas/pull/27700#issuecomment-517703401 - [x] closes #13420 - [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/27788
2019-08-06T20:05:29Z
2019-08-07T13:57:34Z
2019-08-07T13:57:33Z
2019-08-07T13:57:41Z
Fix miniconda path issue #26962
diff --git a/azure-pipelines.yml b/azure-pipelines.yml index cfd7f6546833d..263a87176a9c9 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -22,22 +22,17 @@ jobs: timeoutInMinutes: 90 steps: - script: | - # XXX next command should avoid redefining the path in every step, but - # made the process crash as it couldn't find deactivate - #echo '##vso[task.prependpath]$HOME/miniconda3/bin' + echo '##vso[task.prependpath]$(HOME)/miniconda3/bin' echo '##vso[task.setvariable variable=ENV_FILE]environment.yml' echo '##vso[task.setvariable variable=AZURE]true' displayName: 'Setting environment variables' # Do not require a conda environment - - script: | - export PATH=$HOME/miniconda3/bin:$PATH - ci/code_checks.sh patterns + - script: ci/code_checks.sh patterns displayName: 'Looking for unwanted patterns' condition: true - script: | - export PATH=$HOME/miniconda3/bin:$PATH sudo apt-get install -y libc6-dev-i386 ci/setup_env.sh displayName: 'Setup environment and build pandas' @@ -45,14 +40,12 @@ jobs: # Do not require pandas - script: | - export PATH=$HOME/miniconda3/bin:$PATH source activate pandas-dev ci/code_checks.sh lint displayName: 'Linting' condition: true - script: | - export PATH=$HOME/miniconda3/bin:$PATH source activate pandas-dev ci/code_checks.sh dependencies displayName: 'Dependencies consistency' @@ -60,42 +53,36 @@ jobs: # Require pandas - script: | - export PATH=$HOME/miniconda3/bin:$PATH source activate pandas-dev ci/code_checks.sh code displayName: 'Checks on imported code' condition: true - script: | - export PATH=$HOME/miniconda3/bin:$PATH source activate pandas-dev ci/code_checks.sh doctests displayName: 'Running doctests' condition: true - script: | - export PATH=$HOME/miniconda3/bin:$PATH source activate pandas-dev ci/code_checks.sh docstrings displayName: 'Docstring validation' condition: true - script: | - export PATH=$HOME/miniconda3/bin:$PATH source activate pandas-dev ci/code_checks.sh typing displayName: 'Typing validation' condition: true - script: | - export PATH=$HOME/miniconda3/bin:$PATH source activate pandas-dev pytest --capture=no --strict scripts - displayName: 'Testing docstring validaton script' + displayName: 'Testing docstring validation script' condition: true - script: | - export PATH=$HOME/miniconda3/bin:$PATH source activate pandas-dev cd asv_bench asv check -E existing @@ -124,16 +111,15 @@ jobs: steps: - script: | echo '##vso[task.setvariable variable=ENV_FILE]environment.yml' + echo '##vso[task.prependpath]$(HOME)/miniconda3/bin' displayName: 'Setting environment variables' - script: | - export PATH=$HOME/miniconda3/bin:$PATH sudo apt-get install -y libc6-dev-i386 ci/setup_env.sh displayName: 'Setup environment and build pandas' - script: | - export PATH=$HOME/miniconda3/bin:$PATH source activate pandas-dev # Next we should simply have `doc/make.py --warnings-are-errors`, everything else is required because the ipython directive doesn't fail the build on errors (https://github.com/ipython/ipython/issues/11547) doc/make.py --warnings-are-errors | tee sphinx.log ; SPHINX_RET=${PIPESTATUS[0]} diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml index 39f862290e720..6093df46ffb60 100644 --- a/ci/azure/posix.yml +++ b/ci/azure/posix.yml @@ -56,17 +56,15 @@ jobs: steps: - script: | if [ "$(uname)" == "Linux" ]; then sudo apt-get install -y libc6-dev-i386 $EXTRA_APT; fi + echo '##vso[task.prependpath]$(HOME)/miniconda3/bin' echo "Creating Environment" ci/setup_env.sh displayName: 'Setup environment and build pandas' - script: | - export PATH=$HOME/miniconda3/bin:$PATH source activate pandas-dev ci/run_tests.sh displayName: 'Test' - - script: | - export PATH=$HOME/miniconda3/bin:$PATH - source activate pandas-dev && pushd /tmp && python -c "import pandas; pandas.show_versions();" && popd + - script: source activate pandas-dev && pushd /tmp && python -c "import pandas; pandas.show_versions();" && popd - task: PublishTestResults@2 inputs: testResultsFiles: 'test-data-*.xml' @@ -97,7 +95,6 @@ jobs: } displayName: 'Check for test failures' - script: | - export PATH=$HOME/miniconda3/bin:$PATH source activate pandas-dev python ci/print_skipped.py displayName: 'Print skipped tests' diff --git a/ci/azure/windows.yml b/ci/azure/windows.yml index 20cad1bb4af96..dfa82819b9826 100644 --- a/ci/azure/windows.yml +++ b/ci/azure/windows.yml @@ -17,7 +17,9 @@ jobs: CONDA_PY: "37" steps: - - powershell: Write-Host "##vso[task.prependpath]$env:CONDA\Scripts" + - powershell: | + Write-Host "##vso[task.prependpath]$env:CONDA\Scripts" + Write-Host "##vso[task.prependpath]$HOME/miniconda3/bin" displayName: 'Add conda to PATH' - script: conda update -q -n base conda displayName: Update conda @@ -52,7 +54,6 @@ jobs: } displayName: 'Check for test failures' - script: | - export PATH=$HOME/miniconda3/bin:$PATH source activate pandas-dev python ci/print_skipped.py displayName: 'Print skipped tests'
- [x] closes #26962 - [ ] 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/27787
2019-08-06T19:24:35Z
2019-08-07T09:38:42Z
2019-08-07T09:38:42Z
2019-12-23T16:13:05Z
BUG: fix construction of NonConsolidatableBlock with inconsistent ndim
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 8c3cf7cc51495..982b3655650fc 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -273,6 +273,8 @@ def make_block_same_class(self, values, placement=None, ndim=None, dtype=None): ) if placement is None: placement = self.mgr_locs + if ndim is None: + ndim = self.ndim return make_block( values, placement=placement, ndim=ndim, klass=self.__class__, dtype=dtype ) diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index e02586eacfea7..d56cc50f4739c 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -260,3 +260,9 @@ def test_reindex_non_na_fill_value(self, data_missing): expected = pd.Series(data_missing._from_sequence([na, valid, valid])) self.assert_series_equal(result, expected) + + def test_loc_len1(self, data): + # see GH-27785 take_nd with indexer of len 1 resulting in wrong ndim + df = pd.DataFrame({"A": data}) + res = df.loc[[0], "A"] + assert res._data._block.ndim == 1
- [x] closes #27785 - [ ] 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/27786
2019-08-06T18:56:26Z
2019-08-07T13:25:37Z
2019-08-07T13:25:37Z
2019-08-07T17:50:41Z
ENH: allow object-dtype Index to do arithmetic ops
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 356ae20b2240a..4694ffd160ce6 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -5603,7 +5603,7 @@ def shape(self): return (len(self),) -Index._add_numeric_methods_disabled() +Index._add_numeric_methods_binary() Index._add_logical_methods() Index._add_comparison_methods() diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index 4ab1941e3493f..1f155b1e27e0d 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -432,6 +432,10 @@ def masked_arith_op(x, y, op): result[mask] = op(xrav[mask], yrav[mask]) else: + if isinstance(y, list): + # reached via pandas/tests/arithmetic/test_object.py test_sub_fail + raise TypeError("Invalid operand type for {op}".format(op=op)) + assert is_scalar(y), type(y) assert isinstance(x, np.ndarray), type(x) # mask is only meaningful for x diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py index 2b23790e4ccd3..1141a2965fc3b 100644 --- a/pandas/tests/arithmetic/test_numeric.py +++ b/pandas/tests/arithmetic/test_numeric.py @@ -507,20 +507,6 @@ class TestMultiplicationDivision: # __mul__, __rmul__, __div__, __rdiv__, __floordiv__, __rfloordiv__ # for non-timestamp/timedelta/period dtypes - @pytest.mark.parametrize( - "box", - [ - pytest.param( - pd.Index, - marks=pytest.mark.xfail( - reason="Index.__div__ always raises", raises=TypeError - ), - ), - pd.Series, - pd.DataFrame, - ], - ids=lambda x: x.__name__, - ) def test_divide_decimal(self, box): # resolves issue GH#9787 ser = Series([Decimal(10)]) diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index 9459069f0ea2d..222502463dff7 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -168,21 +168,31 @@ def test_create_index_existing_name(self): def test_numeric_compat(self): idx = self.create_index() - with pytest.raises(TypeError, match="cannot perform __mul__"): - idx * 1 - with pytest.raises(TypeError, match="cannot perform __rmul__"): - 1 * idx + if isinstance( + idx, + (IntervalIndex, CategoricalIndex, MultiIndex, PeriodIndex, DatetimeIndex), + ): + err_msg = "cannot perform __r?mul__|unsupported operand type" + with pytest.raises(TypeError, match=err_msg): + idx * 1 + with pytest.raises(TypeError, match=err_msg): + 1 * idx + else: + result = idx * 1 + tm.assert_index_equal(result, idx) + result = 1 * idx + tm.assert_index_equal(result, idx) - div_err = "cannot perform __truediv__" + div_err = "cannot perform __[a-z]+__|unsupported operand type" with pytest.raises(TypeError, match=div_err): idx / 1 - div_err = div_err.replace(" __", " __r") - with pytest.raises(TypeError, match=div_err): + div_err = div_err + "|division by zero|division or modulo by zero" + with pytest.raises((ZeroDivisionError, TypeError), match=div_err): 1 / idx - with pytest.raises(TypeError, match="cannot perform __floordiv__"): + with pytest.raises((ZeroDivisionError, TypeError), match=div_err): idx // 1 - with pytest.raises(TypeError, match="cannot perform __rfloordiv__"): + with pytest.raises((ZeroDivisionError, TypeError), match=div_err): 1 // idx def test_logical_compat(self):
Implement ops in the base Index class to work the same as Series versions.
https://api.github.com/repos/pandas-dev/pandas/pulls/27784
2019-08-06T17:41:09Z
2019-08-13T00:08:40Z
null
2019-08-14T15:11:00Z
Backport PR #27663 on branch 0.25.x (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 23bf89b2bc1ac..3d93042486c8a 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -615,13 +615,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) @@ -631,11 +639,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() @@ -645,13 +655,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)
Backport PR #27663: BUG: pd.crosstab not working when margin and normalize are set together
https://api.github.com/repos/pandas-dev/pandas/pulls/27783
2019-08-06T15:45:42Z
2019-08-07T03:51:51Z
2019-08-07T03:51:51Z
2019-08-07T03:51:51Z