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
CI: Sync web and dev docs automatically with prod server
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 025b6f1813df7..1b9d28b4f2d69 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -125,32 +125,18 @@ jobs: - name: Check ipython directive errors run: "! grep -B1 \"^<<<-------------------------------------------------------------------------$\" sphinx.log" - - name: Install Rclone - run: sudo apt install rclone -y - if: github.event_name == 'push' - - - name: Set up Rclone + - name: Install ssh key run: | - CONF=$HOME/.config/rclone/rclone.conf - mkdir -p `dirname $CONF` - echo "[ovh_host]" > $CONF - echo "type = swift" >> $CONF - echo "env_auth = false" >> $CONF - echo "auth_version = 3" >> $CONF - echo "auth = https://auth.cloud.ovh.net/v3/" >> $CONF - echo "endpoint_type = public" >> $CONF - echo "tenant_domain = default" >> $CONF - echo "tenant = 2977553886518025" >> $CONF - echo "domain = default" >> $CONF - echo "user = w4KGs3pmDxpd" >> $CONF - echo "key = ${{ secrets.ovh_object_store_key }}" >> $CONF - echo "region = BHS" >> $CONF + mkdir -m 700 -p ~/.ssh + echo "${{ secrets.server_ssh_key }}" > ~/.ssh/id_rsa + chmod 600 ~/.ssh/id_rsa + echo "${{ secrets.server_ip }} ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBE1Kkopomm7FHG5enATf7SgnpICZ4W2bw+Ho+afqin+w7sMcrsa0je7sbztFAV8YchDkiBKnWTG4cRT+KZgZCaY=" > ~/.ssh/known_hosts if: github.event_name == 'push' - - name: Sync web with OVH - run: rclone sync --exclude pandas-docs/** web/build ovh_host:prod + - name: Upload web + run: rsync -az --delete --exclude='pandas-docs' --exclude='Pandas_Cheat_Sheet*' web/build/ docs@${{ secrets.server_ip }}:/usr/share/nginx/pandas if: github.event_name == 'push' - - name: Sync dev docs with OVH - run: rclone sync doc/build/html ovh_host:prod/pandas-docs/dev + - name: Upload dev docs + run: rsync -az --delete doc/build/html/ docs@${{ secrets.server_ip }}:/usr/share/nginx/pandas/pandas-docs/dev if: github.event_name == 'push'
- [X] closes #28528 This forgets about the OVH server, and after every merge to master will synchronize the repo web and docs in the production server. **Note** that this will delete any file in the server that is not known, except the cheat sheets, and all the docs versions in `pandas-doc`. I don't think anything else should be kept, but if there is anything else that we upload manually, please let me know. I made a backup in the server, so if we delete anything by accident with this, it can be easily restored. CC: @TomAugspurger @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/33341
2020-04-06T21:35:09Z
2020-04-07T11:57:42Z
2020-04-07T11:57:42Z
2020-04-07T11:57:43Z
REF: replace column-wise, remove BlockManager.apply filter kwarg
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index aedbba755227d..d2da52ba7bdd0 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4025,6 +4025,41 @@ def replace( method=method, ) + def _replace_columnwise( + self, mapping: Dict[Label, Tuple[Any, Any]], inplace: bool, regex + ): + """ + Dispatch to Series.replace column-wise. + + + Parameters + ---------- + mapping : dict + of the form {col: (target, value)} + inplace : bool + regex : bool or same types as `to_replace` in DataFrame.replace + + Returns + ------- + DataFrame or None + """ + # Operate column-wise + res = self if inplace else self.copy() + ax = self.columns + + for i in range(len(ax)): + if ax[i] in mapping: + ser = self.iloc[:, i] + + target, value = mapping[ax[i]] + newobj = ser.replace(target, value, regex=regex) + + res.iloc[:, i] = newobj + + if inplace: + return + return res.__finalize__(self) + @Appender(_shared_docs["shift"] % _shared_doc_kwargs) def shift(self, periods=1, freq=None, axis=0, fill_value=None) -> "DataFrame": return super().shift( diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 052a4adddca27..a36aca5ea7f1c 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6468,7 +6468,6 @@ def replace( ): if not ( is_scalar(to_replace) - or isinstance(to_replace, pd.Series) or is_re_compilable(to_replace) or is_list_like(to_replace) ): @@ -6559,18 +6558,16 @@ def replace( # {'A': NA} -> 0 elif not is_list_like(value): - keys = [(k, src) for k, src in to_replace.items() if k in self] - keys_len = len(keys) - 1 - for i, (k, src) in enumerate(keys): - convert = i == keys_len - new_data = new_data.replace( - to_replace=src, - value=value, - filter=[k], - inplace=inplace, - regex=regex, - convert=convert, + # Operate column-wise + if self.ndim == 1: + raise ValueError( + "Series.replace cannot use dict-like to_replace " + "and non-None value" ) + mapping = { + col: (to_rep, value) for col, to_rep in to_replace.items() + } + return self._replace_columnwise(mapping, inplace, regex) else: raise TypeError("value argument must be scalar, dict, or Series") @@ -6611,17 +6608,14 @@ def replace( # dest iterable dict-like if is_dict_like(value): # NA -> {'A' : 0, 'B' : -1} - new_data = self._mgr - - for k, v in value.items(): - if k in self: - new_data = new_data.replace( - to_replace=to_replace, - value=v, - filter=[k], - inplace=inplace, - regex=regex, - ) + # Operate column-wise + if self.ndim == 1: + raise ValueError( + "Series.replace cannot use dict-value and " + "non-None to_replace" + ) + mapping = {col: (to_replace, val) for col, val in value.items()} + return self._replace_columnwise(mapping, inplace, regex) elif not is_list_like(value): # NA -> 0 new_data = self._mgr.replace( diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index ba2fd037901a2..d22209e61df0c 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -679,7 +679,6 @@ def replace( to_replace, value, inplace: bool = False, - filter=None, regex: bool = False, convert: bool = True, ): @@ -711,12 +710,7 @@ def replace( # _can_hold_element checks have reduced this back to the # scalar case and we can avoid a costly object cast return self.replace( - to_replace[0], - value, - inplace=inplace, - filter=filter, - regex=regex, - convert=convert, + to_replace[0], value, inplace=inplace, regex=regex, convert=convert, ) # GH 22083, TypeError or ValueError occurred within error handling @@ -730,7 +724,6 @@ def replace( to_replace=to_replace, value=value, inplace=inplace, - filter=filter, regex=regex, convert=convert, ) @@ -743,9 +736,6 @@ def replace( to_replace = convert_scalar_for_putitemlike(to_replace, values.dtype) mask = missing.mask_missing(values, to_replace) - if filter is not None: - filtered_out = ~self.mgr_locs.isin(filter) - mask[filtered_out.nonzero()[0]] = False if not mask.any(): if inplace: @@ -774,7 +764,6 @@ def replace( to_replace=original_to_replace, value=value, inplace=inplace, - filter=filter, regex=regex, convert=convert, ) @@ -2374,20 +2363,13 @@ def _can_hold_element(self, element: Any) -> bool: return issubclass(tipo.type, np.bool_) return isinstance(element, (bool, np.bool_)) - def replace( - self, to_replace, value, inplace=False, filter=None, regex=False, convert=True - ): + def replace(self, to_replace, value, inplace=False, regex=False, convert=True): inplace = validate_bool_kwarg(inplace, "inplace") to_replace_values = np.atleast_1d(to_replace) if not np.can_cast(to_replace_values, bool): return self return super().replace( - to_replace, - value, - inplace=inplace, - filter=filter, - regex=regex, - convert=convert, + to_replace, value, inplace=inplace, regex=regex, convert=convert, ) @@ -2461,9 +2443,7 @@ def _maybe_downcast(self, blocks: List["Block"], downcast=None) -> List["Block"] def _can_hold_element(self, element: Any) -> bool: return True - def replace( - self, to_replace, value, inplace=False, filter=None, regex=False, convert=True - ): + def replace(self, to_replace, value, inplace=False, regex=False, convert=True): to_rep_is_list = is_list_like(to_replace) value_is_list = is_list_like(value) both_lists = to_rep_is_list and value_is_list @@ -2474,33 +2454,18 @@ def replace( if not either_list and is_re(to_replace): return self._replace_single( - to_replace, - value, - inplace=inplace, - filter=filter, - regex=True, - convert=convert, + to_replace, value, inplace=inplace, regex=True, convert=convert, ) elif not (either_list or regex): return super().replace( - to_replace, - value, - inplace=inplace, - filter=filter, - regex=regex, - convert=convert, + to_replace, value, inplace=inplace, regex=regex, convert=convert, ) elif both_lists: for to_rep, v in zip(to_replace, value): result_blocks = [] for b in blocks: result = b._replace_single( - to_rep, - v, - inplace=inplace, - filter=filter, - regex=regex, - convert=convert, + to_rep, v, inplace=inplace, regex=regex, convert=convert, ) result_blocks = _extend_blocks(result, result_blocks) blocks = result_blocks @@ -2511,35 +2476,18 @@ def replace( result_blocks = [] for b in blocks: result = b._replace_single( - to_rep, - value, - inplace=inplace, - filter=filter, - regex=regex, - convert=convert, + to_rep, value, inplace=inplace, regex=regex, convert=convert, ) result_blocks = _extend_blocks(result, result_blocks) blocks = result_blocks return result_blocks return self._replace_single( - to_replace, - value, - inplace=inplace, - filter=filter, - convert=convert, - regex=regex, + to_replace, value, inplace=inplace, convert=convert, regex=regex, ) def _replace_single( - self, - to_replace, - value, - inplace=False, - filter=None, - regex=False, - convert=True, - mask=None, + self, to_replace, value, inplace=False, regex=False, convert=True, mask=None, ): """ Replace elements by the given value. @@ -2552,7 +2500,6 @@ def _replace_single( Replacement object. inplace : bool, default False Perform inplace modification. - filter : list, optional regex : bool, default False If true, perform regular expression substitution. convert : bool, default True @@ -2598,9 +2545,7 @@ def _replace_single( else: # if the thing to replace is not a string or compiled regex call # the superclass method -> to_replace is some kind of object - return super().replace( - to_replace, value, inplace=inplace, filter=filter, regex=regex - ) + return super().replace(to_replace, value, inplace=inplace, regex=regex) new_values = self.values if inplace else self.values.copy() @@ -2625,15 +2570,10 @@ def re_replacer(s): f = np.vectorize(re_replacer, otypes=[self.dtype]) - if filter is None: - filt = slice(None) - else: - filt = self.mgr_locs.isin(filter).nonzero()[0] - if mask is None: - new_values[filt] = f(new_values[filt]) + new_values[:] = f(new_values) else: - new_values[filt][mask] = f(new_values[filt][mask]) + new_values[mask] = f(new_values[mask]) # convert block = self.make_block(new_values) @@ -2730,7 +2670,6 @@ def replace( to_replace, value, inplace: bool = False, - filter=None, regex: bool = False, convert: bool = True, ): diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index e2c9212ae9576..f241410b25a82 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -369,7 +369,7 @@ def reduce(self, func, *args, **kwargs): return res - def apply(self: T, f, filter=None, align_keys=None, **kwargs) -> T: + def apply(self: T, f, align_keys=None, **kwargs) -> T: """ Iterate over the blocks, collect and create a new BlockManager. @@ -377,26 +377,17 @@ def apply(self: T, f, filter=None, align_keys=None, **kwargs) -> T: ---------- f : str or callable Name of the Block method to apply. - filter : list, if supplied, only call the block if the filter is in - the block Returns ------- BlockManager """ + assert "filter" not in kwargs + align_keys = align_keys or [] - result_blocks = [] + result_blocks: List[Block] = [] # fillna: Series/DataFrame is responsible for making sure value is aligned - # filter kwarg is used in replace-* family of methods - if filter is not None: - filter_locs = set(self.items.get_indexer_for(filter)) - if len(filter_locs) == len(self.items): - # All items are included, as if there were no filtering - filter = None - else: - kwargs["filter"] = filter_locs - self._consolidate_inplace() align_copy = False @@ -410,10 +401,6 @@ def apply(self: T, f, filter=None, align_keys=None, **kwargs) -> T: } for b in self.blocks: - if filter is not None: - if not b.mgr_locs.isin(filter_locs).any(): - result_blocks.append(b) - continue if aligned_args: b_items = self.items[b.mgr_locs.indexer] diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index 904a455870ab1..bea8cb8b105e7 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -373,3 +373,19 @@ def test_replace_invalid_to_replace(self): ) with pytest.raises(TypeError, match=msg): series.replace(lambda x: x.strip()) + + def test_replace_only_one_dictlike_arg(self): + # GH#33340 + + ser = pd.Series([1, 2, "A", pd.Timestamp.now(), True]) + to_replace = {0: 1, 2: "A"} + value = "foo" + msg = "Series.replace cannot use dict-like to_replace and non-None value" + with pytest.raises(ValueError, match=msg): + ser.replace(to_replace, value) + + to_replace = 1 + value = {0: "foo", 2: "bar"} + msg = "Series.replace cannot use dict-value and non-None to_replace" + with pytest.raises(ValueError, match=msg): + ser.replace(to_replace, value)
Follow-up to #33279.
https://api.github.com/repos/pandas-dev/pandas/pulls/33340
2020-04-06T21:27:05Z
2020-04-08T17:29:28Z
2020-04-08T17:29:28Z
2020-04-08T17:33:31Z
BUG: Don't raise on value_counts for empty Int64
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 7cb7db27ae603..6ec02a108a879 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -461,7 +461,7 @@ Sparse ExtensionArray ^^^^^^^^^^^^^^ -- +- Fixed bug where :meth:`Serires.value_counts` would raise on empty input of ``Int64`` dtype (:issue:`33317`) - diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 4f3c68aa03b16..f5189068d5da1 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -499,7 +499,8 @@ def _values_for_argsort(self) -> np.ndarray: ExtensionArray.argsort """ data = self._data.copy() - data[self._mask] = data.min() - 1 + if self._mask.any(): + data[self._mask] = data.min() - 1 return data @classmethod diff --git a/pandas/tests/arrays/integer/test_function.py b/pandas/tests/arrays/integer/test_function.py index 58913189593a9..bdf902d1aca62 100644 --- a/pandas/tests/arrays/integer/test_function.py +++ b/pandas/tests/arrays/integer/test_function.py @@ -103,6 +103,16 @@ def test_value_counts_na(): tm.assert_series_equal(result, expected) +def test_value_counts_empty(): + # https://github.com/pandas-dev/pandas/issues/33317 + s = pd.Series([], dtype="Int64") + result = s.value_counts() + # TODO: The dtype of the index seems wrong (it's int64 for non-empty) + idx = pd.Index([], dtype="object") + expected = pd.Series([], index=idx, dtype="Int64") + tm.assert_series_equal(result, expected) + + # TODO(jreback) - these need testing / are broken # shift
- [ ] closes #33317 - [ ] 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/33339
2020-04-06T21:02:15Z
2020-04-06T21:58:59Z
2020-04-06T21:58:59Z
2020-04-06T22:17:45Z
DOC/PLT: Add `stacked` in doc and doc example for barh and bar plot
diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index e466a215091ea..b3c4d3138e915 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -985,6 +985,13 @@ def line(self, x=None, y=None, **kwargs): ... 'lifespan': lifespan}, index=index) >>> ax = df.plot.bar(rot=0) + Plot stacked bar charts for the DataFrame + + .. plot:: + :context: close-figs + + >>> ax = df.plot.bar(stacked=True) + Instead of nesting, the figure can be split by column with ``subplots=True``. In this case, a :class:`numpy.ndarray` of :class:`matplotlib.axes.Axes` are returned. @@ -1066,6 +1073,13 @@ def bar(self, x=None, y=None, **kwargs): ... 'lifespan': lifespan}, index=index) >>> ax = df.plot.barh() + Plot stacked barh charts for the DataFrame + + .. plot:: + :context: close-figs + + >>> ax = df.plot.barh(stacked=True) + We can specify colors for each column .. plot::
- [x] closes #32759 - [ ] 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/33337
2020-04-06T19:32:42Z
2020-05-06T21:30:51Z
2020-05-06T21:30:51Z
2020-05-06T21:31:00Z
PLT: Order of plots does not preserve the column orders in df.hist
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index aa02c3bb9a1f8..7cde357562af4 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -686,6 +686,7 @@ Plotting - :func:`.plot` for line/bar now accepts color by dictonary (:issue:`8193`). - Bug in :meth:`DataFrame.plot.hist` where weights are not working for multiple columns (:issue:`33173`) - Bug in :meth:`DataFrame.boxplot` and :meth:`DataFrame.plot.boxplot` lost color attributes of ``medianprops``, ``whiskerprops``, ``capprops`` and ``medianprops`` (:issue:`30346`) +- Bug in :meth:`DataFrame.hist` where the order of ``column`` argument was ignored (:issue:`29235`) - Bug in :meth:`DataFrame.plot.scatter` that when adding multiple plots with different ``cmap``, colorbars alway use the first ``cmap`` (:issue:`33389`) diff --git a/pandas/plotting/_matplotlib/hist.py b/pandas/plotting/_matplotlib/hist.py index 3a0cdc90dfd5c..b0ce43dc2eb36 100644 --- a/pandas/plotting/_matplotlib/hist.py +++ b/pandas/plotting/_matplotlib/hist.py @@ -4,8 +4,6 @@ from pandas.core.dtypes.generic import ABCDataFrame, ABCIndexClass from pandas.core.dtypes.missing import isna, remove_na_arraylike -import pandas.core.common as com - from pandas.io.formats.printing import pprint_thing from pandas.plotting._matplotlib.core import LinePlot, MPLPlot from pandas.plotting._matplotlib.tools import _flatten, _set_ticks_props, _subplots @@ -403,7 +401,7 @@ def hist_frame( ) _axes = _flatten(axes) - for i, col in enumerate(com.try_sort(data.columns)): + for i, col in enumerate(data.columns): ax = _axes[i] ax.hist(data[col].dropna().values, bins=bins, **kwds) ax.set_title(col) diff --git a/pandas/tests/plotting/test_hist_method.py b/pandas/tests/plotting/test_hist_method.py index fba4f07f6cc0f..5a30e9fbb91c6 100644 --- a/pandas/tests/plotting/test_hist_method.py +++ b/pandas/tests/plotting/test_hist_method.py @@ -269,6 +269,30 @@ def test_hist_subplot_xrot(self): ) self._check_ticks_props(axes, xrot=0) + @pytest.mark.parametrize( + "column, expected", + [ + (None, ["width", "length", "height"]), + (["length", "width", "height"], ["length", "width", "height"]), + ], + ) + def test_hist_column_order_unchanged(self, column, expected): + # GH29235 + + df = DataFrame( + { + "width": [0.7, 0.2, 0.15, 0.2, 1.1], + "length": [1.5, 0.5, 1.2, 0.9, 3], + "height": [3, 0.5, 3.4, 2, 1], + }, + index=["pig", "rabbit", "duck", "chicken", "horse"], + ) + + axes = _check_plot_works(df.hist, column=column, layout=(1, 3)) + result = [axes[0, i].get_title() for i in range(3)] + + assert result == expected + @td.skip_if_no_mpl class TestDataFrameGroupByPlots(TestPlotBase):
- [x] closes #29235 - [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/33336
2020-04-06T19:00:09Z
2020-05-05T00:50:16Z
2020-05-05T00:50:16Z
2020-05-19T08:12:15Z
BLD: Increase minimum version of Cython to 0.29.16
diff --git a/ci/deps/azure-36-32bit.yaml b/ci/deps/azure-36-32bit.yaml index cf3fca307481f..15704cf0d5427 100644 --- a/ci/deps/azure-36-32bit.yaml +++ b/ci/deps/azure-36-32bit.yaml @@ -22,5 +22,5 @@ dependencies: # see comment above - pip - pip: - - cython>=0.29.13 + - cython>=0.29.16 - pytest>=5.0.1 diff --git a/ci/deps/azure-36-locale.yaml b/ci/deps/azure-36-locale.yaml index 810554632a507..56da56b45b702 100644 --- a/ci/deps/azure-36-locale.yaml +++ b/ci/deps/azure-36-locale.yaml @@ -6,7 +6,7 @@ dependencies: - python=3.6.* # tools - - cython>=0.29.13 + - cython>=0.29.16 - pytest>=5.0.1 - pytest-xdist>=1.21 - pytest-asyncio diff --git a/ci/deps/azure-36-locale_slow.yaml b/ci/deps/azure-36-locale_slow.yaml index 48ac50c001715..c086b3651afc3 100644 --- a/ci/deps/azure-36-locale_slow.yaml +++ b/ci/deps/azure-36-locale_slow.yaml @@ -6,7 +6,7 @@ dependencies: - python=3.6.* # tools - - cython>=0.29.13 + - cython>=0.29.16 - pytest>=5.0.1 - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/azure-36-minimum_versions.yaml b/ci/deps/azure-36-minimum_versions.yaml index de7e011d9c7ca..0e0ebe5c75218 100644 --- a/ci/deps/azure-36-minimum_versions.yaml +++ b/ci/deps/azure-36-minimum_versions.yaml @@ -6,7 +6,7 @@ dependencies: - python=3.6.1 # tools - - cython=0.29.13 + - cython=0.29.16 - pytest=5.0.1 - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/azure-37-locale.yaml b/ci/deps/azure-37-locale.yaml index dc51597a33209..31155ac93931a 100644 --- a/ci/deps/azure-37-locale.yaml +++ b/ci/deps/azure-37-locale.yaml @@ -5,7 +5,7 @@ dependencies: - python=3.7.* # tools - - cython>=0.29.13 + - cython>=0.29.16 - pytest>=5.0.1 - pytest-xdist>=1.21 - pytest-asyncio diff --git a/ci/deps/azure-37-numpydev.yaml b/ci/deps/azure-37-numpydev.yaml index a04bdc2448bce..29ebfe2639e32 100644 --- a/ci/deps/azure-37-numpydev.yaml +++ b/ci/deps/azure-37-numpydev.yaml @@ -5,7 +5,6 @@ dependencies: - python=3.7.* # tools - - cython>=0.29.13 - pytest>=5.0.1 - pytest-xdist>=1.21 - hypothesis>=3.58.0 @@ -15,6 +14,7 @@ dependencies: - pytz - pip - pip: + - cython>=0.29.16 - "git+git://github.com/dateutil/dateutil.git" - "-f https://7933911d6844c6c53a7d-47bd50c35cd79bd838daf386af554a83.ssl.cf2.rackcdn.com" - "--pre" diff --git a/ci/deps/azure-macos-36.yaml b/ci/deps/azure-macos-36.yaml index 90980133b31c1..279f44b06bd02 100644 --- a/ci/deps/azure-macos-36.yaml +++ b/ci/deps/azure-macos-36.yaml @@ -5,7 +5,6 @@ dependencies: - python=3.6.* # tools - - cython>=0.29.13 - pytest>=5.0.1 - pytest-xdist>=1.21 - hypothesis>=3.58.0 @@ -32,5 +31,6 @@ dependencies: - xlwt - pip - pip: + - cython>=0.29.16 - pyreadstat - pyxlsb diff --git a/ci/deps/azure-windows-36.yaml b/ci/deps/azure-windows-36.yaml index 663c55492e69e..548660cabaa67 100644 --- a/ci/deps/azure-windows-36.yaml +++ b/ci/deps/azure-windows-36.yaml @@ -6,7 +6,7 @@ dependencies: - python=3.6.* # tools - - cython>=0.29.13 + - cython>=0.29.16 - pytest>=5.0.1 - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/azure-windows-37.yaml b/ci/deps/azure-windows-37.yaml index 6b3ad6f560292..e491fd57b240b 100644 --- a/ci/deps/azure-windows-37.yaml +++ b/ci/deps/azure-windows-37.yaml @@ -6,7 +6,7 @@ dependencies: - python=3.7.* # tools - - cython>=0.29.13 + - cython>=0.29.16 - pytest>=5.0.1 - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/travis-36-cov.yaml b/ci/deps/travis-36-cov.yaml index 6883301a63a9b..2968c8f188d49 100644 --- a/ci/deps/travis-36-cov.yaml +++ b/ci/deps/travis-36-cov.yaml @@ -6,7 +6,7 @@ dependencies: - python=3.6.* # tools - - cython>=0.29.13 + - cython>=0.29.16 - pytest>=5.0.1 - pytest-xdist>=1.21 - hypothesis>=3.58.0 @@ -15,7 +15,7 @@ dependencies: # pandas dependencies - beautifulsoup4 - botocore>=1.11 - - cython>=0.29.13 + - cython>=0.29.16 - dask - fastparquet>=0.3.2 - gcsfs diff --git a/ci/deps/travis-36-locale.yaml b/ci/deps/travis-36-locale.yaml index d0bc046575953..3fc19f1bca084 100644 --- a/ci/deps/travis-36-locale.yaml +++ b/ci/deps/travis-36-locale.yaml @@ -6,7 +6,7 @@ dependencies: - python=3.6.* # tools - - cython>=0.29.13 + - cython>=0.29.16 - pytest>=5.0.1 - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/travis-36-slow.yaml b/ci/deps/travis-36-slow.yaml index 1dfd90d0904ac..df693f0e22c71 100644 --- a/ci/deps/travis-36-slow.yaml +++ b/ci/deps/travis-36-slow.yaml @@ -6,7 +6,7 @@ dependencies: - python=3.6.* # tools - - cython>=0.29.13 + - cython>=0.29.16 - pytest>=5.0.1 - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/travis-37.yaml b/ci/deps/travis-37.yaml index 682b1016ff3a2..986728d0a4a40 100644 --- a/ci/deps/travis-37.yaml +++ b/ci/deps/travis-37.yaml @@ -6,7 +6,7 @@ dependencies: - python=3.7.* # tools - - cython>=0.29.13 + - cython>=0.29.16 - pytest>=5.0.1 - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/ci/deps/travis-38.yaml b/ci/deps/travis-38.yaml index a627b7edc175f..b879c0f81dab2 100644 --- a/ci/deps/travis-38.yaml +++ b/ci/deps/travis-38.yaml @@ -6,7 +6,7 @@ dependencies: - python=3.8.* # tools - - cython>=0.29.13 + - cython>=0.29.16 - pytest>=5.0.1 - pytest-xdist>=1.21 - hypothesis>=3.58.0 diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 7cb7db27ae603..d45e4d2f6ca0e 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -92,6 +92,11 @@ Other enhancements .. --------------------------------------------------------------------------- +Development Changes +^^^^^^^^^^^^^^^^^^^ + +- The minimum version of Cython is now the most recent bug-fix version (0.29.16) (:issue:`33334`). + .. _whatsnew_110.api.other: Other API changes diff --git a/environment.yml b/environment.yml index cf579738f6fe9..b80a004e6cb99 100644 --- a/environment.yml +++ b/environment.yml @@ -12,7 +12,7 @@ dependencies: - asv # building - - cython>=0.29.13 + - cython>=0.29.16 # code checks - black=19.10b0 diff --git a/pyproject.toml b/pyproject.toml index 28d7c3d55c919..696785599d7da 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ requires = [ "setuptools", "wheel", - "Cython>=0.29.13", # Note: sync with setup.py + "Cython>=0.29.16", # Note: sync with setup.py "numpy==1.13.3; python_version=='3.6' and platform_system!='AIX'", "numpy==1.14.5; python_version>='3.7' and platform_system!='AIX'", "numpy==1.16.0; python_version=='3.6' and platform_system=='AIX'", diff --git a/requirements-dev.txt b/requirements-dev.txt index 6a2cc7b53615e..4fda019987469 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,7 +5,7 @@ numpy>=1.15 python-dateutil>=2.6.1 pytz asv -cython>=0.29.13 +cython>=0.29.16 black==19.10b0 cpplint flake8 diff --git a/setup.py b/setup.py index 461ef005c3df3..089baae123d2a 100755 --- a/setup.py +++ b/setup.py @@ -34,7 +34,7 @@ def is_platform_mac(): min_numpy_ver = "1.13.3" -min_cython_ver = "0.29.13" # note: sync with pyproject.toml +min_cython_ver = "0.29.16" # note: sync with pyproject.toml try: import Cython
- In particular, this fixes a bug in code returning ctuples - cython/cython#2745 - cython/cython#1427 - This is a prereq for #33220 - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33334
2020-04-06T18:26:27Z
2020-04-07T23:24:23Z
2020-04-07T23:24:22Z
2020-04-08T04:52:18Z
REF: BlockManager.delete -> idelete
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index fac4ca6768ece..3363d22686f96 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3713,7 +3713,8 @@ def __delitem__(self, key) -> None: # If the above loop ran and didn't delete anything because # there was no match, this call should raise the appropriate # exception: - self._mgr.delete(key) + loc = self.axes[-1].get_loc(key) + self._mgr.idelete(loc) # delete from the caches try: diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index c6efd6a2ac6a7..b2c43be21771e 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1007,12 +1007,10 @@ def iget(self, i: int) -> "SingleBlockManager": self.axes[1], ) - def delete(self, item): + def idelete(self, indexer): """ - Delete selected item (items if non-unique) in-place. + Delete selected locations in-place (new block and array, same BlockManager) """ - indexer = self.items.get_loc(item) - is_deleted = np.zeros(self.shape[0], dtype=np.bool_) is_deleted[indexer] = True ref_loc_offset = -is_deleted.cumsum() @@ -1606,15 +1604,14 @@ def _consolidate_check(self): def _consolidate_inplace(self): pass - def delete(self, item): + def idelete(self, indexer): """ - Delete single item from SingleBlockManager. + Delete single location from SingleBlockManager. Ensures that self.blocks doesn't become empty. """ - loc = self.items.get_loc(item) - self._block.delete(loc) - self.axes[0] = self.axes[0].delete(loc) + self._block.delete(indexer) + self.axes[0] = self.axes[0].delete(indexer) def fast_xs(self, loc): """
Moving towards all-locational inside BlockManager, also makes it easier to grep for where methods are used.
https://api.github.com/repos/pandas-dev/pandas/pulls/33332
2020-04-06T17:49:35Z
2020-04-06T21:22:21Z
2020-04-06T21:22:21Z
2020-04-06T21:28:06Z
CLN: Static types in `pandas/_lib/lib.pyx`
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 276c2d5198831..6147d6d9c1658 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1001,34 +1001,34 @@ cdef inline bint c_is_list_like(object obj, bint allow_sets): _TYPE_MAP = { - 'categorical': 'categorical', - 'category': 'categorical', - 'int8': 'integer', - 'int16': 'integer', - 'int32': 'integer', - 'int64': 'integer', - 'i': 'integer', - 'uint8': 'integer', - 'uint16': 'integer', - 'uint32': 'integer', - 'uint64': 'integer', - 'u': 'integer', - 'float32': 'floating', - 'float64': 'floating', - 'f': 'floating', - 'complex64': 'complex', - 'complex128': 'complex', - 'c': 'complex', - 'string': 'string', - 'S': 'bytes', - 'U': 'string', - 'bool': 'boolean', - 'b': 'boolean', - 'datetime64[ns]': 'datetime64', - 'M': 'datetime64', - 'timedelta64[ns]': 'timedelta64', - 'm': 'timedelta64', - 'interval': 'interval', + "categorical": "categorical", + "category": "categorical", + "int8": "integer", + "int16": "integer", + "int32": "integer", + "int64": "integer", + "i": "integer", + "uint8": "integer", + "uint16": "integer", + "uint32": "integer", + "uint64": "integer", + "u": "integer", + "float32": "floating", + "float64": "floating", + "f": "floating", + "complex64": "complex", + "complex128": "complex", + "c": "complex", + "string": "string", + "S": "bytes", + "U": "string", + "bool": "boolean", + "b": "boolean", + "datetime64[ns]": "datetime64", + "M": "datetime64", + "timedelta64[ns]": "timedelta64", + "m": "timedelta64", + "interval": "interval", } # types only exist on certain platform @@ -1173,12 +1173,13 @@ cdef class Seen: or self.nat_) -cdef _try_infer_map(v): +cdef object _try_infer_map(object v): """ If its in our map, just return the dtype. """ cdef: - object attr, val + object val + str attr for attr in ['name', 'kind', 'base']: val = getattr(v.dtype, attr) if val in _TYPE_MAP:
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33329
2020-04-06T16:23:39Z
2020-04-10T16:14:06Z
2020-04-10T16:14:06Z
2020-04-10T16:16:25Z
DOC: Fix examples in `pandas/core/strings.py`
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index cd9e4384fd0d9..1bdbbb54a0aac 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -296,6 +296,10 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then pytest -q --doctest-modules pandas/core/series.py RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Doctests strings.py' ; echo $MSG + pytest -q --doctest-modules pandas/core/strings.py + RET=$(($RET + $?)) ; echo $MSG "DONE" + # Directories MSG='Doctests arrays'; echo $MSG diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 59b8b37f72695..52d9a81489db4 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -652,9 +652,9 @@ def str_replace(arr, pat, repl, n=-1, case=None, flags=0, regex=True): To get the idea: >>> pd.Series(['foo', 'fuz', np.nan]).str.replace('f', repr) - 0 <_sre.SRE_Match object; span=(0, 1), match='f'>oo - 1 <_sre.SRE_Match object; span=(0, 1), match='f'>uz - 2 NaN + 0 <re.Match object; span=(0, 1), match='f'>oo + 1 <re.Match object; span=(0, 1), match='f'>uz + 2 NaN dtype: object Reverse every lowercase alphabetic word: @@ -2076,8 +2076,18 @@ class StringMethods(NoNewAttributesMixin): Examples -------- - >>> s.str.split('_') - >>> s.str.replace('_', '') + >>> s = pd.Series(["A_Str_Series"]) + >>> s + 0 A_Str_Series + dtype: object + + >>> s.str.split("_") + 0 [A, Str, Series] + dtype: object + + >>> s.str.replace("_", "") + 0 AStrSeries + dtype: object """ def __init__(self, data): @@ -2583,9 +2593,14 @@ def cat(self, others=None, sep=None, na_rep=None, join="left"): Examples -------- - >>> s = pd.Series(["this is a regular sentence", - ... "https://docs.python.org/3/tutorial/index.html", - ... np.nan]) + >>> s = pd.Series( + ... [ + ... "this is a regular sentence", + ... "https://docs.python.org/3/tutorial/index.html", + ... np.nan + ... ] + ... ) + >>> s 0 this is a regular sentence 1 https://docs.python.org/3/tutorial/index.html 2 NaN @@ -2625,7 +2640,7 @@ def cat(self, others=None, sep=None, na_rep=None, join="left"): The `pat` parameter can be used to split by other characters. - >>> s.str.split(pat = "/") + >>> s.str.split(pat="/") 0 [this is a regular sentence] 1 [https:, , docs.python.org, 3, tutorial, index... 2 NaN @@ -2636,14 +2651,10 @@ def cat(self, others=None, sep=None, na_rep=None, join="left"): the columns during the split. >>> s.str.split(expand=True) - 0 1 2 3 - 0 this is a regular - 1 https://docs.python.org/3/tutorial/index.html None None None - 2 NaN NaN NaN NaN \ - 4 - 0 sentence - 1 None - 2 NaN + 0 1 2 3 4 + 0 this is a regular sentence + 1 https://docs.python.org/3/tutorial/index.html None None None None + 2 NaN NaN NaN NaN NaN For slightly more complex use cases like splitting the html document name from a url, a combination of parameter settings can be used. @@ -2658,7 +2669,9 @@ def cat(self, others=None, sep=None, na_rep=None, join="left"): expressions. >>> s = pd.Series(["1+1=2"]) - + >>> s + 0 1+1=2 + dtype: object >>> s.str.split(r"\+|=", expand=True) 0 1 2 0 1 1 2 @@ -2750,7 +2763,7 @@ def rsplit(self, pat=None, n=-1, expand=False): >>> idx.str.partition() MultiIndex([('X', ' ', '123'), ('Y', ' ', '999')], - dtype='object') + ) Or an index with tuples with ``expand=False``:
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33328
2020-04-06T16:08:05Z
2020-04-06T20:42:01Z
2020-04-06T20:42:01Z
2020-04-07T10:49:02Z
PERF: fix placement when slicing a Series
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index ac8de977b9a1a..c6efd6a2ac6a7 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1568,7 +1568,7 @@ def get_slice(self, slobj: slice, axis: int = 0) -> "SingleBlockManager": blk = self._block array = blk._slice(slobj) - block = blk.make_block_same_class(array, placement=range(len(array))) + block = blk.make_block_same_class(array, placement=slice(0, len(array))) return type(self)(block, self.index[slobj]) @property
Closes https://github.com/pandas-dev/pandas/issues/33323
https://api.github.com/repos/pandas-dev/pandas/pulls/33324
2020-04-06T14:22:55Z
2020-04-06T16:11:08Z
2020-04-06T16:11:08Z
2020-04-06T16:11:08Z
TST: Don't use 'is' on strings to avoid SyntaxWarning
diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 961c18749f055..b28e8a5b347aa 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -234,9 +234,16 @@ def test_set_index_pass_arrays_duplicate( # need to adapt first drop for case that both keys are 'A' -- # cannot drop the same column twice; - # use "is" because == would give ambiguous Boolean error for containers + # plain == would give ambiguous Boolean error for containers first_drop = ( - False if (keys[0] is "A" and keys[1] is "A") else drop # noqa: F632 + False + if ( + isinstance(keys[0], str) + and keys[0] == "A" + and isinstance(keys[1], str) + and keys[1] == "A" + ) + else drop ) # to test against already-tested behaviour, we add sequentially, # hence second append always True; must wrap keys in list, otherwise
This avoids the below warning (in Python 3.8, [user-visible in Debian](https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=956021) because they byte-compile everything on install), and possibly unspecified behaviour (though I haven't seen that in practice). ``` /usr/lib/python3/dist-packages/pandas/tests/frame/test_alter_axes.py:241: SyntaxWarning: "is" with a literal. Did you mean "=="? False if (keys[0] is "A" and keys[1] is "A") else drop # noqa: F632 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/33322
2020-04-06T14:13:00Z
2020-04-06T21:34:55Z
2020-04-06T21:34:55Z
2020-04-06T21:35:00Z
DOC/CLN: Fix docstring typo
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 3aa8a1e93355d..d0319e9181bad 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4232,7 +4232,7 @@ def equals(self, other: Any) -> bool: >>> idx1.equals(idx2) False - The oreder is compared + The order is compared >>> ascending_idx = pd.Index([1, 2, 3]) >>> ascending_idx
https://api.github.com/repos/pandas-dev/pandas/pulls/33320
2020-04-06T12:54:06Z
2020-04-06T13:05:16Z
2020-04-06T13:05:16Z
2020-04-06T16:13:13Z
Changed files permissions to be the same
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py old mode 100755 new mode 100644 diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py old mode 100755 new mode 100644 diff --git a/pandas/tests/io/generate_legacy_storage_files.py b/pandas/tests/io/generate_legacy_storage_files.py old mode 100755 new mode 100644
Not 100% sure about this change, feel free to close at anytime.
https://api.github.com/repos/pandas-dev/pandas/pulls/33318
2020-04-06T12:22:30Z
2020-04-06T14:49:14Z
2020-04-06T14:49:14Z
2020-04-06T15:05:44Z
CLN: Added static types for `pandas/_libs/reduction.pyx`
diff --git a/pandas/_libs/reduction.pyx b/pandas/_libs/reduction.pyx index 9f8579606014a..4a9c89848a9d8 100644 --- a/pandas/_libs/reduction.pyx +++ b/pandas/_libs/reduction.pyx @@ -36,7 +36,12 @@ cdef class Reducer: object dummy, f, labels, typ, ityp, index ndarray arr - def __init__(self, ndarray arr, object f, axis=1, dummy=None, labels=None): + def __init__( + self, ndarray arr, object f, int axis=1, object dummy=None, object labels=None + ): + cdef: + Py_ssize_t n, k + n, k = (<object>arr).shape if axis == 0: @@ -60,7 +65,7 @@ cdef class Reducer: self.dummy, self.typ, self.index, self.ityp = self._check_dummy( dummy=dummy) - cdef _check_dummy(self, dummy=None): + cdef _check_dummy(self, object dummy=None): cdef: object index = None, typ = None, ityp = None @@ -147,7 +152,7 @@ cdef class Reducer: cdef class _BaseGrouper: - cdef _check_dummy(self, dummy): + cdef _check_dummy(self, object dummy): # both values and index must be an ndarray! values = dummy.values @@ -190,13 +195,16 @@ cdef class _BaseGrouper: """ Call self.f on our new group, then update to the next group. """ + cdef: + object res + cached_ityp._engine.clear_mapping() res = self.f(cached_typ) res = _extract_result(res) if not initialized: # On the first pass, we check the output shape to see # if this looks like a reduction. - initialized = 1 + initialized = True _check_result_array(res, len(self.dummy_arr)) islider.advance(group_size) @@ -534,7 +542,11 @@ cdef class BlockSlider: cdef: char **base_ptrs - def __init__(self, frame): + def __init__(self, object frame): + cdef: + Py_ssize_t i + object b + self.frame = frame self.dummy = frame[:0] self.index = self.dummy.index
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33316
2020-04-06T10:26:24Z
2020-04-06T14:48:12Z
2020-04-06T14:48:11Z
2020-04-06T15:07:07Z
DOC: do not include type hints in signature in html docs
diff --git a/doc/source/conf.py b/doc/source/conf.py index 35833627f6c05..d24483abd28e1 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -109,6 +109,7 @@ ) ) autosummary_generate = True if pattern is None else ["index"] +autodoc_typehints = "none" # numpydoc numpydoc_attributes_as_param_list = False
See https://github.com/pandas-dev/pandas/issues/33025. Removing the type hints in the online docs until we have a better solution to improve readability.
https://api.github.com/repos/pandas-dev/pandas/pulls/33312
2020-04-06T08:11:52Z
2020-04-06T20:52:53Z
2020-04-06T20:52:53Z
2020-04-06T20:55:44Z
Update citation webpage
diff --git a/README.md b/README.md index 5342eda4390eb..8c3617df2e8ad 100644 --- a/README.md +++ b/README.md @@ -7,6 +7,7 @@ # pandas: powerful Python data analysis toolkit [![PyPI Latest Release](https://img.shields.io/pypi/v/pandas.svg)](https://pypi.org/project/pandas/) [![Conda Latest Release](https://anaconda.org/conda-forge/pandas/badges/version.svg)](https://anaconda.org/anaconda/pandas/) +[![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.3509134.svg)](https://doi.org/10.5281/zenodo.3509134) [![Package Status](https://img.shields.io/pypi/status/pandas.svg)](https://pypi.org/project/pandas/) [![License](https://img.shields.io/pypi/l/pandas.svg)](https://github.com/pandas-dev/pandas/blob/master/LICENSE) [![Travis Build Status](https://travis-ci.org/pandas-dev/pandas.svg?branch=master)](https://travis-ci.org/pandas-dev/pandas) diff --git a/web/pandas/about/citing.md b/web/pandas/about/citing.md index d5cb64e58f0ad..25d2c86061daa 100644 --- a/web/pandas/about/citing.md +++ b/web/pandas/about/citing.md @@ -2,31 +2,35 @@ ## Citing pandas -If you use _pandas_ for a scientific publication, we would appreciate citations to one of the following papers: +If you use _pandas_ for a scientific publication, we would appreciate citations to the published software and the +following paper: + +- [pandas on Zenodo](https://zenodo.org/record/3715232#.XoqFyC2ZOL8), + Please find us on Zenodo and replace with the citation for the version you are using. You cna replace the full author + list from there with "The pandas development team" like in the example below. + + @software{reback2020pandas, + author = {The pandas development team}, + title = {pandas-dev/pandas: Pandas}, + month = feb, + year = 2020, + publisher = {Zenodo}, + version = {latest}, + doi = {10.5281/zenodo.3509134}, + url = {https://doi.org/10.5281/zenodo.3509134} + } - [Data structures for statistical computing in python](https://conference.scipy.org/proceedings/scipy2010/pdfs/mckinney.pdf), McKinney, Proceedings of the 9th Python in Science Conference, Volume 445, 2010. - @inproceedings{mckinney2010data, - title={Data structures for statistical computing in python}, - author={Wes McKinney}, - booktitle={Proceedings of the 9th Python in Science Conference}, - volume={445}, - pages={51--56}, - year={2010}, - organization={Austin, TX} - } - - -- [pandas: a foundational Python library for data analysis and statistics](https://www.scribd.com/document/71048089/pandas-a-Foundational-Python-Library-for-Data-Analysis-and-Statistics), - McKinney, Python for High Performance and Scientific Computing, Volume 14, 2011. - - @article{mckinney2011pandas, - title={pandas: a foundational Python library for data analysis and statistics}, - author={Wes McKinney}, - journal={Python for High Performance and Scientific Computing}, - volume={14}, - year={2011} + @InProceedings{ mckinney-proc-scipy-2010, + author = { {W}es {M}c{K}inney }, + title = { {D}ata {S}tructures for {S}tatistical {C}omputing in {P}ython }, + booktitle = { {P}roceedings of the 9th {P}ython in {S}cience {C}onference }, + pages = { 56 - 61 }, + year = { 2010 }, + editor = { {S}t\'efan van der {W}alt and {J}arrod {M}illman }, + doi = { 10.25080/Majora-92bf1922-00a } } ## Brand and logo
Follow-up of #32388, addressing #24036 I will leave it to the pandas team to decide whether to put in there a BibTeX entry with the concept DOI or a specific version, some options of dealing with this are described [in this comment](https://github.com/sherpa/sherpa/pull/634#issuecomment-553668211). Note how [this comment thread](https://github.com/pandas-dev/pandas/pull/32388#discussion_r386392799) on the previous PR asked to replace the author list by "The pandas development team". However, if users go to Zenodo to get the correct BibTeX entry of the version they're actually using, their citation will contain the full author list provided in Zenodo.
https://api.github.com/repos/pandas-dev/pandas/pulls/33311
2020-04-06T01:45:50Z
2020-04-10T17:43:37Z
2020-04-10T17:43:37Z
2020-05-07T10:10:11Z
CLN: remove fill_tuple kludge
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index d8b54fd5cffb3..a968fe1fa68f9 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1241,7 +1241,7 @@ def func(x): blocks = [self.make_block_same_class(interp_values)] return self._maybe_downcast(blocks, downcast) - def take_nd(self, indexer, axis: int, new_mgr_locs=None, fill_tuple=None): + def take_nd(self, indexer, axis: int, new_mgr_locs=None, fill_value=lib.no_default): """ Take values according to indexer and return them as a block.bb @@ -1252,11 +1252,10 @@ def take_nd(self, indexer, axis: int, new_mgr_locs=None, fill_tuple=None): values = self.values - if fill_tuple is None: + if fill_value is lib.no_default: fill_value = self.fill_value allow_fill = False else: - fill_value = fill_tuple[0] allow_fill = True new_values = algos.take_nd( @@ -1721,14 +1720,14 @@ def to_native_types(self, na_rep="nan", quoting=None, **kwargs): # we are expected to return a 2-d ndarray return values.reshape(1, len(values)) - def take_nd(self, indexer, axis: int = 0, new_mgr_locs=None, fill_tuple=None): + def take_nd( + self, indexer, axis: int = 0, new_mgr_locs=None, fill_value=lib.no_default + ): """ Take values according to indexer and return them as a block. """ - if fill_tuple is None: + if fill_value is lib.no_default: fill_value = None - else: - fill_value = fill_tuple[0] # axis doesn't matter; we are really a single-dim object # but are passed the axis depending on the calling routing diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index ac8de977b9a1a..00fbcd034163a 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1299,14 +1299,14 @@ def reindex_indexer( raise IndexError("Requested axis not found in manager") if axis == 0: - new_blocks = self._slice_take_blocks_ax0(indexer, fill_tuple=(fill_value,)) + new_blocks = self._slice_take_blocks_ax0(indexer, fill_value=fill_value) else: new_blocks = [ blk.take_nd( indexer, axis=axis, - fill_tuple=( - fill_value if fill_value is not None else blk.fill_value, + fill_value=( + fill_value if fill_value is not None else blk.fill_value ), ) for blk in self.blocks @@ -1317,7 +1317,7 @@ def reindex_indexer( return type(self).from_blocks(new_blocks, new_axes) - def _slice_take_blocks_ax0(self, slice_or_indexer, fill_tuple=None): + def _slice_take_blocks_ax0(self, slice_or_indexer, fill_value=lib.no_default): """ Slice/take blocks along axis=0. @@ -1327,7 +1327,7 @@ def _slice_take_blocks_ax0(self, slice_or_indexer, fill_tuple=None): ------- new_blocks : list of Block """ - allow_fill = fill_tuple is not None + allow_fill = fill_value is not lib.no_default sl_type, slobj, sllen = _preprocess_slice_or_indexer( slice_or_indexer, self.shape[0], allow_fill=allow_fill @@ -1339,16 +1339,15 @@ def _slice_take_blocks_ax0(self, slice_or_indexer, fill_tuple=None): if sl_type in ("slice", "mask"): return [blk.getitem_block(slobj, new_mgr_locs=slice(0, sllen))] elif not allow_fill or self.ndim == 1: - if allow_fill and fill_tuple[0] is None: + if allow_fill and fill_value is None: _, fill_value = maybe_promote(blk.dtype) - fill_tuple = (fill_value,) return [ blk.take_nd( slobj, axis=0, new_mgr_locs=slice(0, sllen), - fill_tuple=fill_tuple, + fill_value=fill_value, ) ] @@ -1371,8 +1370,7 @@ def _slice_take_blocks_ax0(self, slice_or_indexer, fill_tuple=None): blocks = [] for blkno, mgr_locs in libinternals.get_blkno_placements(blknos, group=True): if blkno == -1: - # If we've got here, fill_tuple was not None. - fill_value = fill_tuple[0] + # If we've got here, fill_value was not lib.no_default blocks.append( self._make_na_block(placement=mgr_locs, fill_value=fill_value) @@ -1393,10 +1391,7 @@ def _slice_take_blocks_ax0(self, slice_or_indexer, fill_tuple=None): else: blocks.append( blk.take_nd( - blklocs[mgr_locs.indexer], - axis=0, - new_mgr_locs=mgr_locs, - fill_tuple=None, + blklocs[mgr_locs.indexer], axis=0, new_mgr_locs=mgr_locs, ) )
https://api.github.com/repos/pandas-dev/pandas/pulls/33310
2020-04-06T01:35:09Z
2020-04-06T21:39:21Z
2020-04-06T21:39:21Z
2020-04-07T11:51:11Z
DOC: include Offset.__call__ to autosummary to fix sphinx warning
diff --git a/doc/source/reference/offset_frequency.rst b/doc/source/reference/offset_frequency.rst index fc1c6d6bd6d47..17544cb7a1225 100644 --- a/doc/source/reference/offset_frequency.rst +++ b/doc/source/reference/offset_frequency.rst @@ -37,6 +37,7 @@ Methods DateOffset.onOffset DateOffset.is_anchored DateOffset.is_on_offset + DateOffset.__call__ BusinessDay ----------- @@ -69,6 +70,7 @@ Methods BusinessDay.onOffset BusinessDay.is_anchored BusinessDay.is_on_offset + BusinessDay.__call__ BusinessHour ------------ @@ -100,6 +102,7 @@ Methods BusinessHour.onOffset BusinessHour.is_anchored BusinessHour.is_on_offset + BusinessHour.__call__ CustomBusinessDay ----------------- @@ -131,6 +134,7 @@ Methods CustomBusinessDay.onOffset CustomBusinessDay.is_anchored CustomBusinessDay.is_on_offset + CustomBusinessDay.__call__ CustomBusinessHour ------------------ @@ -162,6 +166,7 @@ Methods CustomBusinessHour.onOffset CustomBusinessHour.is_anchored CustomBusinessHour.is_on_offset + CustomBusinessHour.__call__ MonthOffset ----------- @@ -194,6 +199,7 @@ Methods MonthOffset.onOffset MonthOffset.is_anchored MonthOffset.is_on_offset + MonthOffset.__call__ MonthEnd -------- @@ -226,6 +232,7 @@ Methods MonthEnd.onOffset MonthEnd.is_anchored MonthEnd.is_on_offset + MonthEnd.__call__ MonthBegin ---------- @@ -258,6 +265,7 @@ Methods MonthBegin.onOffset MonthBegin.is_anchored MonthBegin.is_on_offset + MonthBegin.__call__ BusinessMonthEnd ---------------- @@ -290,6 +298,7 @@ Methods BusinessMonthEnd.onOffset BusinessMonthEnd.is_anchored BusinessMonthEnd.is_on_offset + BusinessMonthEnd.__call__ BusinessMonthBegin ------------------ @@ -322,6 +331,7 @@ Methods BusinessMonthBegin.onOffset BusinessMonthBegin.is_anchored BusinessMonthBegin.is_on_offset + BusinessMonthBegin.__call__ CustomBusinessMonthEnd ---------------------- @@ -354,6 +364,7 @@ Methods CustomBusinessMonthEnd.onOffset CustomBusinessMonthEnd.is_anchored CustomBusinessMonthEnd.is_on_offset + CustomBusinessMonthEnd.__call__ CustomBusinessMonthBegin ------------------------ @@ -386,6 +397,7 @@ Methods CustomBusinessMonthBegin.onOffset CustomBusinessMonthBegin.is_anchored CustomBusinessMonthBegin.is_on_offset + CustomBusinessMonthBegin.__call__ SemiMonthOffset --------------- @@ -418,6 +430,7 @@ Methods SemiMonthOffset.onOffset SemiMonthOffset.is_anchored SemiMonthOffset.is_on_offset + SemiMonthOffset.__call__ SemiMonthEnd ------------ @@ -450,6 +463,7 @@ Methods SemiMonthEnd.onOffset SemiMonthEnd.is_anchored SemiMonthEnd.is_on_offset + SemiMonthEnd.__call__ SemiMonthBegin -------------- @@ -482,6 +496,7 @@ Methods SemiMonthBegin.onOffset SemiMonthBegin.is_anchored SemiMonthBegin.is_on_offset + SemiMonthBegin.__call__ Week ---- @@ -514,6 +529,7 @@ Methods Week.onOffset Week.is_anchored Week.is_on_offset + Week.__call__ WeekOfMonth ----------- @@ -545,6 +561,7 @@ Methods WeekOfMonth.onOffset WeekOfMonth.is_anchored WeekOfMonth.is_on_offset + WeekOfMonth.__call__ LastWeekOfMonth --------------- @@ -576,6 +593,7 @@ Methods LastWeekOfMonth.onOffset LastWeekOfMonth.is_anchored LastWeekOfMonth.is_on_offset + LastWeekOfMonth.__call__ QuarterOffset ------------- @@ -608,6 +626,7 @@ Methods QuarterOffset.onOffset QuarterOffset.is_anchored QuarterOffset.is_on_offset + QuarterOffset.__call__ BQuarterEnd ----------- @@ -640,6 +659,7 @@ Methods BQuarterEnd.onOffset BQuarterEnd.is_anchored BQuarterEnd.is_on_offset + BQuarterEnd.__call__ BQuarterBegin ------------- @@ -672,6 +692,7 @@ Methods BQuarterBegin.onOffset BQuarterBegin.is_anchored BQuarterBegin.is_on_offset + BQuarterBegin.__call__ QuarterEnd ---------- @@ -704,6 +725,7 @@ Methods QuarterEnd.onOffset QuarterEnd.is_anchored QuarterEnd.is_on_offset + QuarterEnd.__call__ QuarterBegin ------------ @@ -736,6 +758,7 @@ Methods QuarterBegin.onOffset QuarterBegin.is_anchored QuarterBegin.is_on_offset + QuarterBegin.__call__ YearOffset ---------- @@ -768,6 +791,7 @@ Methods YearOffset.onOffset YearOffset.is_anchored YearOffset.is_on_offset + YearOffset.__call__ BYearEnd -------- @@ -800,6 +824,7 @@ Methods BYearEnd.onOffset BYearEnd.is_anchored BYearEnd.is_on_offset + BYearEnd.__call__ BYearBegin ---------- @@ -832,6 +857,7 @@ Methods BYearBegin.onOffset BYearBegin.is_anchored BYearBegin.is_on_offset + BYearBegin.__call__ YearEnd ------- @@ -864,6 +890,7 @@ Methods YearEnd.onOffset YearEnd.is_anchored YearEnd.is_on_offset + YearEnd.__call__ YearBegin --------- @@ -896,6 +923,7 @@ Methods YearBegin.onOffset YearBegin.is_anchored YearBegin.is_on_offset + YearBegin.__call__ FY5253 ------ @@ -929,6 +957,7 @@ Methods FY5253.onOffset FY5253.is_anchored FY5253.is_on_offset + FY5253.__call__ FY5253Quarter ------------- @@ -962,6 +991,7 @@ Methods FY5253Quarter.is_anchored FY5253Quarter.is_on_offset FY5253Quarter.year_has_extra_week + FY5253Quarter.__call__ Easter ------ @@ -993,6 +1023,7 @@ Methods Easter.onOffset Easter.is_anchored Easter.is_on_offset + Easter.__call__ Tick ---- @@ -1024,6 +1055,7 @@ Methods Tick.onOffset Tick.is_anchored Tick.is_on_offset + Tick.__call__ Day --- @@ -1055,6 +1087,7 @@ Methods Day.onOffset Day.is_anchored Day.is_on_offset + Day.__call__ Hour ---- @@ -1086,6 +1119,7 @@ Methods Hour.onOffset Hour.is_anchored Hour.is_on_offset + Hour.__call__ Minute ------ @@ -1117,6 +1151,7 @@ Methods Minute.onOffset Minute.is_anchored Minute.is_on_offset + Minute.__call__ Second ------ @@ -1148,6 +1183,7 @@ Methods Second.onOffset Second.is_anchored Second.is_on_offset + Second.__call__ Milli ----- @@ -1179,6 +1215,7 @@ Methods Milli.onOffset Milli.is_anchored Milli.is_on_offset + Milli.__call__ Micro ----- @@ -1210,6 +1247,7 @@ Methods Micro.onOffset Micro.is_anchored Micro.is_on_offset + Micro.__call__ Nano ---- @@ -1241,6 +1279,7 @@ Methods Nano.onOffset Nano.is_anchored Nano.is_on_offset + Nano.__call__ BDay ---- @@ -1277,6 +1316,7 @@ Methods BDay.is_on_offset BDay.rollback BDay.rollforward + BDay.__call__ BMonthEnd --------- @@ -1312,6 +1352,7 @@ Methods BMonthEnd.is_on_offset BMonthEnd.rollback BMonthEnd.rollforward + BMonthEnd.__call__ BMonthBegin ----------- @@ -1347,6 +1388,7 @@ Methods BMonthBegin.is_on_offset BMonthBegin.rollback BMonthBegin.rollforward + BMonthBegin.__call__ CBMonthEnd ---------- @@ -1386,6 +1428,7 @@ Methods CBMonthEnd.is_on_offset CBMonthEnd.rollback CBMonthEnd.rollforward + CBMonthEnd.__call__ CBMonthBegin ------------ @@ -1425,6 +1468,7 @@ Methods CBMonthBegin.is_on_offset CBMonthBegin.rollback CBMonthBegin.rollforward + CBMonthBegin.__call__ CDay ---- @@ -1461,6 +1505,7 @@ Methods CDay.is_on_offset CDay.rollback CDay.rollforward + CDay.__call__ .. _api.frequencies:
https://api.github.com/repos/pandas-dev/pandas/pulls/33309
2020-04-06T01:23:39Z
2020-04-06T13:59:55Z
2020-04-06T13:59:55Z
2020-05-26T09:39:48Z
REF: call _block_shape from EABlock.make_block
diff --git a/pandas/core/internals/__init__.py b/pandas/core/internals/__init__.py index bc45b7c74ecc1..d6838355e6791 100644 --- a/pandas/core/internals/__init__.py +++ b/pandas/core/internals/__init__.py @@ -10,7 +10,6 @@ IntBlock, ObjectBlock, TimeDeltaBlock, - _block_shape, _safe_reshape, make_block, ) @@ -34,7 +33,6 @@ "TimeDeltaBlock", "_safe_reshape", "make_block", - "_block_shape", "BlockManager", "SingleBlockManager", "concatenate_block_managers", diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index d8b54fd5cffb3..316811f46cbfb 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -244,6 +244,8 @@ def make_block(self, values, placement=None) -> "Block": """ if placement is None: placement = self.mgr_locs + if self.is_extension: + values = _block_shape(values, ndim=self.ndim) return make_block(values, placement=placement, ndim=self.ndim) @@ -355,13 +357,12 @@ def _split_op_result(self, result) -> List["Block"]: nbs = [] for i, loc in enumerate(self.mgr_locs): vals = result[i] - nv = _block_shape(vals, ndim=self.ndim) - block = self.make_block(values=nv, placement=[loc]) + block = self.make_block(values=vals, placement=[loc]) nbs.append(block) return nbs if not isinstance(result, Block): - result = self.make_block(values=_block_shape(result, ndim=self.ndim)) + result = self.make_block(result) return [result] @@ -1277,9 +1278,6 @@ def take_nd(self, indexer, axis: int, new_mgr_locs=None, fill_tuple=None): 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, stacklevel=7) - # We use block_shape for ExtensionBlock subclasses, which may call here - # via a super. - new_values = _block_shape(new_values, ndim=self.ndim) return [self.make_block(values=new_values)] def shift(self, periods: int, axis: int = 0, fill_value=None): @@ -2267,7 +2265,7 @@ def concat_same_type(self, to_concat): values = values.astype(object, copy=False) placement = self.mgr_locs if self.ndim == 2 else slice(len(values)) - return self.make_block(_block_shape(values, self.ndim), placement=placement) + return self.make_block(values, placement=placement) return super().concat_same_type(to_concat) def fillna(self, value, limit=None, inplace=False, downcast=None): @@ -2456,7 +2454,6 @@ def f(mask, val, idx): # TODO: allow EA once reshape is supported values = values.reshape(shape) - values = _block_shape(values, ndim=self.ndim) return values if self.ndim == 2: @@ -2738,9 +2735,7 @@ def concat_same_type(self, to_concat): ) placement = self.mgr_locs if self.ndim == 2 else slice(len(values)) # not using self.make_block_same_class as values can be object dtype - return self.make_block( - _block_shape(values, ndim=self.ndim), placement=placement - ) + return self.make_block(values, placement=placement) def replace( self, @@ -2859,16 +2854,15 @@ def _extend_blocks(result, blocks=None): return blocks -def _block_shape(values, ndim=1, shape=None): +def _block_shape(values: ArrayLike, ndim: int = 1) -> ArrayLike: """ guarantee the shape of the values to be at least 1 d """ if values.ndim < ndim: - if shape is None: - shape = values.shape - if not is_extension_array_dtype(values): - # TODO: https://github.com/pandas-dev/pandas/issues/23023 + shape = values.shape + if not is_extension_array_dtype(values.dtype): + # TODO(EA2D): https://github.com/pandas-dev/pandas/issues/23023 # block.shape is incorrect for "2D" ExtensionArrays # We can't, and don't need to, reshape. - values = values.reshape(tuple((1,) + shape)) + values = values.reshape(tuple((1,) + shape)) # type: ignore return values
https://api.github.com/repos/pandas-dev/pandas/pulls/33308
2020-04-05T22:46:42Z
2020-04-10T16:02:48Z
2020-04-10T16:02:48Z
2020-04-10T18:13:17Z
TST: misplaced reduction/indexing tests
diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 6525e93d89fce..e1fc7e9d7c5b8 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -1274,3 +1274,28 @@ def test_series_broadcasting(self): df_nan.clip(lower=s, axis=0) for op in ["lt", "le", "gt", "ge", "eq", "ne"]: getattr(df, op)(s_nan, axis=0) + + +class TestDataFrameReductions: + def test_min_max_dt64_with_NaT(self): + # Both NaT and Timestamp are in DataFrame. + df = pd.DataFrame({"foo": [pd.NaT, pd.NaT, pd.Timestamp("2012-05-01")]}) + + res = df.min() + exp = pd.Series([pd.Timestamp("2012-05-01")], index=["foo"]) + tm.assert_series_equal(res, exp) + + res = df.max() + exp = pd.Series([pd.Timestamp("2012-05-01")], index=["foo"]) + tm.assert_series_equal(res, exp) + + # GH12941, only NaTs are in DataFrame. + df = pd.DataFrame({"foo": [pd.NaT, pd.NaT]}) + + res = df.min() + exp = pd.Series([pd.NaT], index=["foo"]) + tm.assert_series_equal(res, exp) + + res = df.max() + exp = pd.Series([pd.NaT], index=["foo"]) + tm.assert_series_equal(res, exp) diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index 452af895e4967..dea921a92ae37 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -54,29 +54,6 @@ def test_frame_append_datetime64_col_other_units(self): assert (tmp["dates"].values == ex_vals).all() - def test_operation_on_NaT(self): - # Both NaT and Timestamp are in DataFrame. - df = pd.DataFrame({"foo": [pd.NaT, pd.NaT, pd.Timestamp("2012-05-01")]}) - - res = df.min() - exp = pd.Series([pd.Timestamp("2012-05-01")], index=["foo"]) - tm.assert_series_equal(res, exp) - - res = df.max() - exp = pd.Series([pd.Timestamp("2012-05-01")], index=["foo"]) - tm.assert_series_equal(res, exp) - - # GH12941, only NaTs are in DataFrame. - df = pd.DataFrame({"foo": [pd.NaT, pd.NaT]}) - - res = df.min() - exp = pd.Series([pd.NaT], index=["foo"]) - tm.assert_series_equal(res, exp) - - res = df.max() - exp = pd.Series([pd.NaT], index=["foo"]) - tm.assert_series_equal(res, exp) - def test_datetime_assignment_with_NaT_and_diff_time_units(self): # GH 7492 data_ns = np.array([1, "nat"], dtype="datetime64[ns]") diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index 5882f5c77428b..58e2afc869e02 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -476,6 +476,13 @@ def test_get_loc_reasonable_key_error(self): index.get_loc("1/1/2000") +class TestContains: + def test_index_dupes_contains(self): + d = datetime(2011, 12, 5, 20, 30) + ix = DatetimeIndex([d, d]) + assert d in ix + + class TestDatetimeIndex: @pytest.mark.parametrize( "null", [None, np.nan, np.datetime64("NaT"), pd.NaT, pd.NA] diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py index b5d04fd499c08..18c11f2b9eb61 100644 --- a/pandas/tests/series/indexing/test_datetime.py +++ b/pandas/tests/series/indexing/test_datetime.py @@ -464,12 +464,6 @@ def test_index_unique(dups): assert idx.nunique(dropna=False) == 21 -def test_index_dupes_contains(): - d = datetime(2011, 12, 5, 20, 30) - ix = DatetimeIndex([d, d]) - assert d in ix - - def test_duplicate_dates_indexing(dups): ts = dups @@ -705,15 +699,6 @@ def test_set_none_nan(): assert series[6] is NaT -def test_nat_operations(): - # GH 8617 - s = Series([0, pd.NaT], dtype="m8[ns]") - exp = s[0] - assert s.median() == exp - assert s.min() == exp - assert s.max() == exp - - def test_setitem_tuple_with_datetimetz(): # GH 20441 arr = date_range("2017", periods=4, tz="US/Eastern") diff --git a/pandas/tests/series/test_reductions.py b/pandas/tests/series/test_reductions.py new file mode 100644 index 0000000000000..be9330a14f9c9 --- /dev/null +++ b/pandas/tests/series/test_reductions.py @@ -0,0 +1,11 @@ +import pandas as pd +from pandas import Series + + +def test_reductions_td64_with_nat(): + # GH#8617 + ser = Series([0, pd.NaT], dtype="m8[ns]") + exp = ser[0] + assert ser.median() == exp + assert ser.min() == exp + assert ser.max() == exp
https://api.github.com/repos/pandas-dev/pandas/pulls/33307
2020-04-05T20:14:50Z
2020-04-06T21:53:20Z
2020-04-06T21:53:20Z
2020-04-06T22:37:23Z
REGR: Fix construction of PeriodIndex from strings
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 584e21e87390d..cd55a4098b542 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -388,6 +388,7 @@ Datetimelike - :class:`Timestamp` raising confusing error message when year, month or day is missing (:issue:`31200`) - Bug in :class:`DatetimeIndex` constructor incorrectly accepting ``bool``-dtyped inputs (:issue:`32668`) - Bug in :meth:`DatetimeIndex.searchsorted` not accepting a ``list`` or :class:`Series` as its argument (:issue:`32762`) +- Bug where :meth:`PeriodIndex` raised when passed a :class:`Series` of strings (:issue:`26109`) - Bug in :class:`Timestamp` arithmetic when adding or subtracting a ``np.ndarray`` with ``timedelta64`` dtype (:issue:`33296`) Timedelta diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 39a3b553b3cf4..99d9d69d66ec2 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -831,11 +831,11 @@ def period_array( """ if is_datetime64_dtype(data): return PeriodArray._from_datetime64(data, freq) - if isinstance(data, (ABCPeriodIndex, ABCSeries, PeriodArray)): + if is_period_dtype(data): return PeriodArray(data, freq) # other iterable of some kind - if not isinstance(data, (np.ndarray, list, tuple)): + if not isinstance(data, (np.ndarray, list, tuple, ABCSeries)): data = list(data) data = np.asarray(data) diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index fe35344f46688..7eb0e46ab8f1e 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -10,7 +10,7 @@ import pandas._testing as tm from pandas.core.arrays import DatetimeArray, PeriodArray, TimedeltaArray from pandas.core.indexes.datetimes import DatetimeIndex -from pandas.core.indexes.period import PeriodIndex +from pandas.core.indexes.period import Period, PeriodIndex from pandas.core.indexes.timedeltas import TimedeltaIndex @@ -897,3 +897,13 @@ def test_searchsorted_datetimelike_with_listlike_invalid_dtype(values, arg): msg = "[Unexpected type|Cannot compare]" with pytest.raises(TypeError, match=msg): values.searchsorted(arg) + + +@pytest.mark.parametrize("klass", [list, tuple, np.array, pd.Series]) +def test_period_index_construction_from_strings(klass): + # https://github.com/pandas-dev/pandas/issues/26109 + strings = ["2020Q1", "2020Q2"] * 2 + data = klass(strings) + result = PeriodIndex(data, freq="Q") + expected = PeriodIndex([Period(s) for s in strings]) + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/arrays/test_period.py b/pandas/tests/arrays/test_period.py index 0b95d3aa19366..d3ced2f1b1f07 100644 --- a/pandas/tests/arrays/test_period.py +++ b/pandas/tests/arrays/test_period.py @@ -37,6 +37,7 @@ def test_registered(): ([pd.Period("2017", "D"), None], None, [17167, iNaT]), (pd.Series(pd.date_range("2017", periods=3)), None, [17167, 17168, 17169]), (pd.date_range("2017", periods=3), None, [17167, 17168, 17169]), + (pd.period_range("2017", periods=4, freq="Q"), None, [188, 189, 190, 191]), ], ) def test_period_array_ok(data, freq, expected):
- [ ] closes #26109 - [ ] 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/33304
2020-04-05T16:45:53Z
2020-04-10T17:29:56Z
2020-04-10T17:29:56Z
2020-04-10T17:36:30Z
DOC/CLN: remove versionadded/changed:: 0.21
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index 31241287c61cb..ba7f7eb907f4a 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -791,7 +791,7 @@ the ``pandas.util._decorators.deprecate``: from pandas.util._decorators import deprecate - deprecate('old_func', 'new_func', '0.21.0') + deprecate('old_func', 'new_func', '1.1.0') Otherwise, you need to do it manually: @@ -803,7 +803,7 @@ Otherwise, you need to do it manually: def old_func(): """Summary of the function. - .. deprecated:: 0.21.0 + .. deprecated:: 1.1.0 Use new_func instead. """ warnings.warn('Use new_func instead.', FutureWarning, stacklevel=2) @@ -1354,9 +1354,9 @@ directive is used. The sphinx syntax for that is: .. code-block:: rst - .. versionadded:: 0.21.0 + .. versionadded:: 1.1.0 -This will put the text *New in version 0.21.0* wherever you put the sphinx +This will put the text *New in version 1.1.0* wherever you put the sphinx directive. This should also be put in the docstring when adding a new function or method (`example <https://github.com/pandas-dev/pandas/blob/v0.20.2/pandas/core/frame.py#L1495>`__) or a new keyword argument (`example <https://github.com/pandas-dev/pandas/blob/v0.20.2/pandas/core/generic.py#L568>`__). diff --git a/doc/source/user_guide/basics.rst b/doc/source/user_guide/basics.rst index aa93f37a313f9..055b43bc1e59b 100644 --- a/doc/source/user_guide/basics.rst +++ b/doc/source/user_guide/basics.rst @@ -1224,8 +1224,6 @@ following can be done: This means that the reindexed Series's index is the same Python object as the DataFrame's index. -.. versionadded:: 0.21.0 - :meth:`DataFrame.reindex` also supports an "axis-style" calling convention, where you specify a single ``labels`` argument and the ``axis`` it applies to. @@ -1435,8 +1433,6 @@ Series can also be used: If the mapping doesn't include a column/index label, it isn't renamed. Note that extra labels in the mapping don't throw an error. -.. versionadded:: 0.21.0 - :meth:`DataFrame.rename` also supports an "axis-style" calling convention, where you specify a single ``mapper`` and the ``axis`` to apply that mapping to. diff --git a/doc/source/user_guide/categorical.rst b/doc/source/user_guide/categorical.rst index a55326db748fd..d4faf527a4790 100644 --- a/doc/source/user_guide/categorical.rst +++ b/doc/source/user_guide/categorical.rst @@ -211,8 +211,6 @@ To get back to the original ``Series`` or NumPy array, use CategoricalDtype ---------------- -.. versionchanged:: 0.21.0 - A categorical's type is fully described by 1. ``categories``: a sequence of unique values and no missing values diff --git a/doc/source/user_guide/groupby.rst b/doc/source/user_guide/groupby.rst index 8cd229070e365..b06c3afa6dfe8 100644 --- a/doc/source/user_guide/groupby.rst +++ b/doc/source/user_guide/groupby.rst @@ -1327,8 +1327,6 @@ See the :ref:`visualization documentation<visualization.box>` for more. Piping function calls ~~~~~~~~~~~~~~~~~~~~~ -.. versionadded:: 0.21.0 - Similar to the functionality provided by ``DataFrame`` and ``Series``, functions that take ``GroupBy`` objects can be chained together using a ``pipe`` method to allow for a cleaner, more readable syntax. To read about ``.pipe`` in general terms, diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index d68dc24bae658..a4cc1f9ee02ca 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -461,8 +461,6 @@ specification: pd.read_csv(StringIO(data), dtype={'col1': 'category'}).dtypes -.. versionadded:: 0.21.0 - Specifying ``dtype='category'`` will result in an unordered ``Categorical`` whose ``categories`` are the unique values observed in the data. For more control on the categories and order, create a @@ -2171,8 +2169,6 @@ Line delimited json pandas is able to read and write line-delimited json files that are common in data processing pipelines using Hadoop or Spark. -.. versionadded:: 0.21.0 - For line-delimited json files, pandas can also return an iterator which reads in ``chunksize`` lines at a time. This can be useful for large files or to read from a stream. .. ipython:: python @@ -4646,8 +4642,6 @@ Read from a feather file. Parquet ------- -.. versionadded:: 0.21.0 - `Apache Parquet <https://parquet.apache.org/>`__ provides a partitioned binary columnar serialization for data frames. It is designed to make reading and writing data frames efficient, and to make sharing data across data analysis languages easy. Parquet can use a variety of compression techniques to shrink the file size as much as possible diff --git a/doc/source/user_guide/merging.rst b/doc/source/user_guide/merging.rst index 49f4bbb6beb19..0450c81958a51 100644 --- a/doc/source/user_guide/merging.rst +++ b/doc/source/user_guide/merging.rst @@ -573,8 +573,6 @@ all standard database join operations between ``DataFrame`` or named ``Series`` dataset. * "many_to_many" or "m:m": allowed, but does not result in checks. - .. versionadded:: 0.21.0 - .. note:: Support for specifying index levels as the ``on``, ``left_on``, and @@ -773,8 +771,6 @@ Here is another example with duplicate join keys in DataFrames: Checking for duplicate keys ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -.. versionadded:: 0.21.0 - Users can use the ``validate`` argument to automatically check whether there are unexpected duplicates in their merge keys. Key uniqueness is checked before merge operations and so should protect against memory overflows. Checking key diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 9802b29b1dbc7..276c2d5198831 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -1197,8 +1197,6 @@ def infer_dtype(value: object, skipna: bool = True) -> str: skipna : bool, default True Ignore NaN values when inferring the type. - .. versionadded:: 0.21.0 - Returns ------- str diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 55c42f59f865e..ad82d68baa5b3 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -242,8 +242,6 @@ class Categorical(ExtensionArray, PandasObject): dtype : CategoricalDtype An instance of ``CategoricalDtype`` to use for this categorical. - .. versionadded:: 0.21.0 - Attributes ---------- categories : Index @@ -257,8 +255,6 @@ class Categorical(ExtensionArray, PandasObject): The instance of ``CategoricalDtype`` storing the ``categories`` and ``ordered``. - .. versionadded:: 0.21.0 - Methods ------- from_codes @@ -876,8 +872,6 @@ def rename_categories(self, new_categories, inplace=False): are passed through and extra categories in the mapping are ignored. - .. versionadded:: 0.21.0. - * callable : a callable that is called on all items in the old categories and whose return values comprise the new categories. @@ -1306,7 +1300,6 @@ def __setstate__(self, state): if not isinstance(state, dict): raise Exception("invalid pickle state") - # compat with pre 0.21.0 CategoricalDtype change if "_dtype" not in state: state["_dtype"] = CategoricalDtype(state["_categories"], state["_ordered"]) diff --git a/pandas/core/common.py b/pandas/core/common.py index 4ff1a93737d41..8b152162dc95a 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -357,8 +357,6 @@ def standardize_mapping(into): """ Helper function to standardize a supplied mapping. - .. versionadded:: 0.21.0 - Parameters ---------- into : instance or subclass of collections.abc.Mapping diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 17c4c6ba1c701..4be5da9c4c54a 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -189,8 +189,6 @@ class CategoricalDtype(PandasExtensionDtype, ExtensionDtype): """ Type for categorical data with the categories and orderedness. - .. versionchanged:: 0.21.0 - Parameters ---------- categories : sequence, optional diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 71b755bbf9665..ddb7be405d77a 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -245,8 +245,6 @@ dataset. * "many_to_many" or "m:m": allowed, but does not result in checks. - .. versionadded:: 0.21.0 - Returns ------- DataFrame @@ -1339,8 +1337,6 @@ def to_dict(self, orient="dict", into=dict): instance of the mapping type you want. If you want a collections.defaultdict, you must pass it initialized. - .. versionadded:: 0.21.0 - Returns ------- dict, list or collections.abc.Mapping @@ -2118,8 +2114,6 @@ def to_parquet( """ Write a DataFrame to the binary parquet format. - .. versionadded:: 0.21.0 - This function writes the dataframe as a `parquet file <https://parquet.apache.org/>`_. You can choose different parquet backends, and have the option of compression. See @@ -3749,13 +3743,9 @@ def drop( index : single label or list-like Alternative to specifying axis (``labels, axis=0`` is equivalent to ``index=labels``). - - .. versionadded:: 0.21.0 columns : single label or list-like Alternative to specifying axis (``labels, axis=1`` is equivalent to ``columns=labels``). - - .. versionadded:: 0.21.0 level : int or level name, optional For MultiIndex, level from which the labels will be removed. inplace : bool, default False diff --git a/pandas/core/generic.py b/pandas/core/generic.py index c202bf846047f..9640c1e087f47 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -526,13 +526,6 @@ def set_axis(self, labels, axis: Axis = 0, inplace: bool = False): Indexes for%(extended_summary_sub)s row labels can be changed by assigning a list-like or Index. - .. versionchanged:: 0.21.0 - - The signature is now `labels` and `axis`, consistent with - the rest of pandas API. Previously, the `axis` and `labels` - arguments were respectively the first and second positional - arguments. - Parameters ---------- labels : list-like, Index @@ -1178,8 +1171,6 @@ def _set_axis_name(self, name, axis=0, inplace=False): inplace : bool, default False If `True`, do operation inplace and return None. - .. versionadded:: 0.21.0 - Returns ------- Series, DataFrame, or None @@ -2146,7 +2137,6 @@ def to_json( only used when the first argument is a filename. By default, the compression is inferred from the filename. - .. versionadded:: 0.21.0 .. versionchanged:: 0.24.0 'infer' option added and set to default index : bool, default True @@ -2663,7 +2653,6 @@ def to_pickle( parameter is equivalent to setting its value to HIGHEST_PROTOCOL. .. [1] https://docs.python.org/3/library/pickle.html. - .. versionadded:: 0.21.0. See Also -------- @@ -3794,8 +3783,6 @@ def reindex_like( the same size as the index and its dtype must exactly match the index's type. - .. versionadded:: 0.21.0 (list-like tolerance) - Returns ------- Series or DataFrame @@ -4235,8 +4222,6 @@ def reindex(self: FrameOrSeries, *args, **kwargs) -> FrameOrSeries: the same size as the index and its dtype must exactly match the index's type. - .. versionadded:: 0.21.0 (list-like tolerance) - Returns ------- %(klass)s with changed index. @@ -5750,8 +5735,6 @@ def infer_objects(self: FrameOrSeries) -> FrameOrSeries: columns unchanged. The inference rules are the same as during normal Series/DataFrame construction. - .. versionadded:: 0.21.0 - Returns ------- converted : same type as input object @@ -7287,8 +7270,6 @@ def clip( Align object with lower and upper along the given axis. inplace : bool, default False Whether to perform the operation in place on the data. - - .. versionadded:: 0.21.0 *args, **kwargs Additional keywords have no effect but might be accepted for compatibility with numpy. diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 5fec68d257167..b97f0366579b3 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2836,8 +2836,6 @@ def get_loc(self, key, method=None, tolerance=None): the index at the matching location most satisfy the equation ``abs(index[loc] - key) <= tolerance``. - .. versionadded:: 0.21.0 (list-like tolerance) - Returns ------- loc : int if unique index, slice if monotonic index, else mask @@ -2909,8 +2907,6 @@ def get_loc(self, key, method=None, tolerance=None): the same size as the index and its dtype must exactly match the index's type. - .. versionadded:: 0.21.0 (list-like tolerance) - Returns ------- indexer : ndarray of int diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 073e1967678ec..635bf32639075 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -91,8 +91,6 @@ class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate): dtype : CategoricalDtype or "category", optional If :class:`CategoricalDtype`, cannot be used together with `categories` or `ordered`. - - .. versionadded:: 0.21.0 copy : bool, default False Make a copy of input ndarray. name : object, optional diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 92c3b9125d269..68d6229e798f5 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -1014,16 +1014,10 @@ def bdate_range( Weekmask of valid business days, passed to ``numpy.busdaycalendar``, only used when custom frequency strings are passed. The default value None is equivalent to 'Mon Tue Wed Thu Fri'. - - .. versionadded:: 0.21.0 - holidays : list-like or None, default None Dates to exclude from the set of valid business days, passed to ``numpy.busdaycalendar``, only used when custom frequency strings are passed. - - .. versionadded:: 0.21.0 - closed : str, default None Make the interval closed with respect to the given frequency to the 'left', 'right', or both sides (None). diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 2e1dcf8da5bd4..b17092caabdd1 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -467,8 +467,6 @@ def nearest(self, limit=None): limit : int, optional Limit of how many values to fill. - .. versionadded:: 0.21.0 - Returns ------- Series or DataFrame diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index b3b0166334413..17473ac26dfd6 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -500,9 +500,6 @@ def crosstab( margins_name : str, default 'All' Name of the row/column that will contain the totals when margins is True. - - .. versionadded:: 0.21.0 - dropna : bool, default True Do not include columns whose entries are all NaN. normalize : bool, {'all', 'index', 'columns'}, or {0,1}, default False diff --git a/pandas/core/series.py b/pandas/core/series.py index 03b82365358ac..2b073b3c5cebf 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1509,8 +1509,6 @@ def to_dict(self, into=dict): instance of the mapping type you want. If you want a collections.defaultdict, you must pass it initialized. - .. versionadded:: 0.21.0 - Returns ------- collections.abc.Mapping @@ -4067,12 +4065,8 @@ def drop( index : single label or list-like Redundant for application on Series, but 'index' can be used instead of 'labels'. - - .. versionadded:: 0.21.0 columns : single label or list-like No change is made to the Series; use 'index' or 'labels' instead. - - .. versionadded:: 0.21.0 level : int or level name, optional For MultiIndex, level for which the labels will be removed. inplace : bool, default False diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 718534e42ec25..fecdf3b758f0f 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -765,8 +765,6 @@ def where( Updates the HTML representation with a style which is selected in accordance with the return value of a function. - .. versionadded:: 0.21.0 - Parameters ---------- cond : callable diff --git a/pandas/io/html.py b/pandas/io/html.py index ce6674ffb9588..442a2791fc6e6 100644 --- a/pandas/io/html.py +++ b/pandas/io/html.py @@ -1057,8 +1057,6 @@ def read_html( the header, otherwise the function attempts to find the header within the body (by putting rows with only ``<th>`` elements into the header). - .. versionadded:: 0.21.0 - Similar to :func:`~read_csv` the `header` argument is applied **after** `skiprows` is applied. diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index d6b90ae99973e..b955b83dbfde5 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -490,9 +490,6 @@ def read_json( for more information on ``chunksize``. This can only be passed if `lines=True`. If this is None, the file will be read into memory all at once. - - .. versionadded:: 0.21.0 - compression : {'infer', 'gzip', 'bz2', 'zip', 'xz', None}, default 'infer' For on-the-fly decompression of on-disk data. If 'infer', then use gzip, bz2, zip or xz if path_or_buf is a string ending in @@ -500,8 +497,6 @@ def read_json( otherwise. If using 'zip', the ZIP file must contain only one data file to be read in. Set to None for no decompression. - .. versionadded:: 0.21.0 - Returns ------- Series or DataFrame diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index 9ae9729fc05ee..46320355512d1 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -260,8 +260,6 @@ def read_parquet(path, engine: str = "auto", columns=None, **kwargs): """ Load a parquet object from the file path, returning a DataFrame. - .. versionadded:: 0.21.0 - Parameters ---------- path : str, path object or file-like object @@ -287,8 +285,6 @@ def read_parquet(path, engine: str = "auto", columns=None, **kwargs): 'pyarrow' is unavailable. columns : list, default=None If not None, only these columns will be read from the file. - - .. versionadded:: 0.21.1 **kwargs Any additional kwargs are passed to the engine. diff --git a/pandas/io/pickle.py b/pandas/io/pickle.py index 4e731b8ecca11..6faebf56a11ab 100644 --- a/pandas/io/pickle.py +++ b/pandas/io/pickle.py @@ -43,7 +43,6 @@ def to_pickle( HIGHEST_PROTOCOL. .. [1] https://docs.python.org/3/library/pickle.html - .. versionadded:: 0.21.0 See Also -------- diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 8c213803170a3..3e4b25088e094 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -306,9 +306,6 @@ def read_hdf( By file-like object, we refer to objects with a ``read()`` method, such as a file handler (e.g. via builtin ``open`` function) or ``StringIO``. - - .. versionadded:: 0.21.0 support for __fspath__ protocol. - key : object, optional The group identifier in the store. Can be omitted if the HDF file contains a single pandas object. @@ -1462,8 +1459,6 @@ def info(self) -> str: """ Print detailed information on the store. - .. versionadded:: 0.21.0 - Returns ------- str
xref #29126
https://api.github.com/repos/pandas-dev/pandas/pulls/33301
2020-04-05T13:26:44Z
2020-04-05T19:21:30Z
2020-04-05T19:21:30Z
2020-04-13T14:41:51Z
BUG: DataFrame._item_cache not cleared on on .copy()
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index d283d4450e6bf..7cb7db27ae603 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -364,6 +364,7 @@ Indexing - Bug in :class:`Index` constructor where an unhelpful error message was raised for ``numpy`` scalars (:issue:`33017`) - Bug in :meth:`DataFrame.lookup` incorrectly raising an ``AttributeError`` when ``frame.index`` or ``frame.columns`` is not unique; this will now raise a ``ValueError`` with a helpful error message (:issue:`33041`) - Bug in :meth:`DataFrame.iloc.__setitem__` creating a new array instead of overwriting ``Categorical`` values in-place (:issue:`32831`) +- Bug in :meth:`DataFrame.copy` _item_cache not invalidated after copy causes post-copy value updates to not be reflected (:issue:`31784`) Missing ^^^^^^^ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 9640c1e087f47..82cc45ee16c00 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -5665,6 +5665,7 @@ def copy(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries: dtype: object """ data = self._data.copy(deep=deep) + self._clear_item_cache() return self._constructor(data).__finalize__(self) def __copy__(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries: diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index 91627b46c2fee..4149485be181d 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -540,3 +540,21 @@ def test_attrs(self): result = df.rename(columns=str) assert result.attrs == {"version": 1} + + def test_cache_on_copy(self): + # GH 31784 _item_cache not cleared on copy causes incorrect reads after updates + df = DataFrame({"a": [1]}) + + df["x"] = [0] + df["a"] + + df.copy() + + df["a"].values[0] = -1 + + tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0]})) + + df["y"] = [0] + + assert df["a"].values[0] == -1 + tm.assert_frame_equal(df, DataFrame({"a": [-1], "x": [0], "y": [0]}))
- [x] closes #31784 - [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/33299
2020-04-05T05:26:53Z
2020-04-06T14:33:38Z
2020-04-06T14:33:38Z
2020-04-07T19:52:35Z
CLN: assorted cleanups
diff --git a/pandas/_libs/tslibs/timedeltas.pxd b/pandas/_libs/tslibs/timedeltas.pxd index b08592755f2ee..d7af7636df753 100644 --- a/pandas/_libs/tslibs/timedeltas.pxd +++ b/pandas/_libs/tslibs/timedeltas.pxd @@ -1,6 +1,6 @@ from numpy cimport int64_t # Exposed for tslib, not intended for outside use. -cdef int64_t cast_from_unit(object ts, object unit) except? -1 +cdef int64_t cast_from_unit(object ts, str unit) except? -1 cpdef int64_t delta_to_nanoseconds(delta) except? -1 cdef convert_to_timedelta64(object ts, object unit) diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index f2b77f3517a25..3af2279e2440f 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -257,10 +257,15 @@ def array_to_timedelta64(object[:] values, unit='ns', errors='raise'): return iresult.base # .base to access underlying np.ndarray -cpdef inline object precision_from_unit(object unit): +cpdef inline object precision_from_unit(str unit): """ Return a casting of the unit represented to nanoseconds + the precision to round the fractional part. + + Notes + ----- + The caller is responsible for ensuring that the default value of "ns" + takes the place of None. """ cdef: int64_t m @@ -301,7 +306,7 @@ cpdef inline object precision_from_unit(object unit): return m, p -cdef inline int64_t cast_from_unit(object ts, object unit) except? -1: +cdef inline int64_t cast_from_unit(object ts, str unit) except? -1: """ return a casting of the unit represented to nanoseconds round the fractional part of a float to our precision, p """ cdef: @@ -525,15 +530,24 @@ cdef inline timedelta_from_spec(object number, object frac, object unit): return cast_from_unit(float(n), unit) -cpdef inline object parse_timedelta_unit(object unit): +cpdef inline str parse_timedelta_unit(object unit): """ Parameters ---------- - unit : an unit string + unit : str or None + + Returns + ------- + str + Canonical unit string. + + Raises + ------ + ValueError : on non-parseable input """ if unit is None: - return 'ns' - elif unit == 'M': + return "ns" + elif unit == "M": return unit try: return timedelta_abbrevs[unit.lower()] @@ -622,14 +636,14 @@ def _binary_op_method_timedeltalike(op, name): # ---------------------------------------------------------------------- # Timedelta Construction -cdef inline int64_t parse_iso_format_string(object ts) except? -1: +cdef inline int64_t parse_iso_format_string(str ts) except? -1: """ Extracts and cleanses the appropriate values from a match object with groups for each component of an ISO 8601 duration Parameters ---------- - ts: + ts: str ISO 8601 Duration formatted string Returns diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 3363d22686f96..9a49b9de2b5ef 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -4500,6 +4500,8 @@ def _reindex_with_indexers( allow_dups=allow_dups, copy=copy, ) + # If we've made a copy once, no need to make another one + copy = False if copy and new_data is self._mgr: new_data = new_data.copy() @@ -6459,7 +6461,6 @@ def replace( ): if not ( is_scalar(to_replace) - or isinstance(to_replace, pd.Series) or is_re_compilable(to_replace) or is_list_like(to_replace) ): diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index d0319e9181bad..df58593bc930c 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1,3 +1,4 @@ +from copy import copy as copy_func from datetime import datetime import operator from textwrap import dedent @@ -5313,7 +5314,7 @@ def _add_numeric_methods_unary(cls): Add in numeric unary methods. """ - def _make_evaluate_unary(op, opstr): + def _make_evaluate_unary(op, opstr: str_t): def _evaluate_numeric_unary(self): attrs = self._get_attributes_dict() @@ -5419,7 +5420,7 @@ def _add_logical_methods(cls): """ ) - def _make_logical_function(name, desc, f): + def _make_logical_function(name: str_t, desc: str_t, f): @Substitution(outname=name, desc=desc) @Appender(_index_shared_docs["index_" + name]) @Appender(_doc) @@ -5508,15 +5509,15 @@ def ensure_index_from_sequences(sequences, names=None): return MultiIndex.from_arrays(sequences, names=names) -def ensure_index(index_like, copy=False): +def ensure_index(index_like, copy: bool = False): """ Ensure that we have an index from some index-like object. Parameters ---------- - index : sequence + index_like : sequence An Index or other sequence - copy : bool + copy : bool, default False Returns ------- @@ -5567,9 +5568,7 @@ def ensure_index(index_like, copy=False): # clean_index_list does the equivalent of copying # so only need to do this if not list instance if copy: - from copy import copy - - index_like = copy(index_like) + index_like = copy_func(index_like) return Index(index_like) @@ -5596,7 +5595,7 @@ def _trim_front(strings): return trimmed -def _validate_join_method(method): +def _validate_join_method(method: str): if method not in ["left", "right", "inner", "outer"]: raise ValueError(f"do not recognize join method {method}") diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 06cd62c61b366..22a44d65a947a 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -625,7 +625,7 @@ def _ensure_listlike_indexer(self, key, axis=None): Parameters ---------- - key : _LocIndexer key or list-like of column labels + key : list-like of column labels Target labels. axis : key axis if known """ @@ -636,7 +636,7 @@ def _ensure_listlike_indexer(self, key, axis=None): return if isinstance(key, tuple): - # key may be a tuple if key is a _LocIndexer key + # key may be a tuple if we are .loc # in that case, set key to the column part of key key = key[column_axis] axis = column_axis @@ -649,9 +649,7 @@ def _ensure_listlike_indexer(self, key, axis=None): and all(is_hashable(k) for k in key) ): for k in key: - try: - self.obj[k] - except KeyError: + if k not in self.obj: self.obj[k] = np.nan def __setitem__(self, key, value): diff --git a/pandas/core/series.py b/pandas/core/series.py index 5ed8241101925..b74e80642dcdb 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -415,7 +415,7 @@ def _set_axis(self, axis: int, labels, fastpath: bool = False) -> None: object.__setattr__(self, "_index", labels) if not fastpath: - # The ensure_index call aabove ensures we have an Index object + # The ensure_index call above ensures we have an Index object self._mgr.set_axis(axis, labels) # ndarray compatibility
Mostly annotations
https://api.github.com/repos/pandas-dev/pandas/pulls/33297
2020-04-04T23:59:58Z
2020-04-07T23:08:25Z
2020-04-07T23:08:24Z
2020-04-07T23:30:08Z
BUG: Timestamp+- ndarray[td64]
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 8bff34dbdadad..2c417d89a40b0 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -304,6 +304,7 @@ Datetimelike - :class:`Timestamp` raising confusing error message when year, month or day is missing (:issue:`31200`) - Bug in :class:`DatetimeIndex` constructor incorrectly accepting ``bool``-dtyped inputs (:issue:`32668`) - Bug in :meth:`DatetimeIndex.searchsorted` not accepting a ``list`` or :class:`Series` as its argument (:issue:`32762`) +- Bug in :class:`Timestamp` arithmetic when adding or subtracting a ``np.ndarray`` with ``timedelta64`` dtype (:issue:`33296`) Timedelta ^^^^^^^^^ diff --git a/pandas/_libs/tslibs/c_timestamp.pyx b/pandas/_libs/tslibs/c_timestamp.pyx index 3c30460a74ece..04fadf220388f 100644 --- a/pandas/_libs/tslibs/c_timestamp.pyx +++ b/pandas/_libs/tslibs/c_timestamp.pyx @@ -253,6 +253,13 @@ cdef class _Timestamp(datetime): elif is_array(other): if other.dtype.kind in ['i', 'u']: raise integer_op_not_supported(self) + if other.dtype.kind == "m": + if self.tz is None: + return self.asm8 + other + return np.asarray( + [self + other[n] for n in range(len(other))], + dtype=object, + ) # index/series like elif hasattr(other, '_typ'): @@ -275,6 +282,13 @@ cdef class _Timestamp(datetime): elif is_array(other): if other.dtype.kind in ['i', 'u']: raise integer_op_not_supported(self) + if other.dtype.kind == "m": + if self.tz is None: + return self.asm8 - other + return np.asarray( + [self - other[n] for n in range(len(other))], + dtype=object, + ) typ = getattr(other, '_typ', None) if typ is not None: diff --git a/pandas/tests/scalar/timestamp/test_arithmetic.py b/pandas/tests/scalar/timestamp/test_arithmetic.py index ee70d1d0432fc..b038ee1aee106 100644 --- a/pandas/tests/scalar/timestamp/test_arithmetic.py +++ b/pandas/tests/scalar/timestamp/test_arithmetic.py @@ -6,6 +6,7 @@ from pandas.errors import OutOfBoundsDatetime from pandas import Timedelta, Timestamp +import pandas._testing as tm from pandas.tseries import offsets from pandas.tseries.frequencies import to_offset @@ -177,29 +178,6 @@ def test_timestamp_add_timedelta64_unit(self, other, expected_difference): valdiff = result.value - ts.value assert valdiff == expected_difference - @pytest.mark.parametrize("ts", [Timestamp.now(), Timestamp.now("utc")]) - @pytest.mark.parametrize( - "other", - [ - 1, - np.int64(1), - np.array([1, 2], dtype=np.int32), - np.array([3, 4], dtype=np.uint64), - ], - ) - def test_add_int_no_freq_raises(self, ts, other): - msg = "Addition/subtraction of integers and integer-arrays" - with pytest.raises(TypeError, match=msg): - ts + other - with pytest.raises(TypeError, match=msg): - other + ts - - with pytest.raises(TypeError, match=msg): - ts - other - msg = "unsupported operand type" - with pytest.raises(TypeError, match=msg): - other - ts - @pytest.mark.parametrize( "ts", [ @@ -229,3 +207,52 @@ def test_add_int_with_freq(self, ts, other): msg = "unsupported operand type" with pytest.raises(TypeError, match=msg): other - ts + + @pytest.mark.parametrize("shape", [(6,), (2, 3,)]) + def test_addsub_m8ndarray(self, shape): + # GH#33296 + ts = Timestamp("2020-04-04 15:45") + other = np.arange(6).astype("m8[h]").reshape(shape) + + result = ts + other + + ex_stamps = [ts + Timedelta(hours=n) for n in range(6)] + expected = np.array([x.asm8 for x in ex_stamps], dtype="M8[ns]").reshape(shape) + tm.assert_numpy_array_equal(result, expected) + + result = other + ts + tm.assert_numpy_array_equal(result, expected) + + result = ts - other + ex_stamps = [ts - Timedelta(hours=n) for n in range(6)] + expected = np.array([x.asm8 for x in ex_stamps], dtype="M8[ns]").reshape(shape) + tm.assert_numpy_array_equal(result, expected) + + msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timestamp'" + with pytest.raises(TypeError, match=msg): + other - ts + + @pytest.mark.parametrize("shape", [(6,), (2, 3,)]) + def test_addsub_m8ndarray_tzaware(self, shape): + # GH#33296 + ts = Timestamp("2020-04-04 15:45", tz="US/Pacific") + + other = np.arange(6).astype("m8[h]").reshape(shape) + + result = ts + other + + ex_stamps = [ts + Timedelta(hours=n) for n in range(6)] + expected = np.array(ex_stamps).reshape(shape) + tm.assert_numpy_array_equal(result, expected) + + result = other + ts + tm.assert_numpy_array_equal(result, expected) + + result = ts - other + ex_stamps = [ts - Timedelta(hours=n) for n in range(6)] + expected = np.array(ex_stamps).reshape(shape) + tm.assert_numpy_array_equal(result, expected) + + msg = r"unsupported operand type\(s\) for -: 'numpy.ndarray' and 'Timestamp'" + with pytest.raises(TypeError, match=msg): + other - ts
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Noticed a now-duplicate test that this gets rid of
https://api.github.com/repos/pandas-dev/pandas/pulls/33296
2020-04-04T22:55:57Z
2020-04-06T22:16:28Z
2020-04-06T22:16:28Z
2020-04-06T22:35:25Z
REF: make kwargs explicit in BlockManager methods
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index bd90325114ee1..d8b54fd5cffb3 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1282,7 +1282,7 @@ def diff(self, n: int, axis: int = 1) -> List["Block"]: new_values = _block_shape(new_values, ndim=self.ndim) return [self.make_block(values=new_values)] - def shift(self, periods, axis: int = 0, fill_value=None): + def shift(self, periods: int, axis: int = 0, fill_value=None): """ shift the block by periods, possibly upcast """ # convert integer to float if necessary. need to do a lot more than # that, handle boolean etc also diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 2f1206e800d9b..fa8799512ed05 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -545,14 +545,24 @@ def get_axe(block, qs, axes): def isna(self, func) -> "BlockManager": return self.apply("apply", func=func) - def where(self, **kwargs) -> "BlockManager": - if kwargs.pop("align", True): + def where( + self, other, cond, align: bool, errors: str, try_cast: bool, axis: int + ) -> "BlockManager": + if align: align_keys = ["other", "cond"] else: align_keys = ["cond"] - kwargs["other"] = extract_array(kwargs["other"], extract_numpy=True) + other = extract_array(other, extract_numpy=True) - return self.apply("where", align_keys=align_keys, **kwargs) + return self.apply( + "where", + align_keys=align_keys, + other=other, + cond=cond, + errors=errors, + try_cast=try_cast, + axis=axis, + ) def setitem(self, indexer, value) -> "BlockManager": return self.apply("setitem", indexer=indexer, value=value) @@ -584,11 +594,13 @@ def diff(self, n: int, axis: int) -> "BlockManager": def interpolate(self, **kwargs) -> "BlockManager": return self.apply("interpolate", **kwargs) - def shift(self, **kwargs) -> "BlockManager": - return self.apply("shift", **kwargs) + def shift(self, periods: int, axis: int, fill_value) -> "BlockManager": + return self.apply("shift", periods=periods, axis=axis, fill_value=fill_value) - def fillna(self, **kwargs) -> "BlockManager": - return self.apply("fillna", **kwargs) + def fillna(self, value, limit, inplace: bool, downcast) -> "BlockManager": + return self.apply( + "fillna", value=value, limit=limit, inplace=inplace, downcast=downcast + ) def downcast(self) -> "BlockManager": return self.apply("downcast") @@ -753,9 +765,7 @@ def combine(self, blocks: List[Block], copy: bool = True) -> "BlockManager": new_blocks = [] for b in blocks: b = b.copy(deep=copy) - b.mgr_locs = algos.take_1d( - inv_indexer, b.mgr_locs.as_array, axis=0, allow_fill=False - ) + b.mgr_locs = inv_indexer[b.mgr_locs.indexer] new_blocks.append(b) axes = list(self.axes)
https://api.github.com/repos/pandas-dev/pandas/pulls/33295
2020-04-04T20:36:12Z
2020-04-05T19:17:00Z
2020-04-05T19:17:00Z
2020-04-05T19:44:39Z
REF: BlockManager.combine -> _combine
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 2f1206e800d9b..59d3fbc306947 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -729,7 +729,7 @@ def get_bool_data(self, copy: bool = False) -> "BlockManager": Whether to copy the blocks """ self._consolidate_inplace() - return self.combine([b for b in self.blocks if b.is_bool], copy) + return self._combine([b for b in self.blocks if b.is_bool], copy) def get_numeric_data(self, copy: bool = False) -> "BlockManager": """ @@ -739,9 +739,9 @@ def get_numeric_data(self, copy: bool = False) -> "BlockManager": Whether to copy the blocks """ self._consolidate_inplace() - return self.combine([b for b in self.blocks if b.is_numeric], copy) + return self._combine([b for b in self.blocks if b.is_numeric], copy) - def combine(self, blocks: List[Block], copy: bool = True) -> "BlockManager": + def _combine(self, blocks: List[Block], copy: bool = True) -> "BlockManager": """ return a new manager with the blocks """ if len(blocks) == 0: return self.make_empty() @@ -896,7 +896,7 @@ def to_dict(self, copy: bool = True): for b in self.blocks: bd.setdefault(str(b.dtype), []).append(b) - return {dtype: self.combine(blocks, copy=copy) for dtype, blocks in bd.items()} + return {dtype: self._combine(blocks, copy=copy) for dtype, blocks in bd.items()} def fast_xs(self, loc: int) -> ArrayLike: """
https://api.github.com/repos/pandas-dev/pandas/pulls/33294
2020-04-04T20:24:10Z
2020-04-05T19:12:08Z
2020-04-05T19:12:08Z
2020-04-05T19:44:07Z
CLN: remove BlockManager.__contains__
diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 2f1206e800d9b..08131a977bda3 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -781,9 +781,6 @@ def get_slice(self, slobj: slice, axis: int = 0) -> "BlockManager": bm = type(self)(new_blocks, new_axes, do_integrity_check=False) return bm - def __contains__(self, item) -> bool: - return item in self.items - @property def nblocks(self) -> int: return len(self.blocks) diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 657849874f091..57fbc9ab13f84 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -301,10 +301,6 @@ def test_duplicate_ref_loc_failure(self): mgr = BlockManager(blocks, axes) mgr.iget(1) - def test_contains(self, mgr): - assert "a" in mgr - assert "baz" not in mgr - def test_pickle(self, mgr): mgr2 = tm.round_trip_pickle(mgr)
https://api.github.com/repos/pandas-dev/pandas/pulls/33293
2020-04-04T20:21:36Z
2020-04-05T20:04:27Z
2020-04-05T20:04:27Z
2020-04-05T20:08:46Z
REGR: Fix bug when replacing categorical value with self
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 7cb7db27ae603..5bd45e100c8cd 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -294,6 +294,7 @@ Categorical - Bug when passing categorical data to :class:`Index` constructor along with ``dtype=object`` incorrectly returning a :class:`CategoricalIndex` instead of object-dtype :class:`Index` (:issue:`32167`) - Bug where :class:`Categorical` comparison operator ``__ne__`` would incorrectly evaluate to ``False`` when either element was missing (:issue:`32276`) - :meth:`Categorical.fillna` now accepts :class:`Categorical` ``other`` argument (:issue:`32420`) +- Bug where :meth:`Categorical.replace` would replace with ``NaN`` whenever the new value and replacement value were equal (:issue:`33288`) Datetimelike ^^^^^^^^^^^^ diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index ad82d68baa5b3..c9b8db28e0cf6 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -2447,6 +2447,8 @@ def replace(self, to_replace, value, inplace: bool = False): # other cases, like if both to_replace and value are list-like or if # to_replace is a dict, are handled separately in NDFrame for replace_value, new_value in replace_dict.items(): + if new_value == replace_value: + continue if replace_value in cat.categories: if isna(new_value): cat.remove_categories(replace_value, inplace=True) diff --git a/pandas/tests/arrays/categorical/test_algos.py b/pandas/tests/arrays/categorical/test_algos.py index 10c454f7c479a..325fa476d70e6 100644 --- a/pandas/tests/arrays/categorical/test_algos.py +++ b/pandas/tests/arrays/categorical/test_algos.py @@ -64,6 +64,8 @@ def test_isin_cats(): [ ("b", "c", ["a", "c"], "Categorical.categories are different"), ("c", "d", ["a", "b"], None), + # https://github.com/pandas-dev/pandas/issues/33288 + ("a", "a", ["a", "b"], None), ("b", None, ["a", None], "Categorical.categories length are different"), ], )
- [ ] closes #33288 - [ ] 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/33292
2020-04-04T20:04:59Z
2020-04-06T22:01:57Z
2020-04-06T22:01:57Z
2020-05-26T09:35:15Z
DEPR: Index.is_mixed
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 8bff34dbdadad..d283d4450e6bf 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -256,6 +256,7 @@ Deprecations - :meth:`DataFrame.to_dict` has deprecated accepting short names for ``orient`` in future versions (:issue:`32515`) - :meth:`Categorical.to_dense` is deprecated and will be removed in a future version, use ``np.asarray(cat)`` instead (:issue:`32639`) - The ``fastpath`` keyword in the ``SingleBlockManager`` constructor is deprecated and will be removed in a future version (:issue:`33092`) +- :meth:`Index.is_mixed` is deprecated and will be removed in a future version, check ``index.inferred_type`` directly instead (:issue:`32922`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 5fec68d257167..394224e6a843f 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1955,6 +1955,12 @@ def is_mixed(self) -> bool: >>> idx.is_mixed() False """ + warnings.warn( + "Index.is_mixed is deprecated and will be removed in a future version. " + "Check index.inferred_type directly instead.", + FutureWarning, + stacklevel=2, + ) return self.inferred_type in ["mixed"] def holds_integer(self) -> bool: @@ -3135,7 +3141,7 @@ def is_int(v): # convert the slice to an indexer here # if we are mixed and have integers - if is_positional and self.is_mixed(): + if is_positional: try: # Validate start & stop if start is not None: diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 35ee81229b716..0417208868314 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1160,6 +1160,12 @@ def test_intersection_difference(self, indices, sort): diff = indices.difference(indices, sort=sort) tm.assert_index_equal(inter, diff) + def test_is_mixed_deprecated(self): + # GH#32922 + index = self.create_index() + with tm.assert_produces_warning(FutureWarning): + index.is_mixed() + @pytest.mark.parametrize( "indices, expected", [
- [x] closes #32922 - [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/33291
2020-04-04T20:01:59Z
2020-04-05T19:53:13Z
2020-04-05T19:53:13Z
2020-04-05T19:54:26Z
BUG: 2D indexing on DTA/TDA/PA
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index c0bbbebac7c33..4fabd8f558fee 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -550,10 +550,7 @@ def __getitem__(self, key): key = np.asarray(key, dtype=bool) key = check_array_indexer(self, key) - if key.all(): - key = slice(0, None, None) - else: - key = lib.maybe_booleans_to_slice(key.view(np.uint8)) + key = lib.maybe_booleans_to_slice(key.view(np.uint8)) elif isinstance(key, list) and len(key) == 1 and isinstance(key[0], slice): # see https://github.com/pandas-dev/pandas/issues/31299, need to allow # this for now (would otherwise raise in check_array_indexer) @@ -561,7 +558,7 @@ def __getitem__(self, key): else: key = check_array_indexer(self, key) - is_period = is_period_dtype(self) + is_period = is_period_dtype(self.dtype) if is_period: freq = self.freq else: @@ -577,11 +574,6 @@ def __getitem__(self, key): freq = self.freq result = getitem(key) - if result.ndim > 1: - # To support MPL which performs slicing with 2 dim - # even though it only has 1 dim by definition - return result - return self._simple_new(result, dtype=self.dtype, freq=freq) def __setitem__( diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index f38a4fb83c64f..c752990531b34 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -214,7 +214,10 @@ class ExtensionIndex(Index): def __getitem__(self, key): result = self._data[key] if isinstance(result, type(self._data)): - return type(self)(result, name=self.name) + if result.ndim == 1: + return type(self)(result, name=self.name) + # Unpack to ndarray for MPL compat + result = result._data # Includes cases where we get a 2D ndarray back for MPL compat deprecate_ndim_indexing(result) diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 83995ab26cb56..fe35344f46688 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -60,6 +60,12 @@ def timedelta_index(request): class SharedTests: index_cls: Type[Union[DatetimeIndex, PeriodIndex, TimedeltaIndex]] + @pytest.fixture + def arr1d(self): + data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9 + arr = self.array_cls(data, freq="D") + return arr + def test_compare_len1_raises(self): # make sure we raise when comparing with different lengths, specific # to the case where one has length-1, which numpy would broadcast @@ -204,6 +210,18 @@ def test_searchsorted(self): result = arr.searchsorted(pd.NaT) assert result == 0 + def test_getitem_2d(self, arr1d): + # 2d slicing on a 1D array + expected = type(arr1d)(arr1d._data[:, np.newaxis], dtype=arr1d.dtype) + result = arr1d[:, np.newaxis] + tm.assert_equal(result, expected) + + # Lookup on a 2D array + arr2d = expected + expected = type(arr2d)(arr2d._data[:3, 0], dtype=arr2d.dtype) + result = arr2d[:3, 0] + tm.assert_equal(result, expected) + def test_setitem(self): data = np.arange(10, dtype="i8") * 24 * 3600 * 10 ** 9 arr = self.array_cls(data, freq="D") @@ -265,6 +283,13 @@ class TestDatetimeArray(SharedTests): array_cls = DatetimeArray dtype = pd.Timestamp + @pytest.fixture + def arr1d(self, tz_naive_fixture): + tz = tz_naive_fixture + dti = pd.date_range("2016-01-01 01:01:00", periods=3, freq="H", tz=tz) + dta = dti._data + return dta + def test_round(self, tz_naive_fixture): # GH#24064 tz = tz_naive_fixture @@ -645,6 +670,10 @@ class TestPeriodArray(SharedTests): array_cls = PeriodArray dtype = pd.Period + @pytest.fixture + def arr1d(self, period_index): + return period_index._data + def test_from_pi(self, period_index): pi = period_index arr = PeriodArray(pi)
Broken off from #32997. The fixture this implements in the datetimelike tests can be used in a follow-up to clean up those tests a bit
https://api.github.com/repos/pandas-dev/pandas/pulls/33290
2020-04-04T19:23:36Z
2020-04-06T22:17:19Z
2020-04-06T22:17:19Z
2020-04-06T22:33:48Z
DOC: Improved doc for `Index.equals`
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 5fec68d257167..9a254a499ad82 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4193,15 +4193,64 @@ def putmask(self, mask, value): # coerces to object return self.astype(object).putmask(mask, value) - def equals(self, other) -> bool: + def equals(self, other: Any) -> bool: """ - Determine if two Index objects contain the same elements. + Determine if two Index object are equal. + + The things that are being compared are: + + * The elements inside the Index object. + * The order of the elements inside the Index object. + + Parameters + ---------- + other : Any + The other object to compare against. Returns ------- bool - True if "other" is an Index and it has the same elements as calling - index; False otherwise. + True if "other" is an Index and it has the same elements and order + as the calling index; False otherwise. + + Examples + -------- + >>> idx1 = pd.Index([1, 2, 3]) + >>> idx1 + Int64Index([1, 2, 3], dtype='int64') + >>> idx1.equals(pd.Index([1, 2, 3])) + True + + The elements inside are compared + + >>> idx2 = pd.Index(["1", "2", "3"]) + >>> idx2 + Index(['1', '2', '3'], dtype='object') + + >>> idx1.equals(idx2) + False + + The oreder is compared + + >>> ascending_idx = pd.Index([1, 2, 3]) + >>> ascending_idx + Int64Index([1, 2, 3], dtype='int64') + >>> descending_idx = pd.Index([3, 2, 1]) + >>> descending_idx + Int64Index([3, 2, 1], dtype='int64') + >>> ascending_idx.equals(descending_idx) + False + + The dtype is *not* compared + + >>> int64_idx = pd.Int64Index([1, 2, 3]) + >>> int64_idx + Int64Index([1, 2, 3], dtype='int64') + >>> uint64_idx = pd.UInt64Index([1, 2, 3]) + >>> uint64_idx + UInt64Index([1, 2, 3], dtype='uint64') + >>> int64_idx.equals(uint64_idx) + True """ if self.is_(other): return True
- [x] closes #33285 - [ ] 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/33289
2020-04-04T19:13:10Z
2020-04-06T08:29:12Z
2020-04-06T08:29:11Z
2020-04-06T08:29:43Z
CLN: Add/refine type hints to some functions in core.dtypes.cast
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index da9646aa8c46f..6cd0948f9beb8 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -3,6 +3,7 @@ """ from datetime import date, datetime, timedelta +from typing import TYPE_CHECKING, Type import numpy as np @@ -63,6 +64,7 @@ ABCDataFrame, ABCDatetimeArray, ABCDatetimeIndex, + ABCExtensionArray, ABCPeriodArray, ABCPeriodIndex, ABCSeries, @@ -70,6 +72,10 @@ from pandas.core.dtypes.inference import is_list_like from pandas.core.dtypes.missing import isna, notna +if TYPE_CHECKING: + from pandas import Series + from pandas.core.arrays import ExtensionArray # noqa: F401 + _int8_max = np.iinfo(np.int8).max _int16_max = np.iinfo(np.int16).max _int32_max = np.iinfo(np.int32).max @@ -246,9 +252,7 @@ def trans(x): return result -def maybe_cast_result( - result, obj: ABCSeries, numeric_only: bool = False, how: str = "" -): +def maybe_cast_result(result, obj: "Series", numeric_only: bool = False, how: str = ""): """ Try casting result to a different type if appropriate @@ -256,8 +260,8 @@ def maybe_cast_result( ---------- result : array-like Result to cast. - obj : ABCSeries - Input series from which result was calculated. + obj : Series + Input Series from which result was calculated. numeric_only : bool, default False Whether to cast only numerics or datetimes as well. how : str, default "" @@ -313,13 +317,13 @@ def maybe_cast_result_dtype(dtype: DtypeObj, how: str) -> DtypeObj: return d.get((dtype, how), dtype) -def maybe_cast_to_extension_array(cls, obj, dtype=None): +def maybe_cast_to_extension_array(cls: Type["ExtensionArray"], obj, dtype=None): """ Call to `_from_sequence` that returns the object unchanged on Exception. Parameters ---------- - cls : ExtensionArray subclass + cls : class, subclass of ExtensionArray obj : arraylike Values to pass to cls._from_sequence dtype : ExtensionDtype, optional @@ -329,6 +333,8 @@ def maybe_cast_to_extension_array(cls, obj, dtype=None): ExtensionArray or obj """ assert isinstance(cls, type), f"must pass a type: {cls}" + assertion_msg = f"must pass a subclass of ExtensionArray: {cls}" + assert issubclass(cls, ABCExtensionArray), assertion_msg try: result = cls._from_sequence(obj, dtype=dtype) except Exception: diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 093c925acbc49..88580f6ebb3ed 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -151,7 +151,7 @@ def pinner(cls): @pin_whitelisted_properties(Series, base.series_apply_whitelist) -class SeriesGroupBy(GroupBy): +class SeriesGroupBy(GroupBy[Series]): _apply_whitelist = base.series_apply_whitelist def _iterate_slices(self) -> Iterable[Series]: @@ -815,7 +815,7 @@ def pct_change(self, periods=1, fill_method="pad", limit=None, freq=None): @pin_whitelisted_properties(DataFrame, base.dataframe_apply_whitelist) -class DataFrameGroupBy(GroupBy): +class DataFrameGroupBy(GroupBy[DataFrame]): _apply_whitelist = base.dataframe_apply_whitelist @@ -1462,7 +1462,7 @@ def _transform_fast(self, result: DataFrame, func_nm: str) -> DataFrame: for i, _ in enumerate(result.columns): res = algorithms.take_1d(result.iloc[:, i].values, ids) # TODO: we have no test cases that get here with EA dtypes; - # try_cast may not be needed if EAs never get here + # maybe_cast_result may not be needed if EAs never get here if cast: res = maybe_cast_result(res, obj.iloc[:, i], how=func_nm) output.append(res) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index ebdb0062491be..4d19f6a79ff87 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -17,6 +17,7 @@ class providing the base-class of operations. Callable, Dict, FrozenSet, + Generic, Hashable, Iterable, List, @@ -24,6 +25,7 @@ class providing the base-class of operations. Optional, Tuple, Type, + TypeVar, Union, ) @@ -353,13 +355,13 @@ def _group_selection_context(groupby): ] -class _GroupBy(PandasObject, SelectionMixin): +class _GroupBy(PandasObject, SelectionMixin, Generic[FrameOrSeries]): _group_selection = None _apply_whitelist: FrozenSet[str] = frozenset() def __init__( self, - obj: NDFrame, + obj: FrameOrSeries, keys: Optional[_KeysArgType] = None, axis: int = 0, level=None, @@ -995,7 +997,11 @@ def _apply_filter(self, indices, dropna): return filtered -class GroupBy(_GroupBy): +# To track operations that expand dimensions, like ohlc +OutputFrameOrSeries = TypeVar("OutputFrameOrSeries", bound=NDFrame) + + +class GroupBy(_GroupBy[FrameOrSeries]): """ Class for grouping and aggregating relational data. @@ -2420,8 +2426,8 @@ def tail(self, n=5): return self._selected_obj[mask] def _reindex_output( - self, output: FrameOrSeries, fill_value: Scalar = np.NaN - ) -> FrameOrSeries: + self, output: OutputFrameOrSeries, fill_value: Scalar = np.NaN + ) -> OutputFrameOrSeries: """ If we have categorical groupers, then we might want to make sure that we have a fully re-indexed output to the levels. This means expanding diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 742de397956c0..8d535374a083f 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -682,7 +682,7 @@ def _aggregate_series_pure_python(self, obj: Series, func): assert result is not None result = lib.maybe_convert_objects(result, try_float=0) - # TODO: try_cast back to EA? + # TODO: maybe_cast_to_extension_array? return result, counts
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Some cleanup resulting from PR #32894. In order to get SeriesGroupBy._transform_fast to realize self.obj is a Series, it seemed I needed to add a generic type to GroupBy and _GroupBy. I don't know if there is a better way to do this. Here, one cannot use FrameOrSeries as a Series may return a DataFrame and vice-versa, so I added _GroupByT.
https://api.github.com/repos/pandas-dev/pandas/pulls/33286
2020-04-04T16:18:53Z
2020-04-05T19:39:56Z
2020-04-05T19:39:56Z
2020-07-11T16:02:14Z
BUG: fix boolean array skipna=False for .any() and .all()
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 5c39377899a20..83989002c1e89 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -452,7 +452,7 @@ Missing ^^^^^^^ - Calling :meth:`fillna` on an empty Series now correctly returns a shallow copied object. The behaviour is now consistent with :class:`Index`, :class:`DataFrame` and a non-empty :class:`Series` (:issue:`32543`). - +- Bug in :meth:`~Series.any` and :meth:`~Series.all` incorrectly returning ``<NA>`` for all ``False`` or all ``True`` values using the nulllable boolean dtype and with ``skipna=False`` (:issue:`33253`) MultiIndex ^^^^^^^^^^ diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index e85534def6b97..7ffbd0d595565 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -520,7 +520,7 @@ def any(self, skipna: bool = True, **kwargs): if skipna: return result else: - if result or len(self) == 0: + if result or len(self) == 0 or not self._mask.any(): return result else: return self.dtype.na_value @@ -587,7 +587,7 @@ def all(self, skipna: bool = True, **kwargs): if skipna: return result else: - if not result or len(self) == 0: + if not result or len(self) == 0 or not self._mask.any(): return result else: return self.dtype.na_value diff --git a/pandas/tests/arrays/boolean/test_reduction.py b/pandas/tests/arrays/boolean/test_reduction.py index ce50266c756a8..5dd5620162a8a 100644 --- a/pandas/tests/arrays/boolean/test_reduction.py +++ b/pandas/tests/arrays/boolean/test_reduction.py @@ -19,6 +19,9 @@ def data(): ([False, pd.NA], False, False, pd.NA, False), ([pd.NA], False, True, pd.NA, pd.NA), ([], False, True, False, True), + # GH-33253: all True / all False values buggy with skipna=False + ([True, True], True, True, True, True), + ([False, False], False, False, False, False), ], ) def test_any_all(values, exp_any, exp_all, exp_any_noskip, exp_all_noskip): diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index 8fb035e085d40..fa62d5d8c4983 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -891,6 +891,30 @@ def test_all_any_params(self): with pytest.raises(NotImplementedError): s.all(bool_only=True) + def test_all_any_boolean(self): + # Check skipna, with boolean type + s1 = Series([pd.NA, True], dtype="boolean") + s2 = Series([pd.NA, False], dtype="boolean") + assert s1.all(skipna=False) is pd.NA # NA && True => NA + assert s1.all(skipna=True) + assert s2.any(skipna=False) is pd.NA # NA || False => NA + assert not s2.any(skipna=True) + + # GH-33253: all True / all False values buggy with skipna=False + s3 = Series([True, True], dtype="boolean") + s4 = Series([False, False], dtype="boolean") + assert s3.all(skipna=False) + assert not s4.any(skipna=False) + + # Check level TODO(GH-33449) result should also be boolean + s = pd.Series( + [False, False, True, True, False, True], + index=[0, 0, 1, 1, 2, 2], + dtype="boolean", + ) + tm.assert_series_equal(s.all(level=0), Series([False, True, False])) + tm.assert_series_equal(s.any(level=0), Series([False, True, True])) + def test_timedelta64_analytics(self): # index min/max
- [x] closes #33253 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry I added "not self._mask.any()" to check if there is no missing value for both .any() and .all() when skipna is False. It looks fine for the example you provided. ![any_all](https://user-images.githubusercontent.com/43714531/78453697-65cc1400-7661-11ea-9666-2fef60f2e81e.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/33284
2020-04-04T14:36:37Z
2020-04-10T08:37:17Z
2020-04-10T08:37:16Z
2020-04-10T08:37:27Z
DOC: Fix EX01 in DataFrame.drop_duplicates
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 71b755bbf9665..1f73efed82cb9 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4673,6 +4673,47 @@ def drop_duplicates( See Also -------- DataFrame.value_counts: Count unique combinations of columns. + + Examples + -------- + Consider dataset containing ramen rating. + + >>> df = pd.DataFrame({ + ... 'brand': ['Yum Yum', 'Yum Yum', 'Indomie', 'Indomie', 'Indomie'], + ... 'style': ['cup', 'cup', 'cup', 'pack', 'pack'], + ... 'rating': [4, 4, 3.5, 15, 5] + ... }) + >>> df + brand style rating + 0 Yum Yum cup 4.0 + 1 Yum Yum cup 4.0 + 2 Indomie cup 3.5 + 3 Indomie pack 15.0 + 4 Indomie pack 5.0 + + By default, it removes duplicate rows based on all columns. + + >>> df.drop_duplicates() + brand style rating + 0 Yum Yum cup 4.0 + 2 Indomie cup 3.5 + 3 Indomie pack 15.0 + 4 Indomie pack 5.0 + + To remove duplicates on specific column(s), use ``subset``. + + >>> df.drop_duplicates(subset=['brand']) + brand style rating + 0 Yum Yum cup 4.0 + 2 Indomie cup 3.5 + + To remove duplicates and keep last occurences, use ``keep``. + + >>> df.drop_duplicates(subset=['brand', 'style'], keep='last') + brand style rating + 1 Yum Yum cup 4.0 + 2 Indomie cup 3.5 + 4 Indomie pack 5.0 """ if self.empty: return self.copy()
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Related to #27977. ``` ################################################################################ ################################## Validation ################################## ################################################################################
https://api.github.com/repos/pandas-dev/pandas/pulls/33283
2020-04-04T12:15:30Z
2020-04-10T17:51:59Z
2020-04-10T17:51:59Z
2020-04-10T17:52:03Z
DOC: Fix error in Series.clip and DataFrame.clip
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 0ecfbce460b3a..c202bf846047f 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -7299,6 +7299,12 @@ def clip( Same type as calling object with the values outside the clip boundaries replaced. + See Also + -------- + Series.clip : Trim values at input threshold in series. + DataFrame.clip : Trim values at input threshold in dataframe. + numpy.clip : Clip (limit) the values in an array. + Examples -------- >>> data = {'col_0': [9, -3, 0, -1, 5], 'col_1': [-2, -7, 6, 8, -5]}
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Related to #27977. output of `python scripts/validate_docstrings.py pandas.Series.clip and pandas.DataFrame.clip`: ``` ################################################################################ ################################## Validation ################################## ################################################################################ ```
https://api.github.com/repos/pandas-dev/pandas/pulls/33282
2020-04-04T10:13:53Z
2020-04-04T21:23:03Z
2020-04-04T21:23:03Z
2020-04-04T21:23:10Z
Troubleshoot Travis
diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index d9071a80b5db7..b74abc965f7fa 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -15,6 +15,16 @@ from pandas import DataFrame, DatetimeIndex, Series, Timestamp, read_json import pandas._testing as tm +_seriesd = tm.getSeriesData() + +_frame = DataFrame(_seriesd) + +_cat_frame = _frame.copy() +cat = ["bah"] * 5 + ["bar"] * 5 + ["baz"] * 5 + ["foo"] * (len(_cat_frame) - 15) +_cat_frame.index = pd.CategoricalIndex(cat, name="E") +_cat_frame["E"] = list(reversed(cat)) +_cat_frame["sort"] = np.arange(len(_cat_frame), dtype="int64") + def assert_json_roundtrip_equal(result, expected, orient): if orient == "records" or orient == "values": @@ -26,6 +36,12 @@ def assert_json_roundtrip_equal(result, expected, orient): @pytest.mark.filterwarnings("ignore:the 'numpy' keyword is deprecated:FutureWarning") class TestPandasContainer: + @pytest.fixture(autouse=True) + def setup(self): + self.categorical = _cat_frame.copy() + + yield + def test_frame_double_encoded_labels(self, orient): df = DataFrame( [["a", "b"], ["c", "d"]], @@ -167,21 +183,25 @@ def test_roundtrip_str_axes(self, orient, convert_axes, numpy, dtype): @pytest.mark.parametrize("convert_axes", [True, False]) @pytest.mark.parametrize("numpy", [True, False]) def test_roundtrip_categorical(self, orient, convert_axes, numpy): - cats = ["a", "b"] - df = pd.DataFrame( - pd.Categorical(cats), index=pd.CategoricalIndex(cats), columns=["cat"] - ) + # TODO: create a better frame to test with and improve coverage + if orient in ("index", "columns"): + pytest.xfail(f"Can't have duplicate index values for orient '{orient}')") - data = df.to_json(orient=orient) - if numpy and orient != "split": + data = self.categorical.to_json(orient=orient) + if numpy and orient in ("records", "values"): pytest.xfail(f"Orient {orient} is broken with numpy=True") result = pd.read_json( data, orient=orient, convert_axes=convert_axes, numpy=numpy ) - # Categorical dtypes are not preserved on round trip - expected = pd.DataFrame(cats, index=cats, columns=["cat"]) + expected = self.categorical.copy() + expected.index = expected.index.astype(str) # Categorical not preserved + expected.index.name = None # index names aren't preserved in JSON + + if not numpy and orient == "index": + expected = expected.sort_index() + assert_json_roundtrip_equal(result, expected, orient) @pytest.mark.parametrize("convert_axes", [True, False])
Reverts #33228, which appears to be the first build that started failing on Travis.
https://api.github.com/repos/pandas-dev/pandas/pulls/33280
2020-04-04T00:59:49Z
2020-04-04T17:15:47Z
2020-04-04T17:15:47Z
2020-04-04T17:17:08Z
API/CLN: simplify CategoricalBlock.replace
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 2cc0bb07bd17f..e267a7a4e5bd5 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2761,18 +2761,9 @@ def replace( ): inplace = validate_bool_kwarg(inplace, "inplace") result = self if inplace else self.copy() - if filter is None: # replace was called on a series - result.values.replace(to_replace, value, inplace=True) - if convert: - return result.convert(numeric=False, copy=not inplace) - else: - return result - else: # replace was called on a DataFrame - if not isna(value): - result.values.add_categories(value, inplace=True) - return super(CategoricalBlock, result).replace( - to_replace, value, inplace, filter, regex, convert - ) + + result.values.replace(to_replace, value, inplace=True) + return result # ----------------------------------------------------------------- diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index ee89562261b19..a9fb686d5bc50 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -1303,9 +1303,15 @@ def test_replace_method(self, to_replace, method, expected): def test_categorical_replace_with_dict(self, replace_dict, final_data): # GH 26988 df = DataFrame([[1, 1], [2, 2]], columns=["a", "b"], dtype="category") - expected = DataFrame(final_data, columns=["a", "b"], dtype="category") - expected["a"] = expected["a"].cat.set_categories([1, 2, 3]) - expected["b"] = expected["b"].cat.set_categories([1, 2, 3]) + + final_data = np.array(final_data) + + a = pd.Categorical(final_data[:, 0], categories=[3, 2]) + + excat = [3, 2] if replace_dict["b"] == 1 else [1, 3] + b = pd.Categorical(final_data[:, 1], categories=excat) + + expected = DataFrame({"a": a, "b": b}) result = df.replace(replace_dict, 3) tm.assert_frame_equal(result, expected) with pytest.raises(AssertionError):
- [x] closes #33272 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Makes DataFrame.replace on Categorical behave like Series.replace.
https://api.github.com/repos/pandas-dev/pandas/pulls/33279
2020-04-04T00:52:22Z
2020-04-06T21:16:03Z
2020-04-06T21:16:03Z
2020-04-06T21:26:20Z
CLN 31942/replace appender with doc 3
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index b522920ec9f23..ec98ade5c4b2f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2183,9 +2183,10 @@ def to_feather(self, path, **kwargs) -> None: to_feather(self, path, **kwargs) - @Appender( - """ - Examples + @doc( + Series.to_markdown, + klass=_shared_doc_kwargs["klass"], + examples="""Examples -------- >>> df = pd.DataFrame( ... data={"animal_1": ["elk", "pig"], "animal_2": ["dog", "quetzal"]} @@ -2206,10 +2207,8 @@ def to_feather(self, path, **kwargs) -> None: +----+------------+------------+ | 1 | pig | quetzal | +----+------------+------------+ - """ + """, ) - @Substitution(klass="DataFrame") - @Appender(_shared_docs["to_markdown"]) def to_markdown( self, buf: Optional[IO[str]] = None, mode: Optional[str] = None, **kwargs ) -> Optional[str]: @@ -4758,20 +4757,20 @@ def _maybe_casted_values(index, labels=None): # ---------------------------------------------------------------------- # Reindex-based selection methods - @Appender(_shared_docs["isna"] % _shared_doc_kwargs) + @doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"]) def isna(self) -> "DataFrame": result = self._constructor(self._data.isna(func=isna)) return result.__finalize__(self, method="isna") - @Appender(_shared_docs["isna"] % _shared_doc_kwargs) + @doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"]) def isnull(self) -> "DataFrame": return self.isna() - @Appender(_shared_docs["notna"] % _shared_doc_kwargs) + @doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"]) def notna(self) -> "DataFrame": return ~self.isna() - @Appender(_shared_docs["notna"] % _shared_doc_kwargs) + @doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"]) def notnull(self) -> "DataFrame": return ~self.isna() @@ -7330,13 +7329,14 @@ def _gotitem( """ ) - @Substitution( + @doc( + _shared_docs["aggregate"], + klass=_shared_doc_kwargs["klass"], + axis=_shared_doc_kwargs["axis"], see_also=_agg_summary_and_see_also_doc, examples=_agg_examples_doc, versionadded="\n.. versionadded:: 0.20.0\n", - **_shared_doc_kwargs, ) - @Appender(_shared_docs["aggregate"]) def aggregate(self, func, axis=0, *args, **kwargs): axis = self._get_axis_number(axis) @@ -7364,7 +7364,11 @@ def _aggregate(self, arg, axis=0, *args, **kwargs): agg = aggregate - @Appender(_shared_docs["transform"] % _shared_doc_kwargs) + @doc( + NDFrame.transform, + klass=_shared_doc_kwargs["klass"], + axis=_shared_doc_kwargs["axis"], + ) def transform(self, func, axis=0, *args, **kwargs) -> "DataFrame": axis = self._get_axis_number(axis) if axis == 1: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index bad61a440b8c5..707b1b7fda4f4 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -853,7 +853,7 @@ def rename( copy : bool, default True Also copy underlying data. inplace : bool, default False - Whether to return a new %(klass)s. If True then value of copy is + Whether to return a new {klass}. If True then value of copy is ignored. level : int or level name, default None In case of a MultiIndex, only rename labels in the specified @@ -867,7 +867,7 @@ def rename( Returns ------- - renamed : %(klass)s (new object) + renamed : {klass} (new object) Raises ------ @@ -1903,29 +1903,6 @@ def _repr_data_resource_(self): # ---------------------------------------------------------------------- # I/O Methods - _shared_docs[ - "to_markdown" - ] = """ - Print %(klass)s in Markdown-friendly format. - - .. versionadded:: 1.0.0 - - Parameters - ---------- - buf : str, Path or StringIO-like, optional, default None - Buffer to write to. If None, the output is returned as a string. - mode : str, optional - Mode in which file is opened. - **kwargs - These parameters will be passed to `tabulate \ - <https://pypi.org/project/tabulate>`_. - - Returns - ------- - str - %(klass)s in Markdown-friendly format. - """ - @doc(klass="object") def to_excel( self, @@ -4242,9 +4219,15 @@ def sort_values( """ raise AbstractMethodError(self) + @doc( + klass=_shared_doc_kwargs["klass"], + axes=_shared_doc_kwargs["axes"], + optional_labels="", + optional_axis="", + ) def reindex(self: FrameOrSeries, *args, **kwargs) -> FrameOrSeries: """ - Conform %(klass)s to new index with optional filling logic. + Conform {klass} to new index with optional filling logic. Places NA/NaN in locations having no value in the previous index. A new object is produced unless the new index is equivalent to the current one and @@ -4252,12 +4235,12 @@ def reindex(self: FrameOrSeries, *args, **kwargs) -> FrameOrSeries: Parameters ---------- - %(optional_labels)s - %(axes)s : array-like, optional + {optional_labels} + {axes} : array-like, optional New labels / index to conform to, should be specified using keywords. Preferably an Index object to avoid duplicating data. - %(optional_axis)s - method : {None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'} + {optional_axis} + method : {{None, 'backfill'/'bfill', 'pad'/'ffill', 'nearest'}} Method to use for filling holes in reindexed DataFrame. Please note: this is only applicable to DataFrames/Series with a monotonically increasing/decreasing index. @@ -4291,7 +4274,7 @@ def reindex(self: FrameOrSeries, *args, **kwargs) -> FrameOrSeries: Returns ------- - %(klass)s with changed index. + {klass} with changed index. See Also -------- @@ -4304,7 +4287,7 @@ def reindex(self: FrameOrSeries, *args, **kwargs) -> FrameOrSeries: ``DataFrame.reindex`` supports two calling conventions * ``(index=index_labels, columns=column_labels, ...)`` - * ``(labels, axis={'index', 'columns'}, ...)`` + * ``(labels, axis={{'index', 'columns'}}, ...)`` We *highly* recommend using keyword arguments to clarify your intent. @@ -4312,8 +4295,8 @@ def reindex(self: FrameOrSeries, *args, **kwargs) -> FrameOrSeries: Create a dataframe with some fictional data. >>> index = ['Firefox', 'Chrome', 'Safari', 'IE10', 'Konqueror'] - >>> df = pd.DataFrame({'http_status': [200, 200, 404, 404, 301], - ... 'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]}, + >>> df = pd.DataFrame({{'http_status': [200, 200, 404, 404, 301], + ... 'response_time': [0.04, 0.02, 0.07, 0.08, 1.0]}}, ... index=index) >>> df http_status response_time @@ -4384,7 +4367,7 @@ def reindex(self: FrameOrSeries, *args, **kwargs) -> FrameOrSeries: of dates). >>> date_index = pd.date_range('1/1/2010', periods=6, freq='D') - >>> df2 = pd.DataFrame({"prices": [100, 101, np.nan, 100, 89, 88]}, + >>> df2 = pd.DataFrame({{"prices": [100, 101, np.nan, 100, 89, 88]}}, ... index=date_index) >>> df2 prices @@ -5018,19 +5001,19 @@ def sample( locs = rs.choice(axis_length, size=n, replace=replace, p=weights) return self.take(locs, axis=axis) - _shared_docs[ - "pipe" - ] = r""" + @doc(klass=_shared_doc_kwargs["klass"]) + def pipe(self, func, *args, **kwargs): + r""" Apply func(self, \*args, \*\*kwargs). Parameters ---------- func : function - Function to apply to the %(klass)s. + Function to apply to the {klass}. ``args``, and ``kwargs`` are passed into ``func``. Alternatively a ``(callable, data_keyword)`` tuple where ``data_keyword`` is a string indicating the keyword of - ``callable`` that expects the %(klass)s. + ``callable`` that expects the {klass}. args : iterable, optional Positional arguments passed into ``func``. kwargs : mapping, optional @@ -5070,121 +5053,49 @@ def sample( ... .pipe((func, 'arg2'), arg1=a, arg3=c) ... ) # doctest: +SKIP """ - - @Appender(_shared_docs["pipe"] % _shared_doc_kwargs) - def pipe(self, func, *args, **kwargs): return com.pipe(self, func, *args, **kwargs) _shared_docs["aggregate"] = dedent( """ - Aggregate using one or more operations over the specified axis. - %(versionadded)s - Parameters - ---------- - func : function, str, list or dict - Function to use for aggregating the data. If a function, must either - work when passed a %(klass)s or when passed to %(klass)s.apply. - - Accepted combinations are: - - - function - - string function name - - list of functions and/or function names, e.g. ``[np.sum, 'mean']`` - - dict of axis labels -> functions, function names or list of such. - %(axis)s - *args - Positional arguments to pass to `func`. - **kwargs - Keyword arguments to pass to `func`. - - Returns - ------- - scalar, Series or DataFrame - - The return can be: - - * scalar : when Series.agg is called with single function - * Series : when DataFrame.agg is called with a single function - * DataFrame : when DataFrame.agg is called with several functions - - Return scalar, Series or DataFrame. - %(see_also)s - Notes - ----- - `agg` is an alias for `aggregate`. Use the alias. - - A passed user-defined-function will be passed a Series for evaluation. - %(examples)s""" - ) + Aggregate using one or more operations over the specified axis. + {versionadded} + Parameters + ---------- + func : function, str, list or dict + Function to use for aggregating the data. If a function, must either + work when passed a {klass} or when passed to {klass}.apply. + + Accepted combinations are: + + - function + - string function name + - list of functions and/or function names, e.g. ``[np.sum, 'mean']`` + - dict of axis labels -> functions, function names or list of such. + {axis} + *args + Positional arguments to pass to `func`. + **kwargs + Keyword arguments to pass to `func`. - _shared_docs[ - "transform" - ] = """ - Call ``func`` on self producing a %(klass)s with transformed values. + Returns + ------- + scalar, Series or DataFrame - Produced %(klass)s will have same axis length as self. + The return can be: - Parameters - ---------- - func : function, str, list or dict - Function to use for transforming the data. If a function, must either - work when passed a %(klass)s or when passed to %(klass)s.apply. - - Accepted combinations are: - - - function - - string function name - - list of functions and/or function names, e.g. ``[np.exp. 'sqrt']`` - - dict of axis labels -> functions, function names or list of such. - %(axis)s - *args - Positional arguments to pass to `func`. - **kwargs - Keyword arguments to pass to `func`. - - Returns - ------- - %(klass)s - A %(klass)s that must have the same length as self. - - Raises - ------ - ValueError : If the returned %(klass)s has a different length than self. - - See Also - -------- - %(klass)s.agg : Only perform aggregating type operations. - %(klass)s.apply : Invoke function on a %(klass)s. - - Examples - -------- - >>> df = pd.DataFrame({'A': range(3), 'B': range(1, 4)}) - >>> df - A B - 0 0 1 - 1 1 2 - 2 2 3 - >>> df.transform(lambda x: x + 1) - A B - 0 1 2 - 1 2 3 - 2 3 4 - - Even though the resulting %(klass)s must have the same length as the - input %(klass)s, it is possible to provide several input functions: - - >>> s = pd.Series(range(3)) - >>> s - 0 0 - 1 1 - 2 2 - dtype: int64 - >>> s.transform([np.sqrt, np.exp]) - sqrt exp - 0 0.000000 1.000000 - 1 1.000000 2.718282 - 2 1.414214 7.389056 - """ + * scalar : when Series.agg is called with single function + * Series : when DataFrame.agg is called with a single function + * DataFrame : when DataFrame.agg is called with several functions + + Return scalar, Series or DataFrame. + {see_also} + Notes + ----- + `agg` is an alias for `aggregate`. Use the alias. + + A passed user-defined-function will be passed a Series for evaluation. + {examples}""" + ) # ---------------------------------------------------------------------- # Attribute access @@ -6199,7 +6110,7 @@ def ffill( Returns ------- - %(klass)s or None + {klass} or None Object with missing values filled or None if ``inplace=True``. """ return self.fillna( @@ -6220,7 +6131,7 @@ def bfill( Returns ------- - %(klass)s or None + {klass} or None Object with missing values filled or None if ``inplace=True``. """ return self.fillna( @@ -6691,9 +6602,18 @@ def replace( else: return result.__finalize__(self, method="replace") - _shared_docs[ - "interpolate" - ] = """ + def interpolate( + self: FrameOrSeries, + method: str = "linear", + axis: Axis = 0, + limit: Optional[int] = None, + inplace: bool_t = False, + limit_direction: Optional[str] = None, + limit_area: Optional[str] = None, + downcast: Optional[str] = None, + **kwargs, + ) -> Optional[FrameOrSeries]: + """ Please note that only ``method='linear'`` is supported for DataFrame/Series with a MultiIndex. @@ -6721,14 +6641,14 @@ def replace( `scipy.interpolate.BPoly.from_derivatives` which replaces 'piecewise_polynomial' interpolation method in scipy 0.18. - axis : {0 or 'index', 1 or 'columns', None}, default None + axis : {{0 or 'index', 1 or 'columns', None}}, default None Axis to interpolate along. limit : int, optional Maximum number of consecutive NaNs to fill. Must be greater than 0. inplace : bool, default False Update the data in place if possible. - limit_direction : {'forward', 'backward', 'both'}, Optional + limit_direction : {{'forward', 'backward', 'both'}}, Optional Consecutive NaNs will be filled in this direction. If limit is specified: @@ -6746,7 +6666,7 @@ def replace( raises ValueError if `limit_direction` is 'backward' or 'both' and method is 'pad' or 'ffill'. - limit_area : {`None`, 'inside', 'outside'}, default None + limit_area : {{`None`, 'inside', 'outside'}}, default None If limit is specified, consecutive NaNs will be filled with this restriction. @@ -6888,22 +6808,6 @@ def replace( 3 16.0 Name: d, dtype: float64 """ - - @Appender(_shared_docs["interpolate"] % _shared_doc_kwargs) - def interpolate( - self: FrameOrSeries, - method: str = "linear", - axis: Axis = 0, - limit: Optional[int] = None, - inplace: bool_t = False, - limit_direction: Optional[str] = None, - limit_area: Optional[str] = None, - downcast: Optional[str] = None, - **kwargs, - ) -> Optional[FrameOrSeries]: - """ - Interpolate values according to different methods. - """ inplace = validate_bool_kwarg(inplace, "inplace") axis = self._get_axis_number(axis) @@ -7159,9 +7063,9 @@ def asof(self, where, subset=None): # ---------------------------------------------------------------------- # Action Methods - _shared_docs[ - "isna" - ] = """ + @doc(klass=_shared_doc_kwargs["klass"]) + def isna(self: FrameOrSeries) -> FrameOrSeries: + """ Detect missing values. Return a boolean same-sized object indicating if the values are NA. @@ -7173,26 +7077,26 @@ def asof(self, where, subset=None): Returns ------- - %(klass)s - Mask of bool values for each element in %(klass)s that + {klass} + Mask of bool values for each element in {klass} that indicates whether an element is not an NA value. See Also -------- - %(klass)s.isnull : Alias of isna. - %(klass)s.notna : Boolean inverse of isna. - %(klass)s.dropna : Omit axes labels with missing values. + {klass}.isnull : Alias of isna. + {klass}.notna : Boolean inverse of isna. + {klass}.dropna : Omit axes labels with missing values. isna : Top-level isna. Examples -------- Show which entries in a DataFrame are NA. - >>> df = pd.DataFrame({'age': [5, 6, np.NaN], + >>> df = pd.DataFrame({{'age': [5, 6, np.NaN], ... 'born': [pd.NaT, pd.Timestamp('1939-05-27'), ... pd.Timestamp('1940-04-25')], ... 'name': ['Alfred', 'Batman', ''], - ... 'toy': [None, 'Batmobile', 'Joker']}) + ... 'toy': [None, 'Batmobile', 'Joker']}}) >>> df age born name toy 0 5.0 NaT Alfred None @@ -7220,18 +7124,15 @@ def asof(self, where, subset=None): 2 True dtype: bool """ - - @Appender(_shared_docs["isna"] % _shared_doc_kwargs) - def isna(self: FrameOrSeries) -> FrameOrSeries: return isna(self).__finalize__(self, method="isna") - @Appender(_shared_docs["isna"] % _shared_doc_kwargs) + @doc(isna, klass=_shared_doc_kwargs["klass"]) def isnull(self: FrameOrSeries) -> FrameOrSeries: return isna(self).__finalize__(self, method="isnull") - _shared_docs[ - "notna" - ] = """ + @doc(klass=_shared_doc_kwargs["klass"]) + def notna(self: FrameOrSeries) -> FrameOrSeries: + """ Detect existing (non-missing) values. Return a boolean same-sized object indicating if the values are not NA. @@ -7243,26 +7144,26 @@ def isnull(self: FrameOrSeries) -> FrameOrSeries: Returns ------- - %(klass)s - Mask of bool values for each element in %(klass)s that + {klass} + Mask of bool values for each element in {klass} that indicates whether an element is not an NA value. See Also -------- - %(klass)s.notnull : Alias of notna. - %(klass)s.isna : Boolean inverse of notna. - %(klass)s.dropna : Omit axes labels with missing values. + {klass}.notnull : Alias of notna. + {klass}.isna : Boolean inverse of notna. + {klass}.dropna : Omit axes labels with missing values. notna : Top-level notna. Examples -------- Show which entries in a DataFrame are not NA. - >>> df = pd.DataFrame({'age': [5, 6, np.NaN], + >>> df = pd.DataFrame({{'age': [5, 6, np.NaN], ... 'born': [pd.NaT, pd.Timestamp('1939-05-27'), ... pd.Timestamp('1940-04-25')], ... 'name': ['Alfred', 'Batman', ''], - ... 'toy': [None, 'Batmobile', 'Joker']}) + ... 'toy': [None, 'Batmobile', 'Joker']}}) >>> df age born name toy 0 5.0 NaT Alfred None @@ -7290,12 +7191,9 @@ def isnull(self: FrameOrSeries) -> FrameOrSeries: 2 False dtype: bool """ - - @Appender(_shared_docs["notna"] % _shared_doc_kwargs) - def notna(self: FrameOrSeries) -> FrameOrSeries: return notna(self).__finalize__(self, method="notna") - @Appender(_shared_docs["notna"] % _shared_doc_kwargs) + @doc(notna, klass=_shared_doc_kwargs["klass"]) def notnull(self: FrameOrSeries) -> FrameOrSeries: return notna(self).__finalize__(self, method="notnull") @@ -8977,32 +8875,47 @@ def _where( result = self._constructor(new_data) return result.__finalize__(self) - _shared_docs[ - "where" - ] = """ - Replace values where the condition is %(cond_rev)s. + @doc( + klass=_shared_doc_kwargs["klass"], + cond="True", + cond_rev="False", + name="where", + name_other="mask", + ) + def where( + self, + cond, + other=np.nan, + inplace=False, + axis=None, + level=None, + errors="raise", + try_cast=False, + ): + """ + Replace values where the condition is {cond_rev}. Parameters ---------- - cond : bool %(klass)s, array-like, or callable - Where `cond` is %(cond)s, keep the original value. Where - %(cond_rev)s, replace with corresponding value from `other`. - If `cond` is callable, it is computed on the %(klass)s and - should return boolean %(klass)s or array. The callable must - not change input %(klass)s (though pandas doesn't check it). - other : scalar, %(klass)s, or callable - Entries where `cond` is %(cond_rev)s are replaced with + cond : bool {klass}, array-like, or callable + Where `cond` is {cond}, keep the original value. Where + {cond_rev}, replace with corresponding value from `other`. + If `cond` is callable, it is computed on the {klass} and + should return boolean {klass} or array. The callable must + not change input {klass} (though pandas doesn't check it). + other : scalar, {klass}, or callable + Entries where `cond` is {cond_rev} are replaced with corresponding value from `other`. - If other is callable, it is computed on the %(klass)s and - should return scalar or %(klass)s. The callable must not - change input %(klass)s (though pandas doesn't check it). + If other is callable, it is computed on the {klass} and + should return scalar or {klass}. The callable must not + change input {klass} (though pandas doesn't check it). inplace : bool, default False Whether to perform the operation in place on the data. axis : int, default None Alignment axis if needed. level : int, default None Alignment level if needed. - errors : str, {'raise', 'ignore'}, default 'raise' + errors : str, {{'raise', 'ignore'}}, default 'raise' Note that currently this parameter won't affect the results and will always coerce to a suitable dtype. @@ -9018,13 +8931,13 @@ def _where( See Also -------- - :func:`DataFrame.%(name_other)s` : Return an object of same shape as + :func:`DataFrame.{name_other}` : Return an object of same shape as self. Notes ----- - The %(name)s method is an application of the if-then idiom. For each - element in the calling DataFrame, if ``cond`` is ``%(cond)s`` the + The {name} method is an application of the if-then idiom. For each + element in the calling DataFrame, if ``cond`` is ``{cond}`` the element is used; otherwise the corresponding element from the DataFrame ``other`` is used. @@ -9032,7 +8945,7 @@ def _where( :func:`numpy.where`. Roughly ``df1.where(m, df2)`` is equivalent to ``np.where(m, df1, df2)``. - For further details and examples see the ``%(name)s`` documentation in + For further details and examples see the ``{name}`` documentation in :ref:`indexing <indexing.where_mask>`. Examples @@ -9070,7 +8983,7 @@ def _where( 2 4 5 3 6 7 4 8 9 - >>> m = df %% 3 == 0 + >>> m = df % 3 == 0 >>> df.where(m, -df) A B 0 0 -1 @@ -9093,42 +9006,18 @@ def _where( 3 True True 4 True True """ - - @Appender( - _shared_docs["where"] - % dict( - _shared_doc_kwargs, - cond="True", - cond_rev="False", - name="where", - name_other="mask", - ) - ) - def where( - self, - cond, - other=np.nan, - inplace=False, - axis=None, - level=None, - errors="raise", - try_cast=False, - ): - other = com.apply_if_callable(other, self) return self._where( cond, other, inplace, axis, level, errors=errors, try_cast=try_cast ) - @Appender( - _shared_docs["where"] - % dict( - _shared_doc_kwargs, - cond="False", - cond_rev="True", - name="mask", - name_other="where", - ) + @doc( + where, + klass=_shared_doc_kwargs["klass"], + cond="False", + cond_rev="True", + name="mask", + name_other="where", ) def mask( self, @@ -9518,7 +9407,7 @@ def tz_convert( Returns ------- - %(klass)s + {klass} Object with time zone converted axis. Raises @@ -10141,9 +10030,15 @@ def describe_1d(data): d.columns = data.columns.copy() return d - _shared_docs[ - "pct_change" - ] = """ + def pct_change( + self: FrameOrSeries, + periods=1, + fill_method="pad", + limit=None, + freq=None, + **kwargs, + ) -> FrameOrSeries: + """ Percentage change between the current and a prior element. Computes the percentage change from the immediately previous row by @@ -10257,17 +10152,6 @@ def describe_1d(data): GOOG NaN -0.151997 -0.086016 APPL NaN 0.337604 0.012002 """ - - @Appender(_shared_docs["pct_change"] % _shared_doc_kwargs) - def pct_change( - self: FrameOrSeries, - periods=1, - fill_method="pad", - limit=None, - freq=None, - **kwargs, - ) -> FrameOrSeries: - # TODO: Not sure if above is correct - need someone to confirm. axis = self._get_axis_number(kwargs.pop("axis", self._stat_axis_name)) if fill_method is None: data = self @@ -10327,18 +10211,35 @@ def _add_numeric_operations(cls): empty_value=True, ) - @Substitution( + @doc( desc="Return the mean absolute deviation of the values " "for the requested axis.", name1=name1, name2=name2, axis_descr=axis_descr, - min_count="", see_also="", examples="", ) - @Appender(_num_doc_mad) def mad(self, axis=None, skipna=None, level=None): + """ + {desc} + + Parameters + ---------- + axis : {axis_descr} + Axis for the function to be applied on. + skipna : bool, default None + Exclude NA/null values when computing the result. + level : int or level name, default None + If the axis is a MultiIndex (hierarchical), count along a + particular level, collapsing into a {name1}. + + Returns + ------- + {name1} or {name2} (if level specified)\ + {see_also}\ + {examples} + """ if skipna is None: skipna = True if axis is None: @@ -10603,8 +10504,74 @@ def ewm( cls.ewm = ewm - @Appender(_shared_docs["transform"] % dict(axis="", **_shared_doc_kwargs)) + @doc(klass=_shared_doc_kwargs["klass"], axis="") def transform(self, func, *args, **kwargs): + """ + Call ``func`` on self producing a {klass} with transformed values. + + Produced {klass} will have same axis length as self. + + Parameters + ---------- + func : function, str, list or dict + Function to use for transforming the data. If a function, must either + work when passed a {klass} or when passed to {klass}.apply. + + Accepted combinations are: + + - function + - string function name + - list of functions and/or function names, e.g. ``[np.exp. 'sqrt']`` + - dict of axis labels -> functions, function names or list of such. + {axis} + *args + Positional arguments to pass to `func`. + **kwargs + Keyword arguments to pass to `func`. + + Returns + ------- + {klass} + A {klass} that must have the same length as self. + + Raises + ------ + ValueError : If the returned {klass} has a different length than self. + + See Also + -------- + {klass}.agg : Only perform aggregating type operations. + {klass}.apply : Invoke function on a {klass}. + + Examples + -------- + >>> df = pd.DataFrame({{'A': range(3), 'B': range(1, 4)}}) + >>> df + A B + 0 0 1 + 1 1 2 + 2 2 3 + >>> df.transform(lambda x: x + 1) + A B + 0 1 2 + 1 2 3 + 2 3 4 + + Even though the resulting {klass} must have the same length as the + input {klass}, it is possible to provide several input functions: + + >>> s = pd.Series(range(3)) + >>> s + 0 0 + 1 1 + 2 2 + dtype: int64 + >>> s.transform([np.sqrt, np.exp]) + sqrt exp + 0 0.000000 1.000000 + 1 1.000000 2.718282 + 2 1.414214 7.389056 + """ result = self.agg(func, *args, **kwargs) if is_scalar(result) or len(result) != len(self): raise ValueError("transforms cannot produce aggregated results") @@ -10614,21 +10581,6 @@ def transform(self, func, *args, **kwargs): # ---------------------------------------------------------------------- # Misc methods - _shared_docs[ - "valid_index" - ] = """ - Return index for %(position)s non-NA/null value. - - Returns - ------- - scalar : type of index - - Notes - ----- - If all elements are non-NA/null, returns None. - Also returns None for empty %(klass)s. - """ - def _find_valid_index(self, how: str): """ Retrieves the index of the first valid value. @@ -10647,15 +10599,23 @@ def _find_valid_index(self, how: str): return None return self.index[idxpos] - @Appender( - _shared_docs["valid_index"] % {"position": "first", "klass": "Series/DataFrame"} - ) + @doc(position="first", klass=_shared_doc_kwargs["klass"]) def first_valid_index(self): + """ + Return index for {position} non-NA/null value. + + Returns + ------- + scalar : type of index + + Notes + ----- + If all elements are non-NA/null, returns None. + Also returns None for empty {klass}. + """ return self._find_valid_index("first") - @Appender( - _shared_docs["valid_index"] % {"position": "last", "klass": "Series/DataFrame"} - ) + @doc(first_valid_index, position="last", klass=_shared_doc_kwargs["klass"]) def last_valid_index(self): return self._find_valid_index("last") @@ -10696,26 +10656,6 @@ def _doc_parms(cls): %(examples)s """ -_num_doc_mad = """ -%(desc)s - -Parameters ----------- -axis : %(axis_descr)s - Axis for the function to be applied on. -skipna : bool, default None - Exclude NA/null values when computing the result. -level : int or level name, default None - If the axis is a MultiIndex (hierarchical), count along a - particular level, collapsing into a %(name1)s. - -Returns -------- -%(name1)s or %(name2)s (if level specified)\ -%(see_also)s\ -%(examples)s -""" - _num_ddof_doc = """ %(desc)s diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index db5df9818b0b0..128f7cd6cd90c 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -224,10 +224,9 @@ def _selection_name(self): def apply(self, func, *args, **kwargs): return super().apply(func, *args, **kwargs) - @Substitution( - examples=_agg_examples_doc, klass="Series", + @doc( + _agg_template, examples=_agg_examples_doc, klass="Series", ) - @Appender(_agg_template) def aggregate( self, func=None, *args, engine="cython", engine_kwargs=None, **kwargs ): @@ -915,10 +914,9 @@ class DataFrameGroupBy(GroupBy[DataFrame]): See :ref:`groupby.aggregate.named` for more.""" ) - @Substitution( - examples=_agg_examples_doc, klass="DataFrame", + @doc( + _agg_template, examples=_agg_examples_doc, klass="DataFrame", ) - @Appender(_agg_template) def aggregate( self, func=None, *args, engine="cython", engine_kwargs=None, **kwargs ): diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index c2be8d96402df..e4baee1e9cb97 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -372,7 +372,7 @@ class providing the base-class of operations. ---------- func : function, str, list or dict Function to use for aggregating the data. If a function, must either - work when passed a %(klass)s or when passed to %(klass)s.apply. + work when passed a {klass} or when passed to {klass}.apply. Accepted combinations are: @@ -403,7 +403,7 @@ class providing the base-class of operations. * For ``'numba'`` engine, the engine can accept ``nopython``, ``nogil`` and ``parallel`` dictionary keys. The values must either be ``True`` or ``False``. The default ``engine_kwargs`` for the ``'numba'`` engine is - ``{'nopython': True, 'nogil': False, 'parallel': False}`` and will be + ``{{'nopython': True, 'nogil': False, 'parallel': False}}`` and will be applied to the function .. versionadded:: 1.1.0 @@ -412,20 +412,20 @@ class providing the base-class of operations. Returns ------- -%(klass)s +{klass} See Also -------- -%(klass)s.groupby.apply -%(klass)s.groupby.transform -%(klass)s.aggregate +{klass}.groupby.apply +{klass}.groupby.transform +{klass}.aggregate Notes ----- When using ``engine='numba'``, there will be no "fall back" behavior internally. The group data and group index will be passed as numpy arrays to the JITed user defined function, and no alternative execution attempts will be tried. -%(examples)s +{examples} """ diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 5e363f2814d39..bfdfc65723433 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -274,14 +274,14 @@ def pipe(self, func, *args, **kwargs): """ ) - @Substitution( + @doc( + _shared_docs["aggregate"], see_also=_agg_see_also_doc, examples=_agg_examples_doc, versionadded="", klass="DataFrame", axis="", ) - @Appender(_shared_docs["aggregate"]) def aggregate(self, func, *args, **kwargs): self._set_binner() diff --git a/pandas/core/series.py b/pandas/core/series.py index b32a4c36a8247..a6e5cf9eb7a8a 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1410,8 +1410,46 @@ def to_string( with open(buf, "w") as f: f.write(result) - @Appender( + @doc( + klass=_shared_doc_kwargs["klass"], + examples=dedent( + """ + Examples + -------- + >>> s = pd.Series(["elk", "pig", "dog", "quetzal"], name="animal") + >>> print(s.to_markdown()) + | | animal | + |---:|:---------| + | 0 | elk | + | 1 | pig | + | 2 | dog | + | 3 | quetzal | + """ + ), + ) + def to_markdown( + self, buf: Optional[IO[str]] = None, mode: Optional[str] = None, **kwargs + ) -> Optional[str]: """ + Print {klass} in Markdown-friendly format. + + .. versionadded:: 1.0.0 + + Parameters + ---------- + buf : str, Path or StringIO-like, optional, default None + Buffer to write to. If None, the output is returned as a string. + mode : str, optional + Mode in which file is opened. + **kwargs + These parameters will be passed to `tabulate \ + <https://pypi.org/project/tabulate>`_. + + Returns + ------- + str + {klass} in Markdown-friendly format. + Examples -------- >>> s = pd.Series(["elk", "pig", "dog", "quetzal"], name="animal") @@ -1438,12 +1476,6 @@ def to_string( | 3 | quetzal | +----+----------+ """ - ) - @Substitution(klass="Series") - @Appender(generic._shared_docs["to_markdown"]) - def to_markdown( - self, buf: Optional[IO[str]] = None, mode: Optional[str] = None, **kwargs - ) -> Optional[str]: return self.to_frame().to_markdown(buf, mode, **kwargs) # ---------------------------------------------------------------------- @@ -3964,13 +3996,14 @@ def _gotitem(self, key, ndim, subset=None) -> "Series": """ ) - @Substitution( + @doc( + generic._shared_docs["aggregate"], + klass=_shared_doc_kwargs["klass"], + axis=_shared_doc_kwargs["axis"], see_also=_agg_see_also_doc, examples=_agg_examples_doc, versionadded="\n.. versionadded:: 0.20.0\n", - **_shared_doc_kwargs, ) - @Appender(generic._shared_docs["aggregate"]) def aggregate(self, func, axis=0, *args, **kwargs): # Validate the axis parameter self._get_axis_number(axis) @@ -3999,7 +4032,11 @@ def aggregate(self, func, axis=0, *args, **kwargs): agg = aggregate - @Appender(generic._shared_docs["transform"] % _shared_doc_kwargs) + @doc( + NDFrame.transform, + klass=_shared_doc_kwargs["klass"], + axis=_shared_doc_kwargs["axis"], + ) def transform(self, func, axis=0, *args, **kwargs): # Validate the axis parameter self._get_axis_number(axis) @@ -4190,7 +4227,11 @@ def _needs_reindex_multi(self, axes, method, level): """ return False - @doc(NDFrame.align, **_shared_doc_kwargs) + @doc( + NDFrame.align, + klass=_shared_doc_kwargs["klass"], + axes_single_arg=_shared_doc_kwargs["axes_single_arg"], + ) def align( self, other, @@ -4321,8 +4362,13 @@ def rename( def set_axis(self, labels, axis: Axis = 0, inplace: bool = False): return super().set_axis(labels, axis=axis, inplace=inplace) - @Substitution(**_shared_doc_kwargs) - @Appender(generic.NDFrame.reindex.__doc__) + @doc( + NDFrame.reindex, + klass=_shared_doc_kwargs["klass"], + axes=_shared_doc_kwargs["axes"], + optional_labels=_shared_doc_kwargs["optional_labels"], + optional_axis=_shared_doc_kwargs["optional_axis"], + ) def reindex(self, index=None, **kwargs): return super().reindex(index=index, **kwargs) @@ -4451,7 +4497,7 @@ def fillna( downcast=downcast, ) - @doc(NDFrame.replace, **_shared_doc_kwargs) + @doc(NDFrame.replace, klass=_shared_doc_kwargs["klass"]) def replace( self, to_replace=None, @@ -4470,7 +4516,7 @@ def replace( method=method, ) - @doc(NDFrame.shift, **_shared_doc_kwargs) + @doc(NDFrame.shift, klass=_shared_doc_kwargs["klass"]) def shift(self, periods=1, freq=None, axis=0, fill_value=None) -> "Series": return super().shift( periods=periods, freq=freq, axis=axis, fill_value=fill_value @@ -4691,19 +4737,19 @@ def _convert_dtypes( result = input_series.copy() return result - @Appender(generic._shared_docs["isna"] % _shared_doc_kwargs) + @doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"]) def isna(self) -> "Series": return super().isna() - @Appender(generic._shared_docs["isna"] % _shared_doc_kwargs) + @doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"]) def isnull(self) -> "Series": return super().isnull() - @Appender(generic._shared_docs["notna"] % _shared_doc_kwargs) + @doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"]) def notna(self) -> "Series": return super().notna() - @Appender(generic._shared_docs["notna"] % _shared_doc_kwargs) + @doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"]) def notnull(self) -> "Series": return super().notnull() diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 0e39b94574a12..b708020be90d2 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -7,7 +7,7 @@ import pandas._libs.window.aggregations as window_aggregations from pandas._typing import FrameOrSeries from pandas.compat.numpy import function as nv -from pandas.util._decorators import Appender, Substitution +from pandas.util._decorators import Appender, Substitution, doc from pandas.core.dtypes.generic import ABCDataFrame @@ -214,14 +214,14 @@ def _constructor(self): """ ) - @Substitution( + @doc( + _shared_docs["aggregate"], see_also=_agg_see_also_doc, examples=_agg_examples_doc, versionadded="", klass="Series/Dataframe", axis="", ) - @Appender(_shared_docs["aggregate"]) def aggregate(self, func, *args, **kwargs): return super().aggregate(func, *args, **kwargs) diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py index 438032a0c4419..bbc19fad8b799 100644 --- a/pandas/core/window/expanding.py +++ b/pandas/core/window/expanding.py @@ -2,7 +2,7 @@ from typing import Dict, Optional from pandas.compat.numpy import function as nv -from pandas.util._decorators import Appender, Substitution +from pandas.util._decorators import Appender, Substitution, doc from pandas.core.window.common import WindowGroupByMixin, _doc_template, _shared_docs from pandas.core.window.rolling import _Rolling_and_Expanding @@ -113,14 +113,14 @@ def _get_window(self, other=None, **kwargs): """ ) - @Substitution( + @doc( + _shared_docs["aggregate"], see_also=_agg_see_also_doc, examples=_agg_examples_doc, versionadded="", klass="Series/Dataframe", axis="", ) - @Appender(_shared_docs["aggregate"]) def aggregate(self, func, *args, **kwargs): return super().aggregate(func, *args, **kwargs) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 92be2d056cfcb..89f8450ef7bde 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -15,7 +15,7 @@ from pandas._typing import Axis, FrameOrSeries, Scalar from pandas.compat._optional import import_optional_dependency from pandas.compat.numpy import function as nv -from pandas.util._decorators import Appender, Substitution, cache_readonly +from pandas.util._decorators import Appender, Substitution, cache_readonly, doc from pandas.core.dtypes.common import ( ensure_float64, @@ -1151,14 +1151,14 @@ def _get_window( """ ) - @Substitution( + @doc( + _shared_docs["aggregate"], see_also=_agg_see_also_doc, examples=_agg_examples_doc, versionadded="", klass="Series/DataFrame", axis="", ) - @Appender(_shared_docs["aggregate"]) def aggregate(self, func, *args, **kwargs): result, how = self._aggregate(func, *args, **kwargs) if result is None: @@ -2020,14 +2020,14 @@ def _validate_freq(self): """ ) - @Substitution( + @doc( + _shared_docs["aggregate"], see_also=_agg_see_also_doc, examples=_agg_examples_doc, versionadded="", klass="Series/Dataframe", axis="", ) - @Appender(_shared_docs["aggregate"]) def aggregate(self, func, *args, **kwargs): return super().aggregate(func, *args, **kwargs)
- [x] ref #31942 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] replaces `Appender` decorator with `doc`
https://api.github.com/repos/pandas-dev/pandas/pulls/33277
2020-04-03T22:12:25Z
2020-06-19T12:01:14Z
2020-06-19T12:01:14Z
2020-06-19T16:36:01Z
Added finalize benchmark
diff --git a/asv_bench/benchmarks/finalize.py b/asv_bench/benchmarks/finalize.py new file mode 100644 index 0000000000000..dc06f55cc6ca0 --- /dev/null +++ b/asv_bench/benchmarks/finalize.py @@ -0,0 +1,16 @@ +import pandas as pd + + +class Finalize: + param_names = ["series", "frame"] + params = [pd.Series, pd.DataFrame] + + def setup(self, param): + N = 1000 + obj = param(dtype=float) + for i in range(N): + obj.attrs[i] = i + self.obj = obj + + def time_finalize_micro(self, param): + self.obj.__finalize__(self.obj, method="__finalize__")
This adds a benchmark for finalize. It scales with the number of `attrs`.
https://api.github.com/repos/pandas-dev/pandas/pulls/33275
2020-04-03T21:03:52Z
2020-04-06T18:35:58Z
2020-04-06T18:35:58Z
2020-04-06T18:36:01Z
Pass method in __finalize__
diff --git a/pandas/core/base.py b/pandas/core/base.py index a28a2c9594341..5945d8a4b432d 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -1521,4 +1521,4 @@ def duplicated(self, keep="first"): else: return self._constructor( duplicated(self, keep=keep), index=self.index - ).__finalize__(self) + ).__finalize__(self, method="duplicated") diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 67523facb7b7d..aedbba755227d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2515,7 +2515,7 @@ def transpose(self, *args, copy: bool = False) -> "DataFrame": new_values, index=self.columns, columns=self.index ) - return result.__finalize__(self) + return result.__finalize__(self, method="transpose") @property def T(self) -> "DataFrame": @@ -4470,7 +4470,7 @@ def _maybe_casted_values(index, labels=None): @Appender(_shared_docs["isna"] % _shared_doc_kwargs) def isna(self) -> "DataFrame": result = self._constructor(self._data.isna(func=isna)) - return result.__finalize__(self) + return result.__finalize__(self, method="isna") @Appender(_shared_docs["isna"] % _shared_doc_kwargs) def isnull(self) -> "DataFrame": @@ -4798,7 +4798,7 @@ def sort_values( if inplace: return self._update_inplace(result) else: - return result.__finalize__(self) + return result.__finalize__(self, method="sort_values") def sort_index( self, @@ -4934,7 +4934,7 @@ def sort_index( if inplace: return self._update_inplace(result) else: - return result.__finalize__(self) + return result.__finalize__(self, method="sort_index") def value_counts( self, diff --git a/pandas/core/generic.py b/pandas/core/generic.py index fac4ca6768ece..16725e72d5df2 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -590,7 +590,9 @@ def swapaxes(self: FrameOrSeries, axis1, axis2, copy=True) -> FrameOrSeries: if copy: new_values = new_values.copy() - return self._constructor(new_values, *new_axes).__finalize__(self) + return self._constructor(new_values, *new_axes).__finalize__( + self, method="swapaxes" + ) def droplevel(self: FrameOrSeries, level, axis=0) -> FrameOrSeries: """ @@ -993,7 +995,7 @@ def rename( self._update_inplace(result) return None else: - return result.__finalize__(self) + return result.__finalize__(self, method="rename") @rewrite_axis_style_signature("mapper", [("copy", True), ("inplace", False)]) def rename_axis(self, mapper=lib.no_default, **kwargs): @@ -1357,7 +1359,7 @@ def __invert__(self): return self new_data = self._mgr.apply(operator.invert) - result = self._constructor(new_data).__finalize__(self) + result = self._constructor(new_data).__finalize__(self, method="__invert__") return result def __nonzero__(self): @@ -1802,7 +1804,9 @@ def __array_wrap__(self, result, context=None): # ptp also requires the item_from_zerodim return result d = self._construct_axes_dict(self._AXIS_ORDERS, copy=False) - return self._constructor(result, **d).__finalize__(self) + return self._constructor(result, **d).__finalize__( + self, method="__array_wrap__" + ) # ideally we would define this to avoid the getattr checks, but # is slower @@ -3361,7 +3365,7 @@ class max_speed new_data = self._mgr.take( indices, axis=self._get_block_manager_axis(axis), verify=True ) - return self._constructor(new_data).__finalize__(self) + return self._constructor(new_data).__finalize__(self, method="take") def _take_with_is_copy(self: FrameOrSeries, indices, axis=0) -> FrameOrSeries: """ @@ -4430,7 +4434,7 @@ def reindex(self: FrameOrSeries, *args, **kwargs) -> FrameOrSeries: # perform the reindex on the axes return self._reindex_axes( axes, level, limit, tolerance, method, fill_value, copy - ).__finalize__(self) + ).__finalize__(self, method="reindex") def _reindex_axes( self: FrameOrSeries, axes, level, limit, tolerance, method, fill_value, copy @@ -5129,7 +5133,7 @@ def pipe(self, func, *args, **kwargs): # Attribute access def __finalize__( - self: FrameOrSeries, other, method=None, **kwargs + self: FrameOrSeries, other, method: Optional[str] = None, **kwargs ) -> FrameOrSeries: """ Propagate metadata from other to self. @@ -5138,9 +5142,14 @@ def __finalize__( ---------- other : the object from which to get the attributes that we are going to propagate - method : optional, a passed method name ; possibly to take different - types of propagation actions based on this + method : str, optional + A passed method name providing context on where ``__finalize__`` + was called. + + .. warning: + The value passed as `method` are not currently considered + stable across pandas releases. """ if isinstance(other, NDFrame): for name in other.attrs: @@ -5293,10 +5302,10 @@ def _check_inplace_setting(self, value) -> bool_t: return True def _get_numeric_data(self): - return self._constructor(self._mgr.get_numeric_data()).__finalize__(self) + return self._constructor(self._mgr.get_numeric_data()).__finalize__(self,) def _get_bool_data(self): - return self._constructor(self._mgr.get_bool_data()).__finalize__(self) + return self._constructor(self._mgr.get_bool_data()).__finalize__(self,) # ---------------------------------------------------------------------- # Internal Interface Methods @@ -5562,8 +5571,8 @@ def astype( else: # else, only a single dtype is given - new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors) - return self._constructor(new_data).__finalize__(self) + new_data = self._mgr.astype(dtype=dtype, copy=copy, errors=errors,) + return self._constructor(new_data).__finalize__(self, method="astype") # GH 19920: retain column metadata after concat result = pd.concat(results, axis=1, copy=False) @@ -5677,7 +5686,7 @@ def copy(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries: """ data = self._mgr.copy(deep=deep) self._clear_item_cache() - return self._constructor(data).__finalize__(self) + return self._constructor(data).__finalize__(self, method="copy") def __copy__(self: FrameOrSeries, deep: bool_t = True) -> FrameOrSeries: return self.copy(deep=deep) @@ -5783,7 +5792,7 @@ def infer_objects(self: FrameOrSeries) -> FrameOrSeries: self._mgr.convert( datetime=True, numeric=False, timedelta=True, coerce=False, copy=True ) - ).__finalize__(self) + ).__finalize__(self, method="infer_objects") def convert_dtypes( self: FrameOrSeries, @@ -6110,7 +6119,7 @@ def fillna( if inplace: return self._update_inplace(result) else: - return result.__finalize__(self) + return result.__finalize__(self, method="fillna") def ffill( self: FrameOrSeries, @@ -6626,7 +6635,7 @@ def replace( if inplace: return self._update_inplace(result) else: - return result.__finalize__(self) + return result.__finalize__(self, method="replace") _shared_docs[ "interpolate" @@ -6892,7 +6901,7 @@ def interpolate( if inplace: return self._update_inplace(result) else: - return result.__finalize__(self) + return result.__finalize__(self, method="interpolate") # ---------------------------------------------------------------------- # Timeseries methods Methods @@ -7130,11 +7139,11 @@ def asof(self, where, subset=None): @Appender(_shared_docs["isna"] % _shared_doc_kwargs) def isna(self: FrameOrSeries) -> FrameOrSeries: - return isna(self).__finalize__(self) + return isna(self).__finalize__(self, method="isna") @Appender(_shared_docs["isna"] % _shared_doc_kwargs) def isnull(self: FrameOrSeries) -> FrameOrSeries: - return isna(self).__finalize__(self) + return isna(self).__finalize__(self, method="isnull") _shared_docs[ "notna" @@ -7200,11 +7209,11 @@ def isnull(self: FrameOrSeries) -> FrameOrSeries: @Appender(_shared_docs["notna"] % _shared_doc_kwargs) def notna(self: FrameOrSeries) -> FrameOrSeries: - return notna(self).__finalize__(self) + return notna(self).__finalize__(self, method="notna") @Appender(_shared_docs["notna"] % _shared_doc_kwargs) def notnull(self: FrameOrSeries) -> FrameOrSeries: - return notna(self).__finalize__(self) + return notna(self).__finalize__(self, method="notnull") def _clip_with_scalar(self, lower, upper, inplace: bool_t = False): if (lower is not None and np.any(isna(lower))) or ( @@ -8228,7 +8237,7 @@ def ranker(data): pct=pct, ) ranks = self._constructor(ranks, **data._construct_axes_dict()) - return ranks.__finalize__(self) + return ranks.__finalize__(self, method="rank") # if numeric_only is None, and we can't get anything, we try with # numeric_only=True @@ -8435,7 +8444,10 @@ def _align_frame( left.index = join_index right.index = join_index - return left.__finalize__(self), right.__finalize__(other) + return ( + left.__finalize__(self), + right.__finalize__(other), + ) def _align_series( self, @@ -8519,7 +8531,10 @@ def _align_series( left.index = join_index right.index = join_index - return left.__finalize__(self), right.__finalize__(other) + return ( + left.__finalize__(self), + right.__finalize__(other), + ) def _where( self, @@ -8932,7 +8947,7 @@ def shift( else: return self.tshift(periods, freq) - return self._constructor(new_data).__finalize__(self) + return self._constructor(new_data).__finalize__(self, method="shift") def slice_shift(self: FrameOrSeries, periods: int = 1, axis=0) -> FrameOrSeries: """ @@ -8969,7 +8984,7 @@ def slice_shift(self: FrameOrSeries, periods: int = 1, axis=0) -> FrameOrSeries: shifted_axis = self._get_axis(axis)[islicer] new_obj.set_axis(shifted_axis, axis=axis, inplace=True) - return new_obj.__finalize__(self) + return new_obj.__finalize__(self, method="slice_shift") def tshift( self: FrameOrSeries, periods: int = 1, freq=None, axis: Axis = 0 @@ -9029,7 +9044,7 @@ def tshift( result = self.copy() result.set_axis(new_ax, axis, inplace=True) - return result.__finalize__(self) + return result.__finalize__(self, method="tshift") def truncate( self: FrameOrSeries, before=None, after=None, axis=None, copy: bool_t = True @@ -9240,7 +9255,7 @@ def _tz_convert(ax, tz): result = self.copy(deep=copy) result = result.set_axis(ax, axis=axis, inplace=False) - return result.__finalize__(self) + return result.__finalize__(self, method="tz_convert") def tz_localize( self: FrameOrSeries, @@ -9409,7 +9424,7 @@ def _tz_localize(ax, tz, ambiguous, nonexistent): result = self.copy(deep=copy) result = result.set_axis(ax, axis=axis, inplace=False) - return result.__finalize__(self) + return result.__finalize__(self, method="tz_localize") # ---------------------------------------------------------------------- # Numeric Methods @@ -11188,7 +11203,7 @@ def block_accum_func(blk_values): d = self._construct_axes_dict() d["copy"] = False - return self._constructor(result, **d).__finalize__(self) + return self._constructor(result, **d).__finalize__(self, method=name) return set_function_name(cum_func, name, cls) diff --git a/pandas/core/series.py b/pandas/core/series.py index 5ed8241101925..ccb1ec25b5ba4 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -661,7 +661,7 @@ def view(self, dtype=None) -> "Series": """ return self._constructor( self._values.view(dtype), index=self.index - ).__finalize__(self) + ).__finalize__(self, method="view") # ---------------------------------------------------------------------- # NDArray Compat @@ -829,7 +829,7 @@ def take(self, indices, axis=0, is_copy=None, **kwargs) -> "Series": return self._constructor( new_values, index=new_index, fastpath=True - ).__finalize__(self) + ).__finalize__(self, method="take") def _take_with_is_copy(self, indices, axis=0): """ @@ -962,12 +962,12 @@ def _get_values_tuple(self, key): # If key is contained, would have returned by now indexer, new_index = self.index.get_loc_level(key) return self._constructor(self._values[indexer], index=new_index).__finalize__( - self + self, ) def _get_values(self, indexer): try: - return self._constructor(self._mgr.get_slice(indexer)).__finalize__(self) + return self._constructor(self._mgr.get_slice(indexer)).__finalize__(self,) except ValueError: # mpl compat if we look up e.g. ser[:, np.newaxis]; # see tests.series.timeseries.test_mpl_compat_hack @@ -1181,7 +1181,9 @@ def repeat(self, repeats, axis=None) -> "Series": nv.validate_repeat(tuple(), dict(axis=axis)) new_index = self.index.repeat(repeats) new_values = self._values.repeat(repeats) - return self._constructor(new_values, index=new_index).__finalize__(self) + return self._constructor(new_values, index=new_index).__finalize__( + self, method="repeat" + ) def reset_index(self, level=None, drop=False, name=None, inplace=False): """ @@ -1308,7 +1310,7 @@ def reset_index(self, level=None, drop=False, name=None, inplace=False): else: return self._constructor( self._values.copy(), index=new_index - ).__finalize__(self) + ).__finalize__(self, method="reset_index") elif inplace: raise TypeError( "Cannot reset_index inplace on a Series to create a DataFrame" @@ -1707,7 +1709,9 @@ def count(self, level=None): obs = level_codes[notna(self._values)] out = np.bincount(obs, minlength=len(lev) or None) - return self._constructor(out, index=lev, dtype="int64").__finalize__(self) + return self._constructor(out, index=lev, dtype="int64").__finalize__( + self, method="count" + ) def mode(self, dropna=True) -> "Series": """ @@ -2130,7 +2134,9 @@ def round(self, decimals=0, *args, **kwargs) -> "Series": """ nv.validate_round(args, kwargs) result = self._values.round(decimals) - result = self._constructor(result, index=self.index).__finalize__(self) + result = self._constructor(result, index=self.index).__finalize__( + self, method="round" + ) return result @@ -2352,7 +2358,9 @@ def diff(self, periods: int = 1) -> "Series": dtype: float64 """ result = algorithms.diff(self.array, periods) - return self._constructor(result, index=self.index).__finalize__(self) + return self._constructor(result, index=self.index).__finalize__( + self, method="diff" + ) def autocorr(self, lag=1) -> float: """ @@ -2469,7 +2477,7 @@ def dot(self, other): if isinstance(other, ABCDataFrame): return self._constructor( np.dot(lvals, rvals), index=other.columns - ).__finalize__(self) + ).__finalize__(self, method="dot") elif isinstance(other, Series): return np.dot(lvals, rvals) elif isinstance(rvals, np.ndarray): @@ -2994,7 +3002,7 @@ def _try_kind_sort(arr): if inplace: self._update_inplace(result) else: - return result.__finalize__(self) + return result.__finalize__(self, method="sort_values") def sort_index( self, @@ -3172,7 +3180,7 @@ def sort_index( if inplace: self._update_inplace(result) else: - return result.__finalize__(self) + return result.__finalize__(self, method="sort_index") def argsort(self, axis=0, kind="quicksort", order=None) -> "Series": """ @@ -3206,11 +3214,13 @@ def argsort(self, axis=0, kind="quicksort", order=None) -> "Series": result = Series(-1, index=self.index, name=self.name, dtype="int64") notmask = ~mask result[notmask] = np.argsort(values[notmask], kind=kind) - return self._constructor(result, index=self.index).__finalize__(self) + return self._constructor(result, index=self.index).__finalize__( + self, method="argsort" + ) else: return self._constructor( np.argsort(values, kind=kind), index=self.index, dtype="int64" - ).__finalize__(self) + ).__finalize__(self, method="argsort") def nlargest(self, n=5, keep="first") -> "Series": """ @@ -3428,7 +3438,7 @@ def swaplevel(self, i=-2, j=-1, copy=True) -> "Series": assert isinstance(self.index, ABCMultiIndex) new_index = self.index.swaplevel(i, j) return self._constructor(self._values, index=new_index, copy=copy).__finalize__( - self + self, method="swaplevel" ) def reorder_levels(self, order) -> "Series": @@ -3632,7 +3642,9 @@ def map(self, arg, na_action=None) -> "Series": dtype: object """ new_values = super()._map_values(arg, na_action=na_action) - return self._constructor(new_values, index=self.index).__finalize__(self) + return self._constructor(new_values, index=self.index).__finalize__( + self, method="map" + ) def _gotitem(self, key, ndim, subset=None) -> "Series": """ @@ -3819,7 +3831,7 @@ def apply(self, func, convert_dtype=True, args=(), **kwds): """ if len(self) == 0: return self._constructor(dtype=self.dtype, index=self.index).__finalize__( - self + self, method="apply" ) # dispatch to agg @@ -3856,7 +3868,9 @@ def f(x): # so extension arrays can be used return self._constructor_expanddim(pd.array(mapped), index=self.index) else: - return self._constructor(mapped, index=self.index).__finalize__(self) + return self._constructor(mapped, index=self.index).__finalize__( + self, method="apply" + ) def _reduce( self, op, name, axis=0, skipna=True, numeric_only=None, filter_type=None, **kwds @@ -4297,7 +4311,9 @@ def isin(self, values) -> "Series": Name: animal, dtype: bool """ result = algorithms.isin(self, values) - return self._constructor(result, index=self.index).__finalize__(self) + return self._constructor(result, index=self.index).__finalize__( + self, method="isin" + ) def between(self, left, right, inclusive=True) -> "Series": """ @@ -4533,7 +4549,9 @@ def to_timestamp(self, freq=None, how="start", copy=True) -> "Series": assert isinstance(self.index, (ABCDatetimeIndex, ABCPeriodIndex)) new_index = self.index.to_timestamp(freq=freq, how=how) - return self._constructor(new_values, index=new_index).__finalize__(self) + return self._constructor(new_values, index=new_index).__finalize__( + self, method="to_timestamp" + ) def to_period(self, freq=None, copy=True) -> "Series": """ @@ -4558,7 +4576,9 @@ def to_period(self, freq=None, copy=True) -> "Series": assert isinstance(self.index, ABCDatetimeIndex) new_index = self.index.to_period(freq=freq) - return self._constructor(new_values, index=new_index).__finalize__(self) + return self._constructor(new_values, index=new_index).__finalize__( + self, method="to_period" + ) # ---------------------------------------------------------------------- # Add index
This passes `method` everywhere we use `__finalize__`. I'm trying to get a better sense for 1. When we call finalize (and when we fail too) 2. When we finalize multiple times 3. The overhead of finalize I haven't called it anywhere new yet (followup PR with that coming though).
https://api.github.com/repos/pandas-dev/pandas/pulls/33273
2020-04-03T19:58:08Z
2020-04-06T22:04:41Z
2020-04-06T22:04:41Z
2020-04-06T22:04:50Z
CLN: Added static types _libs/algos
diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index 7a32b8957003e..6b6ead795584f 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -50,18 +50,17 @@ from pandas._libs.khash cimport ( import pandas._libs.missing as missing -cdef float64_t FP_ERR = 1e-13 - -cdef float64_t NaN = <float64_t>np.NaN - -cdef int64_t NPY_NAT = get_nat() +cdef: + float64_t FP_ERR = 1e-13 + float64_t NaN = <float64_t>np.NaN + int64_t NPY_NAT = get_nat() tiebreakers = { - 'average': TIEBREAK_AVERAGE, - 'min': TIEBREAK_MIN, - 'max': TIEBREAK_MAX, - 'first': TIEBREAK_FIRST, - 'dense': TIEBREAK_DENSE, + "average": TIEBREAK_AVERAGE, + "min": TIEBREAK_MIN, + "max": TIEBREAK_MAX, + "first": TIEBREAK_FIRST, + "dense": TIEBREAK_DENSE, } @@ -120,6 +119,7 @@ cpdef ndarray[int64_t, ndim=1] unique_deltas(const int64_t[:] arr): kh_int64_t *table int ret = 0 list uniques = [] + ndarray[int64_t, ndim=1] result table = kh_init_int64() kh_resize_int64(table, 10) @@ -261,7 +261,7 @@ def kth_smallest(numeric[:] a, Py_ssize_t k) -> numeric: @cython.boundscheck(False) @cython.wraparound(False) -def nancorr(const float64_t[:, :] mat, bint cov=0, minp=None): +def nancorr(const float64_t[:, :] mat, bint cov=False, minp=None): cdef: Py_ssize_t i, j, xi, yi, N, K bint minpv @@ -325,7 +325,7 @@ def nancorr(const float64_t[:, :] mat, bint cov=0, minp=None): @cython.boundscheck(False) @cython.wraparound(False) -def nancorr_spearman(const float64_t[:, :] mat, Py_ssize_t minp=1): +def nancorr_spearman(const float64_t[:, :] mat, Py_ssize_t minp=1) -> ndarray: cdef: Py_ssize_t i, j, xi, yi, N, K ndarray[float64_t, ndim=2] result @@ -581,7 +581,7 @@ D @cython.boundscheck(False) @cython.wraparound(False) -def backfill(ndarray[algos_t] old, ndarray[algos_t] new, limit=None): +def backfill(ndarray[algos_t] old, ndarray[algos_t] new, limit=None) -> ndarray: cdef: Py_ssize_t i, j, nleft, nright ndarray[int64_t, ndim=1] indexer @@ -810,18 +810,14 @@ def rank_1d( """ cdef: Py_ssize_t i, j, n, dups = 0, total_tie_count = 0, non_na_idx = 0 - ndarray[rank_t] sorted_data, values - ndarray[float64_t] ranks ndarray[int64_t] argsorted ndarray[uint8_t, cast=True] sorted_mask - rank_t val, nan_value - float64_t sum_ranks = 0 int tiebreak = 0 - bint keep_na = 0 + bint keep_na = False bint isnan, condition float64_t count = 0.0 @@ -1034,19 +1030,14 @@ def rank_2d( """ cdef: Py_ssize_t i, j, z, k, n, dups = 0, total_tie_count = 0 - Py_ssize_t infs - ndarray[float64_t, ndim=2] ranks ndarray[rank_t, ndim=2] values - ndarray[int64_t, ndim=2] argsorted - rank_t val, nan_value - float64_t sum_ranks = 0 int tiebreak = 0 - bint keep_na = 0 + bint keep_na = False float64_t count = 0.0 bint condition, skip_condition
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33271
2020-04-03T19:31:02Z
2020-04-05T20:00:29Z
2020-04-05T20:00:29Z
2020-04-06T08:28:14Z
REF: dispatch TDBlock.to_native_types to TDA._format_native_types
diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index a9c8977991740..8c93dca783113 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -389,7 +389,7 @@ def _format_native_types(self, na_rep="NaT", date_format=None, **kwargs): from pandas.io.formats.format import _get_format_timedelta64 formatter = _get_format_timedelta64(self._data, na_rep) - return np.array([formatter(x) for x in self._data]) + return np.array([formatter(x) for x in self._data.ravel()]).reshape(self.shape) # ---------------------------------------------------------------- # Arithmetic Methods diff --git a/pandas/core/construction.py b/pandas/core/construction.py index c9754ff588896..2d60ad9ba50bf 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -187,7 +187,7 @@ def array( >>> pd.array(["1H", "2H"], dtype='timedelta64[ns]') <TimedeltaArray> - ['01:00:00', '02:00:00'] + ['0 days 01:00:00', '0 days 02:00:00'] Length: 2, dtype: timedelta64[ns] Examples diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py index 2908d468bcae0..d2cee5d94422c 100644 --- a/pandas/core/indexes/accessors.py +++ b/pandas/core/indexes/accessors.py @@ -241,9 +241,9 @@ class TimedeltaProperties(Properties): ... pd.timedelta_range(start="1 second", periods=3, freq="S") ... ) >>> seconds_series - 0 00:00:01 - 1 00:00:02 - 2 00:00:03 + 0 0 days 00:00:01 + 1 0 days 00:00:02 + 2 0 days 00:00:03 dtype: timedelta64[ns] >>> seconds_series.dt.seconds 0 1 @@ -301,11 +301,11 @@ def components(self): -------- >>> s = pd.Series(pd.to_timedelta(np.arange(5), unit='s')) >>> s - 0 00:00:00 - 1 00:00:01 - 2 00:00:02 - 3 00:00:03 - 4 00:00:04 + 0 0 days 00:00:00 + 1 0 days 00:00:01 + 2 0 days 00:00:02 + 3 0 days 00:00:03 + 4 0 days 00:00:04 dtype: timedelta64[ns] >>> s.dt.components days hours minutes seconds milliseconds microseconds nanoseconds diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index d8b54fd5cffb3..fa53eeded0387 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -2358,26 +2358,10 @@ def fillna(self, value, **kwargs): ) return super().fillna(value, **kwargs) - def to_native_types(self, na_rep=None, quoting=None, **kwargs): + def to_native_types(self, na_rep="NaT", **kwargs): """ convert to our native types format """ - values = self.values - mask = isna(values) - - rvalues = np.empty(values.shape, dtype=object) - if na_rep is None: - na_rep = "NaT" - rvalues[mask] = na_rep - imask = (~mask).ravel() - - # FIXME: - # should use the formats.format.Timedelta64Formatter here - # to figure what format to pass to the Timedelta - # e.g. to not show the decimals say - rvalues.flat[imask] = np.array( - [Timedelta(val)._repr_base(format="all") for val in values.ravel()[imask]], - dtype=object, - ) - return rvalues + tda = self.array_values() + return tda._format_native_types(na_rep, **kwargs) class BoolBlock(NumericBlock): diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index 960a82caafeeb..48f30acf269da 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -69,8 +69,8 @@ def to_timedelta(arg, unit="ns", errors="raise"): Converting numbers by specifying the `unit` keyword argument: >>> pd.to_timedelta(np.arange(5), unit='s') - TimedeltaIndex(['00:00:00', '00:00:01', '00:00:02', - '00:00:03', '00:00:04'], + TimedeltaIndex(['0 days 00:00:00', '0 days 00:00:01', '0 days 00:00:02', + '0 days 00:00:03', '0 days 00:00:04'], dtype='timedelta64[ns]', freq=None) >>> pd.to_timedelta(np.arange(5), unit='d') TimedeltaIndex(['0 days', '1 days', '2 days', '3 days', '4 days'], diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index a9e668312d751..59542a8da535e 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1672,14 +1672,9 @@ def _get_format_timedelta64( even_days = ( np.logical_and(consider_values, values_int % one_day_nanos != 0).sum() == 0 ) - all_sub_day = ( - np.logical_and(consider_values, np.abs(values_int) >= one_day_nanos).sum() == 0 - ) if even_days: format = None - elif all_sub_day: - format = "sub_day" else: format = "long" diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index 2cda4ba16f7ce..27ebee4aaaccf 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -248,12 +248,7 @@ def test_astype_str(self): { "a": list(map(str, map(lambda x: Timestamp(x)._date_repr, a._values))), "b": list(map(str, map(Timestamp, b._values))), - "c": list( - map( - str, - map(lambda x: Timedelta(x)._repr_base(format="all"), c._values), - ) - ), + "c": list(map(lambda x: Timedelta(x)._repr_base(), c._values)), "d": list(map(str, d._values)), "e": list(map(str, e._values)), } diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 1a5d122d732a9..f3c3344992942 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -3003,13 +3003,13 @@ def test_days_neg(self): def test_subdays(self): y = pd.to_timedelta(list(range(5)) + [pd.NaT], unit="s") result = fmt.Timedelta64Formatter(y, box=True).get_result() - assert result[0].strip() == "'00:00:00'" - assert result[1].strip() == "'00:00:01'" + assert result[0].strip() == "'0 days 00:00:00'" + assert result[1].strip() == "'0 days 00:00:01'" def test_subdays_neg(self): y = pd.to_timedelta(list(range(5)) + [pd.NaT], unit="s") result = fmt.Timedelta64Formatter(-y, box=True).get_result() - assert result[0].strip() == "'00:00:00'" + assert result[0].strip() == "'0 days 00:00:00'" assert result[1].strip() == "'-1 days +23:59:59'" def test_zero(self): diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py index 2f2a663d559d0..05e708e575a64 100644 --- a/pandas/tests/series/test_dtypes.py +++ b/pandas/tests/series/test_dtypes.py @@ -132,7 +132,7 @@ def test_astype_str_map(self, dtype, series): expected = series.map(str) tm.assert_series_equal(result, expected) - def test_astype_str_cast(self): + def test_astype_str_cast_dt64(self): # see gh-9757 ts = Series([Timestamp("2010-01-04 00:00:00")]) s = ts.astype(str) @@ -146,11 +146,14 @@ def test_astype_str_cast(self): expected = Series([str("2010-01-04 00:00:00-05:00")]) tm.assert_series_equal(s, expected) + def test_astype_str_cast_td64(self): + # see gh-9757 + td = Series([Timedelta(1, unit="d")]) - s = td.astype(str) + ser = td.astype(str) - expected = Series([str("1 days 00:00:00.000000000")]) - tm.assert_series_equal(s, expected) + expected = Series([str("1 days")]) + tm.assert_series_equal(ser, expected) def test_astype_unicode(self): # see gh-7758: A bit of magic is required to set
https://api.github.com/repos/pandas-dev/pandas/pulls/33270
2020-04-03T19:18:02Z
2020-04-06T23:19:11Z
2020-04-06T23:19:11Z
2020-04-06T23:20:31Z
TYP: Fixed type annotaions in `scripts/validate_rst_title_capitalization`
diff --git a/scripts/validate_rst_title_capitalization.py b/scripts/validate_rst_title_capitalization.py index 59d422a1605a0..3d19e37ac7a1d 100755 --- a/scripts/validate_rst_title_capitalization.py +++ b/scripts/validate_rst_title_capitalization.py @@ -14,7 +14,7 @@ import os import re import sys -from typing import Generator, List, Tuple +from typing import Iterable, List, Tuple CAPITALIZATION_EXCEPTIONS = { "pandas", @@ -148,7 +148,7 @@ def correct_title_capitalization(title: str) -> str: return correct_title -def find_titles(rst_file: str) -> Generator[Tuple[str, int], None, None]: +def find_titles(rst_file: str) -> Iterable[Tuple[str, int]]: """ Algorithm to identify particular text that should be considered headings in an RST file. @@ -184,7 +184,7 @@ def find_titles(rst_file: str) -> Generator[Tuple[str, int], None, None]: previous_line = line -def find_rst_files(source_paths: List[str]) -> Generator[str, None, None]: +def find_rst_files(source_paths: List[str]) -> Iterable[str]: """ Given the command line arguments of directory paths, this method yields the strings of the .rst file directories that these paths contain. @@ -214,7 +214,7 @@ def find_rst_files(source_paths: List[str]) -> Generator[str, None, None]: yield filename -def main(source_paths: List[str], output_format: str) -> bool: +def main(source_paths: List[str], output_format: str) -> int: """ The main method to print all headings with incorrect capitalization.
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33268
2020-04-03T18:56:51Z
2020-04-04T21:35:35Z
2020-04-04T21:35:35Z
2020-04-06T08:26:58Z
TST: add DataFrame test for construct from tuple case from GH-32776
diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 9f40e8c6931c8..fcdc62753ca0a 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -1336,6 +1336,7 @@ def test_constructor_mixed_type_rows(self): (((), ()), [(), ()]), (((), ()), [[], []]), (([], []), [[], []]), + (([1], [2]), [[1], [2]]), # GH 32776 (([1, 2, 3], [4, 5, 6]), [[1, 2, 3], [4, 5, 6]]), ], )
- [x] closes #32776 - [x] tests added / passed - [x] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33267
2020-04-03T18:25:16Z
2020-04-04T21:07:10Z
2020-04-04T21:07:10Z
2020-04-05T02:22:47Z
DOC: Fixed examples in `pandas/core/window`
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 3e9138814fbdf..875ca259f69d9 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -322,6 +322,10 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then pytest -q --doctest-modules pandas/core/tools/ RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Doctests window' ; echo $MSG + pytest -q --doctest-modules pandas/core/window/ + RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Doctests tseries' ; echo $MSG pytest -q --doctest-modules pandas/tseries/ RET=$(($RET + $?)) ; echo $MSG "DONE" diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 0ec876583dcde..2759280dc1d1c 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -167,33 +167,18 @@ def _constructor(self): """ Examples -------- - - >>> df = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C']) + >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) >>> df - A B C - 0 -2.385977 -0.102758 0.438822 - 1 -1.004295 0.905829 -0.954544 - 2 0.735167 -0.165272 -1.619346 - 3 -0.702657 -1.340923 -0.706334 - 4 -0.246845 0.211596 -0.901819 - 5 2.463718 3.157577 -1.380906 - 6 -1.142255 2.340594 -0.039875 - 7 1.396598 -1.647453 1.677227 - 8 -0.543425 1.761277 -0.220481 - 9 -0.640505 0.289374 -1.550670 + A B C + 0 1 4 7 + 1 2 5 8 + 2 3 6 9 >>> df.ewm(alpha=0.5).mean() A B C - 0 -2.385977 -0.102758 0.438822 - 1 -1.464856 0.569633 -0.490089 - 2 -0.207700 0.149687 -1.135379 - 3 -0.471677 -0.645305 -0.906555 - 4 -0.355635 -0.203033 -0.904111 - 5 1.076417 1.503943 -1.146293 - 6 -0.041654 1.925562 -0.588728 - 7 0.680292 0.132049 0.548693 - 8 0.067236 0.948257 0.163353 - 9 -0.286980 0.618493 -0.694496 + 0 1.000000 4.000000 7.000000 + 1 1.666667 4.666667 7.666667 + 2 2.428571 5.428571 8.428571 """ ) diff --git a/pandas/core/window/expanding.py b/pandas/core/window/expanding.py index 140e0144d0a2d..146c139806bca 100644 --- a/pandas/core/window/expanding.py +++ b/pandas/core/window/expanding.py @@ -37,7 +37,8 @@ class Expanding(_Rolling_and_Expanding): Examples -------- - >>> df = pd.DataFrame({'B': [0, 1, 2, np.nan, 4]}) + >>> df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]}) + >>> df B 0 0.0 1 1.0 @@ -98,33 +99,18 @@ def _get_window(self, other=None, **kwargs): """ Examples -------- - - >>> df = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C']) + >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) >>> df - A B C - 0 -2.385977 -0.102758 0.438822 - 1 -1.004295 0.905829 -0.954544 - 2 0.735167 -0.165272 -1.619346 - 3 -0.702657 -1.340923 -0.706334 - 4 -0.246845 0.211596 -0.901819 - 5 2.463718 3.157577 -1.380906 - 6 -1.142255 2.340594 -0.039875 - 7 1.396598 -1.647453 1.677227 - 8 -0.543425 1.761277 -0.220481 - 9 -0.640505 0.289374 -1.550670 + A B C + 0 1 4 7 + 1 2 5 8 + 2 3 6 9 >>> df.ewm(alpha=0.5).mean() A B C - 0 -2.385977 -0.102758 0.438822 - 1 -1.464856 0.569633 -0.490089 - 2 -0.207700 0.149687 -1.135379 - 3 -0.471677 -0.645305 -0.906555 - 4 -0.355635 -0.203033 -0.904111 - 5 1.076417 1.503943 -1.146293 - 6 -0.041654 1.925562 -0.588728 - 7 0.680292 0.132049 0.548693 - 8 0.067236 0.948257 0.163353 - 9 -0.286980 0.618493 -0.694496 + 0 1.000000 4.000000 7.000000 + 1 1.666667 4.666667 7.666667 + 2 2.428571 5.428571 8.428571 """ ) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index dc8cf839d0bcb..729e4069b1309 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1039,33 +1039,18 @@ def _get_window( """ Examples -------- - - >>> df = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C']) + >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) >>> df - A B C - 0 -2.385977 -0.102758 0.438822 - 1 -1.004295 0.905829 -0.954544 - 2 0.735167 -0.165272 -1.619346 - 3 -0.702657 -1.340923 -0.706334 - 4 -0.246845 0.211596 -0.901819 - 5 2.463718 3.157577 -1.380906 - 6 -1.142255 2.340594 -0.039875 - 7 1.396598 -1.647453 1.677227 - 8 -0.543425 1.761277 -0.220481 - 9 -0.640505 0.289374 -1.550670 - - >>> df.rolling(3, win_type='boxcar').agg('mean') - A B C - 0 NaN NaN NaN - 1 NaN NaN NaN - 2 -0.885035 0.212600 -0.711689 - 3 -0.323928 -0.200122 -1.093408 - 4 -0.071445 -0.431533 -1.075833 - 5 0.504739 0.676083 -0.996353 - 6 0.358206 1.903256 -0.774200 - 7 0.906020 1.283573 0.085482 - 8 -0.096361 0.818139 0.472290 - 9 0.070889 0.134399 -0.031308 + A B C + 0 1 4 7 + 1 2 5 8 + 2 3 6 9 + + >>> df.rolling(2, win_type="boxcar").agg("mean") + A B C + 0 NaN NaN NaN + 1 1.5 4.5 7.5 + 2 2.5 5.5 8.5 """ ) @@ -1904,46 +1889,24 @@ def _validate_freq(self): """ Examples -------- - - >>> df = pd.DataFrame(np.random.randn(10, 3), columns=['A', 'B', 'C']) + >>> df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6], "C": [7, 8, 9]}) >>> df - A B C - 0 -2.385977 -0.102758 0.438822 - 1 -1.004295 0.905829 -0.954544 - 2 0.735167 -0.165272 -1.619346 - 3 -0.702657 -1.340923 -0.706334 - 4 -0.246845 0.211596 -0.901819 - 5 2.463718 3.157577 -1.380906 - 6 -1.142255 2.340594 -0.039875 - 7 1.396598 -1.647453 1.677227 - 8 -0.543425 1.761277 -0.220481 - 9 -0.640505 0.289374 -1.550670 + A B C + 0 1 4 7 + 1 2 5 8 + 2 3 6 9 - >>> df.rolling(3).sum() - A B C - 0 NaN NaN NaN - 1 NaN NaN NaN - 2 -2.655105 0.637799 -2.135068 - 3 -0.971785 -0.600366 -3.280224 - 4 -0.214334 -1.294599 -3.227500 - 5 1.514216 2.028250 -2.989060 - 6 1.074618 5.709767 -2.322600 - 7 2.718061 3.850718 0.256446 - 8 -0.289082 2.454418 1.416871 - 9 0.212668 0.403198 -0.093924 - - >>> df.rolling(3).agg({'A':'sum', 'B':'min'}) - A B - 0 NaN NaN - 1 NaN NaN - 2 -2.655105 -0.165272 - 3 -0.971785 -1.340923 - 4 -0.214334 -1.340923 - 5 1.514216 -1.340923 - 6 1.074618 0.211596 - 7 2.718061 -1.647453 - 8 -0.289082 -1.647453 - 9 0.212668 -1.647453 + >>> df.rolling(2).sum() + A B C + 0 NaN NaN NaN + 1 3.0 9.0 15.0 + 2 5.0 11.0 17.0 + + >>> df.rolling(2).agg({"A": "sum", "B": "min"}) + A B + 0 NaN NaN + 1 3.0 4.0 + 2 5.0 5.0 """ )
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33266
2020-04-03T18:10:47Z
2020-04-04T21:10:00Z
2020-04-04T21:10:00Z
2020-04-06T08:34:41Z
TST: add date range test for reindex case from GH-32740
diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 1529a259c49af..e109c7a4f1c8d 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -1,4 +1,4 @@ -from datetime import date +from datetime import date, timedelta import dateutil import numpy as np @@ -44,6 +44,45 @@ def test_reindex_preserves_tz_if_target_is_empty_list_or_array(self): assert str(index.reindex([])[0].tz) == "US/Eastern" assert str(index.reindex(np.array([]))[0].tz) == "US/Eastern" + def test_reindex_with_same_tz(self): + # GH 32740 + rng_a = date_range("2010-01-01", "2010-01-02", periods=24, tz="utc") + rng_b = date_range("2010-01-01", "2010-01-02", periods=23, tz="utc") + result1, result2 = rng_a.reindex( + rng_b, method="nearest", tolerance=timedelta(seconds=20) + ) + expected_list1 = [ + "2010-01-01 00:00:00", + "2010-01-01 01:05:27.272727272", + "2010-01-01 02:10:54.545454545", + "2010-01-01 03:16:21.818181818", + "2010-01-01 04:21:49.090909090", + "2010-01-01 05:27:16.363636363", + "2010-01-01 06:32:43.636363636", + "2010-01-01 07:38:10.909090909", + "2010-01-01 08:43:38.181818181", + "2010-01-01 09:49:05.454545454", + "2010-01-01 10:54:32.727272727", + "2010-01-01 12:00:00", + "2010-01-01 13:05:27.272727272", + "2010-01-01 14:10:54.545454545", + "2010-01-01 15:16:21.818181818", + "2010-01-01 16:21:49.090909090", + "2010-01-01 17:27:16.363636363", + "2010-01-01 18:32:43.636363636", + "2010-01-01 19:38:10.909090909", + "2010-01-01 20:43:38.181818181", + "2010-01-01 21:49:05.454545454", + "2010-01-01 22:54:32.727272727", + "2010-01-02 00:00:00", + ] + expected1 = DatetimeIndex( + expected_list1, dtype="datetime64[ns, UTC]", freq=None, + ) + expected2 = np.array([0] + [-1] * 21 + [23], dtype=np.int64,) + tm.assert_index_equal(result1, expected1) + tm.assert_numpy_array_equal(result2, expected2) + def test_time_loc(self): # GH8667 from datetime import time from pandas._libs.index import _SIZE_CUTOFF
- [x] closes #32740 - [x] tests added / passed - [x] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33265
2020-04-03T17:48:39Z
2020-04-05T18:28:17Z
2020-04-05T18:28:17Z
2020-04-05T18:28:26Z
DOC: Fixed examples in `pandas/core/aggregation.py`
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 0454150f61045..8901efad56f79 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -272,6 +272,10 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then pytest -q --doctest-modules pandas/core/accessor.py RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Doctests aggregation.py' ; echo $MSG + pytest -q --doctest-modules pandas/core/aggregation.py + RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Doctests base.py' ; echo $MSG pytest -q --doctest-modules pandas/core/base.py RET=$(($RET + $?)) ; echo $MSG "DONE" diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py index 448f84d58d7a0..f6380808d5ac2 100644 --- a/pandas/core/aggregation.py +++ b/pandas/core/aggregation.py @@ -27,10 +27,9 @@ def is_multi_agg_with_relabel(**kwargs) -> bool: Examples -------- - >>> is_multi_agg_with_relabel(a='max') + >>> is_multi_agg_with_relabel(a="max") False - >>> is_multi_agg_with_relabel(a_max=('a', 'max'), - ... a_min=('a', 'min')) + >>> is_multi_agg_with_relabel(a_max=("a", "max"), a_min=("a", "min")) True >>> is_multi_agg_with_relabel() False @@ -61,8 +60,8 @@ def normalize_keyword_aggregation(kwargs: dict) -> Tuple[dict, List[str], List[i Examples -------- - >>> normalize_keyword_aggregation({'output': ('input', 'sum')}) - ({'input': ['sum']}, ('output',), [('input', 'sum')]) + >>> normalize_keyword_aggregation({"output": ("input", "sum")}) + (defaultdict(<class 'list'>, {'input': ['sum']}), ('output',), array([0])) """ # Normalize the aggregation functions as Mapping[column, List[func]], # process normally, then fixup the names.
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/33263
2020-04-03T16:28:45Z
2020-04-07T17:53:06Z
2020-04-07T17:53:06Z
2020-04-07T18:49:39Z
TST: don't assert that matplotlib rejects shorthand hex colors
diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 08b33ee547a48..4a9efe9554c6e 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -2041,12 +2041,6 @@ def test_line_colors(self): self._check_colors(ax.get_lines(), linecolors=custom_colors) tm.close() - with pytest.raises(ValueError): - # Color contains shorthand hex value results in ValueError - custom_colors = ["#F00", "#00F", "#FF0", "#000", "#FFF"] - # Forced show plot - _check_plot_works(df.plot, color=custom_colors) - @pytest.mark.slow def test_dont_modify_colors(self): colors = ["r", "g", "b"] @@ -2098,14 +2092,6 @@ def test_line_colors_and_styles_subplots(self): self._check_colors(ax.get_lines(), linecolors=[c]) tm.close() - with pytest.raises(ValueError): - # Color contains shorthand hex value results in ValueError - custom_colors = ["#F00", "#00F", "#FF0", "#000", "#FFF"] - # Forced show plot - # _check_plot_works adds an ax so catch warning. see GH #13188 - with tm.assert_produces_warning(UserWarning): - _check_plot_works(df.plot, color=custom_colors, subplots=True) - rgba_colors = [cm.jet(n) for n in np.linspace(0, 1, len(df))] for cmap in ["jet", cm.jet]: axes = df.plot(colormap=cmap, subplots=True)
From 3.2 [it accepts them](https://matplotlib.org/users/prev_whats_new/whats_new_3.2.0.html#digit-and-4-digit-hex-colors). [Test failure log](https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=954647) (from Debian's pandas 0.25, so includes other issues we don't now have - this one is DID NOT RAISE).
https://api.github.com/repos/pandas-dev/pandas/pulls/33262
2020-04-03T16:09:29Z
2020-04-03T19:14:24Z
2020-04-03T19:14:24Z
2020-04-03T19:14:34Z
PERF: masked ops for reductions (min/max)
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 19e8acdaa7384..d232b68e3c450 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -274,7 +274,7 @@ Performance improvements sparse values from ``scipy.sparse`` matrices using the :meth:`DataFrame.sparse.from_spmatrix` constructor (:issue:`32821`, :issue:`32825`, :issue:`32826`, :issue:`32856`, :issue:`32858`). -- Performance improvement in :meth:`Series.sum` for nullable (integer and boolean) dtypes (:issue:`30982`). +- Performance improvement in reductions (sum, min, max) for nullable (integer and boolean) dtypes (:issue:`30982`, :issue:`33261`). .. --------------------------------------------------------------------------- diff --git a/pandas/core/array_algos/masked_reductions.py b/pandas/core/array_algos/masked_reductions.py index 0fb2605b554c2..b3723340cefd6 100644 --- a/pandas/core/array_algos/masked_reductions.py +++ b/pandas/core/array_algos/masked_reductions.py @@ -45,3 +45,44 @@ def sum( return np.sum(values[~mask]) else: return np.sum(values, where=~mask) + + +def _minmax(func, values: np.ndarray, mask: np.ndarray, skipna: bool = True): + """ + Reduction for 1D masked array. + + Parameters + ---------- + func : np.min or np.max + values : np.ndarray + Numpy array with the values (can be of any dtype that support the + operation). + mask : np.ndarray + Boolean numpy array (True values indicate missing values). + skipna : bool, default True + Whether to skip NA. + """ + if not skipna: + if mask.any(): + return libmissing.NA + else: + if values.size: + return func(values) + else: + # min/max with empty array raise in numpy, pandas returns NA + return libmissing.NA + else: + subset = values[~mask] + if subset.size: + return func(values[~mask]) + else: + # min/max with empty array raise in numpy, pandas returns NA + return libmissing.NA + + +def min(values: np.ndarray, mask: np.ndarray, skipna: bool = True): + return _minmax(np.min, values=values, mask=mask, skipna=skipna) + + +def max(values: np.ndarray, mask: np.ndarray, skipna: bool = True): + return _minmax(np.max, values=values, mask=mask, skipna=skipna) diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index 442d4ca8cef6d..e85534def6b97 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -696,8 +696,9 @@ def _reduce(self, name: str, skipna: bool = True, **kwargs): data = self._data mask = self._mask - if name == "sum": - return masked_reductions.sum(data, mask, skipna=skipna, **kwargs) + if name in {"sum", "min", "max"}: + op = getattr(masked_reductions, name) + return op(data, mask, skipna=skipna, **kwargs) # coerce to a nan-aware float if needed if self._hasna: @@ -715,9 +716,6 @@ def _reduce(self, name: str, skipna: bool = True, **kwargs): if int_result == result: result = int_result - elif name in ["min", "max"] and notna(result): - result = np.bool_(result) - return result def _maybe_mask_result(self, result, mask, other, op_name: str): diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 4f3c68aa03b16..541ecdeb45830 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -561,8 +561,9 @@ def _reduce(self, name: str, skipna: bool = True, **kwargs): data = self._data mask = self._mask - if name == "sum": - return masked_reductions.sum(data, mask, skipna=skipna, **kwargs) + if name in {"sum", "min", "max"}: + op = getattr(masked_reductions, name) + return op(data, mask, skipna=skipna, **kwargs) # coerce to a nan-aware float if needed # (we explicitly use NaN within reductions) @@ -581,7 +582,7 @@ def _reduce(self, name: str, skipna: bool = True, **kwargs): # if we have a preservable numeric op, # provide coercion back to an integer type if possible - elif name in ["min", "max", "prod"]: + elif name == "prod": # GH#31409 more performant than casting-then-checking result = com.cast_scalar_indexer(result) diff --git a/pandas/tests/arrays/integer/test_dtypes.py b/pandas/tests/arrays/integer/test_dtypes.py index ee1ec86745246..515013e95c717 100644 --- a/pandas/tests/arrays/integer/test_dtypes.py +++ b/pandas/tests/arrays/integer/test_dtypes.py @@ -34,7 +34,7 @@ def test_preserve_dtypes(op): # op result = getattr(df.C, op)() - if op == "sum": + if op in {"sum", "min", "max"}: assert isinstance(result, np.int64) else: assert isinstance(result, int) diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index 962b105d1e8fc..8fb035e085d40 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -65,27 +65,58 @@ def test_ops(self, opname, obj): assert result.value == expected @pytest.mark.parametrize("opname", ["max", "min"]) - def test_nanops(self, opname, index_or_series): + @pytest.mark.parametrize( + "dtype, val", + [ + ("object", 2.0), + ("float64", 2.0), + ("datetime64[ns]", datetime(2011, 11, 1)), + ("Int64", 2), + ("boolean", True), + ], + ) + def test_nanminmax(self, opname, dtype, val, index_or_series): # GH#7261 klass = index_or_series - arg_op = "arg" + opname if klass is Index else "idx" + opname - obj = klass([np.nan, 2.0]) - assert getattr(obj, opname)() == 2.0 + if dtype in ["Int64", "boolean"] and klass == pd.Index: + pytest.skip("EAs can't yet be stored in an index") - obj = klass([np.nan]) - assert pd.isna(getattr(obj, opname)()) - assert pd.isna(getattr(obj, opname)(skipna=False)) + def check_missing(res): + if dtype == "datetime64[ns]": + return res is pd.NaT + elif dtype == "Int64": + return res is pd.NA + else: + return pd.isna(res) - obj = klass([], dtype=object) - assert pd.isna(getattr(obj, opname)()) - assert pd.isna(getattr(obj, opname)(skipna=False)) + obj = klass([None], dtype=dtype) + assert check_missing(getattr(obj, opname)()) + assert check_missing(getattr(obj, opname)(skipna=False)) - obj = klass([pd.NaT, datetime(2011, 11, 1)]) - # check DatetimeIndex monotonic path - assert getattr(obj, opname)() == datetime(2011, 11, 1) - assert getattr(obj, opname)(skipna=False) is pd.NaT + obj = klass([], dtype=dtype) + assert check_missing(getattr(obj, opname)()) + assert check_missing(getattr(obj, opname)(skipna=False)) + + if dtype == "object": + # generic test with object only works for empty / all NaN + return + + obj = klass([None, val], dtype=dtype) + assert getattr(obj, opname)() == val + assert check_missing(getattr(obj, opname)(skipna=False)) + obj = klass([None, val, None], dtype=dtype) + assert getattr(obj, opname)() == val + assert check_missing(getattr(obj, opname)(skipna=False)) + + @pytest.mark.parametrize("opname", ["max", "min"]) + def test_nanargminmax(self, opname, index_or_series): + # GH#7261 + klass = index_or_series + arg_op = "arg" + opname if klass is Index else "idx" + opname + + obj = klass([pd.NaT, datetime(2011, 11, 1)]) assert getattr(obj, arg_op)() == 1 result = getattr(obj, arg_op)(skipna=False) if klass is Series: @@ -95,9 +126,6 @@ def test_nanops(self, opname, index_or_series): obj = klass([pd.NaT, datetime(2011, 11, 1), pd.NaT]) # check DatetimeIndex non-monotonic path - assert getattr(obj, opname)(), datetime(2011, 11, 1) - assert getattr(obj, opname)(skipna=False) is pd.NaT - assert getattr(obj, arg_op)() == 1 result = getattr(obj, arg_op)(skipna=False) if klass is Series:
Follow-up on https://github.com/pandas-dev/pandas/pull/30982, adding similar mask reduction but now for min/max.
https://api.github.com/repos/pandas-dev/pandas/pulls/33261
2020-04-03T15:04:06Z
2020-04-06T23:28:01Z
2020-04-06T23:28:00Z
2020-04-07T06:57:46Z
DOC: Fixed examples in `pandas/core/accessor.py`
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index e987e147fa343..5aecfa543783c 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -268,6 +268,10 @@ if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then # Individual files + MSG='Doctests accessor.py' ; echo $MSG + pytest -q --doctest-modules pandas/core/accessor.py + RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Doctests base.py' ; echo $MSG pytest -q --doctest-modules pandas/core/base.py RET=$(($RET + $?)) ; echo $MSG "DONE" diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py index b6ca19bde8009..f970cefe15527 100644 --- a/pandas/core/accessor.py +++ b/pandas/core/accessor.py @@ -257,12 +257,13 @@ def plot(self): Back in an interactive IPython session: - >>> ds = pd.DataFrame({{'longitude': np.linspace(0, 10), - ... 'latitude': np.linspace(0, 20)}}) - >>> ds.geo.center - (5.0, 10.0) - >>> ds.geo.plot() - # plots data on a map + .. code-block:: ipython + + In [1]: ds = pd.DataFrame({{"longitude": np.linspace(0, 10), + ...: "latitude": np.linspace(0, 20)}}) + In [2]: ds.geo.center + Out[2]: (5.0, 10.0) + In [3]: ds.geo.plot() # plots data on a map """ def decorator(accessor):
Since this changes require an interactive Ipython shell (I think), we can't run check them from pytest. This is what the docs looks like: Before: ![Screenshot_20200403_170159](https://user-images.githubusercontent.com/50263213/78368644-9c0b8400-75cc-11ea-9061-24652f2bdfca.png) After: ![register_acc](https://user-images.githubusercontent.com/50263213/78368530-71b9c680-75cc-11ea-8ab5-d2ee2eadc727.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/33260
2020-04-03T14:01:04Z
2020-04-04T15:29:08Z
2020-04-04T15:29:08Z
2020-04-06T08:35:11Z
DOC: Added an example for each series.dt field accessor
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index be2ac8c22bc8a..b9f9edcebad5b 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -1239,6 +1239,22 @@ def date(self): "Y", """ The year of the datetime. + + Examples + -------- + >>> datetime_series = pd.Series( + ... pd.date_range("2000-01-01", periods=3, freq="Y") + ... ) + >>> datetime_series + 0 2000-12-31 + 1 2001-12-31 + 2 2002-12-31 + dtype: datetime64[ns] + >>> datetime_series.dt.year + 0 2000 + 1 2001 + 2 2002 + dtype: int64 """, ) month = _field_accessor( @@ -1246,6 +1262,22 @@ def date(self): "M", """ The month as January=1, December=12. + + Examples + -------- + >>> datetime_series = pd.Series( + ... pd.date_range("2000-01-01", periods=3, freq="M") + ... ) + >>> datetime_series + 0 2000-01-31 + 1 2000-02-29 + 2 2000-03-31 + dtype: datetime64[ns] + >>> datetime_series.dt.month + 0 1 + 1 2 + 2 3 + dtype: int64 """, ) day = _field_accessor( @@ -1253,6 +1285,22 @@ def date(self): "D", """ The day of the datetime. + + Examples + -------- + >>> datetime_series = pd.Series( + ... pd.date_range("2000-01-01", periods=3, freq="D") + ... ) + >>> datetime_series + 0 2000-01-01 + 1 2000-01-02 + 2 2000-01-03 + dtype: datetime64[ns] + >>> datetime_series.dt.day + 0 1 + 1 2 + 2 3 + dtype: int64 """, ) hour = _field_accessor( @@ -1260,6 +1308,22 @@ def date(self): "h", """ The hours of the datetime. + + Examples + -------- + >>> datetime_series = pd.Series( + ... pd.date_range("2000-01-01", periods=3, freq="h") + ... ) + >>> datetime_series + 0 2000-01-01 00:00:00 + 1 2000-01-01 01:00:00 + 2 2000-01-01 02:00:00 + dtype: datetime64[ns] + >>> datetime_series.dt.hour + 0 0 + 1 1 + 2 2 + dtype: int64 """, ) minute = _field_accessor( @@ -1267,6 +1331,22 @@ def date(self): "m", """ The minutes of the datetime. + + Examples + -------- + >>> datetime_series = pd.Series( + ... pd.date_range("2000-01-01", periods=3, freq="T") + ... ) + >>> datetime_series + 0 2000-01-01 00:00:00 + 1 2000-01-01 00:01:00 + 2 2000-01-01 00:02:00 + dtype: datetime64[ns] + >>> datetime_series.dt.minute + 0 0 + 1 1 + 2 2 + dtype: int64 """, ) second = _field_accessor( @@ -1274,6 +1354,22 @@ def date(self): "s", """ The seconds of the datetime. + + Examples + -------- + >>> datetime_series = pd.Series( + ... pd.date_range("2000-01-01", periods=3, freq="s") + ... ) + >>> datetime_series + 0 2000-01-01 00:00:00 + 1 2000-01-01 00:00:01 + 2 2000-01-01 00:00:02 + dtype: datetime64[ns] + >>> datetime_series.dt.second + 0 0 + 1 1 + 2 2 + dtype: int64 """, ) microsecond = _field_accessor( @@ -1281,6 +1377,22 @@ def date(self): "us", """ The microseconds of the datetime. + + Examples + -------- + >>> datetime_series = pd.Series( + ... pd.date_range("2000-01-01", periods=3, freq="us") + ... ) + >>> datetime_series + 0 2000-01-01 00:00:00.000000 + 1 2000-01-01 00:00:00.000001 + 2 2000-01-01 00:00:00.000002 + dtype: datetime64[ns] + >>> datetime_series.dt.microsecond + 0 0 + 1 1 + 2 2 + dtype: int64 """, ) nanosecond = _field_accessor( @@ -1288,6 +1400,22 @@ def date(self): "ns", """ The nanoseconds of the datetime. + + Examples + -------- + >>> datetime_series = pd.Series( + ... pd.date_range("2000-01-01", periods=3, freq="ns") + ... ) + >>> datetime_series + 0 2000-01-01 00:00:00.000000000 + 1 2000-01-01 00:00:00.000000001 + 2 2000-01-01 00:00:00.000000002 + dtype: datetime64[ns] + >>> datetime_series.dt.nanosecond + 0 0 + 1 1 + 2 2 + dtype: int64 """, ) weekofyear = _field_accessor(
- [x] xref https://github.com/pandas-dev/pandas/pull/33208#discussion_r402189839 - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry --- I can also add examples that would cover, ````TimedeltaProperties``` and ```PeriodProperties```, but I think that would be over verbose, wdyt?
https://api.github.com/repos/pandas-dev/pandas/pulls/33259
2020-04-03T12:35:53Z
2020-04-06T22:10:19Z
2020-04-06T22:10:19Z
2020-04-07T10:48:22Z
CLN: Reorgenized doctests order
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 067d88a666bb3..e987e147fa343 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -266,57 +266,62 @@ fi ### DOCTESTS ### if [[ -z "$CHECK" || "$CHECK" == "doctests" ]]; then + # Individual files + + MSG='Doctests base.py' ; echo $MSG + pytest -q --doctest-modules pandas/core/base.py + RET=$(($RET + $?)) ; echo $MSG "DONE" + + MSG='Doctests construction.py' ; echo $MSG + pytest -q --doctest-modules pandas/core/construction.py + RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Doctests frame.py' ; echo $MSG pytest -q --doctest-modules pandas/core/frame.py RET=$(($RET + $?)) ; echo $MSG "DONE" - MSG='Doctests series.py' ; echo $MSG - pytest -q --doctest-modules pandas/core/series.py + MSG='Doctests generic.py' ; echo $MSG + pytest -q --doctest-modules pandas/core/generic.py RET=$(($RET + $?)) ; echo $MSG "DONE" MSG='Doctests groupby.py' ; echo $MSG pytest -q --doctest-modules pandas/core/groupby/groupby.py -k"-cumcount -describe -pipe" RET=$(($RET + $?)) ; echo $MSG "DONE" - MSG='Doctests indexes' ; echo $MSG - pytest -q --doctest-modules pandas/core/indexes/ + MSG='Doctests series.py' ; echo $MSG + pytest -q --doctest-modules pandas/core/series.py RET=$(($RET + $?)) ; echo $MSG "DONE" - MSG='Doctests tools' ; echo $MSG - pytest -q --doctest-modules pandas/core/tools/ - RET=$(($RET + $?)) ; echo $MSG "DONE" - - MSG='Doctests reshaping functions' ; echo $MSG - pytest -q --doctest-modules pandas/core/reshape/ - RET=$(($RET + $?)) ; echo $MSG "DONE" + # Directories MSG='Doctests arrays'; echo $MSG pytest -q --doctest-modules pandas/core/arrays/ RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Doctests computation' ; echo $MSG + pytest -q --doctest-modules pandas/core/computation/ + RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Doctests dtypes'; echo $MSG pytest -q --doctest-modules pandas/core/dtypes/ RET=$(($RET + $?)) ; echo $MSG "DONE" - MSG='Doctests base.py' ; echo $MSG - pytest -q --doctest-modules pandas/core/base.py + MSG='Doctests indexes' ; echo $MSG + pytest -q --doctest-modules pandas/core/indexes/ RET=$(($RET + $?)) ; echo $MSG "DONE" - MSG='Doctests construction.py' ; echo $MSG - pytest -q --doctest-modules pandas/core/construction.py + MSG='Doctests reshaping functions' ; echo $MSG + pytest -q --doctest-modules pandas/core/reshape/ RET=$(($RET + $?)) ; echo $MSG "DONE" - MSG='Doctests generic.py' ; echo $MSG - pytest -q --doctest-modules pandas/core/generic.py + MSG='Doctests tools' ; echo $MSG + pytest -q --doctest-modules pandas/core/tools/ RET=$(($RET + $?)) ; echo $MSG "DONE" MSG='Doctests tseries' ; echo $MSG pytest -q --doctest-modules pandas/tseries/ RET=$(($RET + $?)) ; echo $MSG "DONE" - MSG='Doctests computation' ; echo $MSG - pytest -q --doctest-modules pandas/core/computation/ - RET=$(($RET + $?)) ; echo $MSG "DONE" fi ### DOCSTRINGS ###
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry --- This does not changes anything, just moving things around, to make it more manageable (IMO)
https://api.github.com/repos/pandas-dev/pandas/pulls/33257
2020-04-03T11:10:20Z
2020-04-03T13:08:38Z
2020-04-03T13:08:38Z
2020-04-03T14:01:48Z
INT: provide helpers for accessing the values of DataFrame columns
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index c4471dacfce9c..cad954c1681c1 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -23,6 +23,7 @@ FrozenSet, Hashable, Iterable, + Iterator, List, Optional, Sequence, @@ -40,7 +41,16 @@ from pandas._config import get_option from pandas._libs import algos as libalgos, lib, properties -from pandas._typing import Axes, Axis, Dtype, FilePathOrBuffer, Label, Level, Renamer +from pandas._typing import ( + ArrayLike, + Axes, + Axis, + Dtype, + FilePathOrBuffer, + Label, + Level, + Renamer, +) from pandas.compat import PY37 from pandas.compat._optional import import_optional_dependency from pandas.compat.numpy import function as nv @@ -2573,6 +2583,21 @@ def _ixs(self, i: int, axis: int = 0): return result + def _get_column_array(self, i: int) -> ArrayLike: + """ + Get the values of the i'th column (ndarray or ExtensionArray, as stored + in the Block) + """ + return self._data.iget_values(i) + + def _iter_column_arrays(self) -> Iterator[ArrayLike]: + """ + Iterate over the arrays of all columns in order. + This returns the values as stored in the Block (ndarray or ExtensionArray). + """ + for i in range(len(self.columns)): + yield self._get_column_array(i) + def __getitem__(self, key): key = lib.item_from_zerodim(key) key = com.apply_if_callable(key, self) @@ -8031,8 +8056,12 @@ def _reduce( assert filter_type is None or filter_type == "bool", filter_type - dtype_is_dt = self.dtypes.apply( - lambda x: is_datetime64_any_dtype(x) or is_period_dtype(x) + dtype_is_dt = np.array( + [ + is_datetime64_any_dtype(values.dtype) or is_period_dtype(values.dtype) + for values in self._iter_column_arrays() + ], + dtype=bool, ) if numeric_only is None and name in ["mean", "median"] and dtype_is_dt.any(): warnings.warn( diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index bfb16b48d832c..cc41bfc45a9cf 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -984,6 +984,14 @@ def iget(self, i: int) -> "SingleBlockManager": self.axes[1], ) + def iget_values(self, i: int) -> ArrayLike: + """ + Return the data for column i as the values (ndarray or ExtensionArray). + """ + block = self.blocks[self.blknos[i]] + values = block.iget(self.blklocs[i]) + return values + def idelete(self, indexer): """ Delete selected locations in-place (new block and array, same BlockManager)
Broken off from https://github.com/pandas-dev/pandas/pull/32867, also mentioned this in https://github.com/pandas-dev/pandas/pull/33229 In general, when doing certain things column-wise, we often just need the arrays (eg to calculate a reduction, to check the dtype, ..), and creating Series gives unnecessary overhead in that case. In this PR, I added therefore two helper functions for making it easier to do this (`_ixs_values` as variant on `_ixs` but returning the array instead of Series, and `_iter_arrays` that calls `_ixs_values` for each column iteratively as an additional helper function). I also used it in one place as illustration (in `_reduce`, what I was working on in https://github.com/pandas-dev/pandas/pull/32867, but it can of course be used more generally). In that example case, it is to replace an apply: ``` In [1]: df = pd.DataFrame(np.random.randint(1000, size=(10000,10))).astype("Int64").copy() In [2]: from pandas.core.dtypes.common import is_datetime64_any_dtype, is_period_dtype In [3]: %timeit df.dtypes.apply(lambda x: is_datetime64_any_dtype(x) or is_period_dtype(x)) 256 µs ± 2.66 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each) In [5]: %timeit np.array([is_datetime64_any_dtype(values) or is_period_dtype(values) for values in df._iter_arrays()], dtype=bool) 56.2 µs ± 282 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each) ``` (and this is only fo 10 columns) @jbrockmendel
https://api.github.com/repos/pandas-dev/pandas/pulls/33252
2020-04-03T07:53:42Z
2020-04-10T17:37:22Z
2020-04-10T17:37:22Z
2020-04-10T17:57:22Z
Display Timedelta nanoseconds
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 7fe8f78151336..0969360d66fcc 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -310,6 +310,7 @@ Timedelta - Bug in constructing a :class:`Timedelta` with a high precision integer that would round the :class:`Timedelta` components (:issue:`31354`) - Bug in dividing ``np.nan`` or ``None`` by :class:`Timedelta`` incorrectly returning ``NaT`` (:issue:`31869`) - Timedeltas now understand ``µs`` as identifier for microsecond (:issue:`32899`) +- :class:`Timedelta` string representation now includes nanoseconds, when nanoseconds are non-zero (:issue:`9309`) Timezones ^^^^^^^^^ diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index c8bf317cbf041..f2b77f3517a25 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -1072,9 +1072,11 @@ cdef class _Timedelta(timedelta): subs = (self._h or self._m or self._s or self._ms or self._us or self._ns) - # by default not showing nano if self._ms or self._us or self._ns: seconds_fmt = "{seconds:02}.{milliseconds:03}{microseconds:03}" + if self._ns: + # GH#9309 + seconds_fmt += "{nanoseconds:03}" else: seconds_fmt = "{seconds:02}" diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index d7529ec799022..960a82caafeeb 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -58,12 +58,12 @@ def to_timedelta(arg, unit="ns", errors="raise"): >>> pd.to_timedelta('1 days 06:05:01.00003') Timedelta('1 days 06:05:01.000030') >>> pd.to_timedelta('15.5us') - Timedelta('0 days 00:00:00.000015') + Timedelta('0 days 00:00:00.000015500') Parsing a list or array of strings: >>> pd.to_timedelta(['1 days 06:05:01.00003', '15.5us', 'nan']) - TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015', NaT], + TimedeltaIndex(['1 days 06:05:01.000030', '0 days 00:00:00.000015500', NaT], dtype='timedelta64[ns]', freq=None) Converting numbers by specifying the `unit` keyword argument: diff --git a/pandas/tests/frame/methods/test_describe.py b/pandas/tests/frame/methods/test_describe.py index 8a75e80a12f52..b61d0d28e2fba 100644 --- a/pandas/tests/frame/methods/test_describe.py +++ b/pandas/tests/frame/methods/test_describe.py @@ -230,15 +230,15 @@ def test_describe_timedelta_values(self): tm.assert_frame_equal(result, expected) exp_repr = ( - " t1 t2\n" - "count 5 5\n" - "mean 3 days 00:00:00 0 days 03:00:00\n" - "std 1 days 13:56:50.394919 0 days 01:34:52.099788\n" - "min 1 days 00:00:00 0 days 01:00:00\n" - "25% 2 days 00:00:00 0 days 02:00:00\n" - "50% 3 days 00:00:00 0 days 03:00:00\n" - "75% 4 days 00:00:00 0 days 04:00:00\n" - "max 5 days 00:00:00 0 days 05:00:00" + " t1 t2\n" + "count 5 5\n" + "mean 3 days 00:00:00 0 days 03:00:00\n" + "std 1 days 13:56:50.394919273 0 days 01:34:52.099788303\n" + "min 1 days 00:00:00 0 days 01:00:00\n" + "25% 2 days 00:00:00 0 days 02:00:00\n" + "50% 3 days 00:00:00 0 days 03:00:00\n" + "75% 4 days 00:00:00 0 days 04:00:00\n" + "max 5 days 00:00:00 0 days 05:00:00" ) assert repr(result) == exp_repr diff --git a/pandas/tests/scalar/timedelta/test_constructors.py b/pandas/tests/scalar/timedelta/test_constructors.py index ec3c6e9e3a326..c58994d738562 100644 --- a/pandas/tests/scalar/timedelta/test_constructors.py +++ b/pandas/tests/scalar/timedelta/test_constructors.py @@ -176,10 +176,9 @@ def test_td_from_repr_roundtrip(val): td = Timedelta(val) assert Timedelta(td.value) == td - # str does not normally display nanos - if not td.nanoseconds: - assert Timedelta(str(td)) == td + assert Timedelta(str(td)) == td assert Timedelta(td._repr_base(format="all")) == td + assert Timedelta(td._repr_base()) == td def test_overflow_on_construction():
- [x] closes #9309 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This allows us to make TimedeltaBlock.to_native_types dispatch to TimedeltaArray._format_native_types. ATM TDBlock.to_native_types has a comment ``` # FIXME: # should use the formats.format.Timedelta64Formatter here # to figure what format to pass to the Timedelta # e.g. to not show the decimals say ```
https://api.github.com/repos/pandas-dev/pandas/pulls/33250
2020-04-03T02:07:48Z
2020-04-03T18:53:38Z
2020-04-03T18:53:37Z
2020-04-03T19:13:12Z
REF: dispatch DatetimeBlock.to_native_types to DTA._format_native_types
diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 741290a4908a5..be2ac8c22bc8a 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -613,8 +613,8 @@ def _format_native_types(self, na_rep="NaT", date_format=None, **kwargs): fmt = _get_format_datetime64_from_values(self, date_format) return tslib.format_array_from_datetime( - self.asi8, tz=self.tz, format=fmt, na_rep=na_rep - ) + self.asi8.ravel(), tz=self.tz, format=fmt, na_rep=na_rep + ).reshape(self.shape) # ----------------------------------------------------------------- # Comparison Methods diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 2cc0bb07bd17f..bd90325114ee1 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -6,7 +6,7 @@ import numpy as np -from pandas._libs import NaT, Timestamp, algos as libalgos, lib, tslib, writers +from pandas._libs import NaT, Timestamp, algos as libalgos, lib, writers import pandas._libs.internals as libinternals from pandas._libs.tslibs import Timedelta, conversion from pandas._libs.tslibs.timezones import tz_compare @@ -2116,21 +2116,13 @@ def _can_hold_element(self, element: Any) -> bool: return is_valid_nat_for_dtype(element, self.dtype) - def to_native_types(self, na_rep=None, date_format=None, quoting=None, **kwargs): - """ convert to our native types format, slicing if desired """ - values = self.values - i8values = self.values.view("i8") - - from pandas.io.formats.format import _get_format_datetime64_from_values - - fmt = _get_format_datetime64_from_values(values, date_format) + def to_native_types(self, na_rep="NaT", date_format=None, **kwargs): + """ convert to our native types format """ + dta = self.array_values() - result = tslib.format_array_from_datetime( - i8values.ravel(), - tz=getattr(self.values, "tz", None), - format=fmt, - na_rep=na_rep, - ).reshape(i8values.shape) + result = dta._format_native_types( + na_rep=na_rep, date_format=date_format, **kwargs + ) return np.atleast_2d(result) def set(self, locs, values): diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 17cc897136aad..a9e668312d751 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1547,7 +1547,7 @@ def _is_dates_only( values: Union[np.ndarray, DatetimeArray, Index, DatetimeIndex] ) -> bool: # return a boolean if we are only dates (and don't have a timezone) - assert values.ndim == 1 + values = values.ravel() values = DatetimeIndex(values) if values.tz is not None:
xref #33248
https://api.github.com/repos/pandas-dev/pandas/pulls/33249
2020-04-03T00:44:48Z
2020-04-03T19:33:31Z
2020-04-03T19:33:31Z
2020-04-03T19:42:46Z
REF: do slicing before calling Block.to_native_types
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 8e2592a603716..44c63aaf6a758 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -651,12 +651,10 @@ def should_store(self, value: ArrayLike) -> bool: """ return is_dtype_equal(value.dtype, self.dtype) - def to_native_types(self, slicer=None, na_rep="nan", quoting=None, **kwargs): - """ convert to our native types format, slicing if desired """ + def to_native_types(self, na_rep="nan", quoting=None, **kwargs): + """ convert to our native types format """ values = self.values - if slicer is not None: - values = values[:, slicer] mask = isna(values) itemsize = writers.word_len(na_rep) @@ -1715,11 +1713,9 @@ def get_values(self, dtype=None): def array_values(self) -> ExtensionArray: return self.values - def to_native_types(self, slicer=None, na_rep="nan", quoting=None, **kwargs): + def to_native_types(self, na_rep="nan", quoting=None, **kwargs): """override to use ExtensionArray astype for the conversion""" values = self.values - if slicer is not None: - values = values[slicer] mask = isna(values) values = np.asarray(values.astype(object)) @@ -1937,18 +1933,10 @@ def _can_hold_element(self, element: Any) -> bool: ) def to_native_types( - self, - slicer=None, - na_rep="", - float_format=None, - decimal=".", - quoting=None, - **kwargs, + self, na_rep="", float_format=None, decimal=".", quoting=None, **kwargs, ): - """ convert to our native types format, slicing if desired """ + """ convert to our native types format """ values = self.values - if slicer is not None: - values = values[:, slicer] # see gh-13418: no special formatting is desired at the # output (important for appropriate 'quoting' behaviour), @@ -2131,17 +2119,11 @@ def _can_hold_element(self, element: Any) -> bool: return is_valid_nat_for_dtype(element, self.dtype) - def to_native_types( - self, slicer=None, na_rep=None, date_format=None, quoting=None, **kwargs - ): + def to_native_types(self, na_rep=None, date_format=None, quoting=None, **kwargs): """ convert to our native types format, slicing if desired """ values = self.values i8values = self.values.view("i8") - if slicer is not None: - values = values[..., slicer] - i8values = i8values[..., slicer] - from pandas.io.formats.format import _get_format_datetime64_from_values fmt = _get_format_datetime64_from_values(values, date_format) @@ -2387,11 +2369,9 @@ def fillna(self, value, **kwargs): ) return super().fillna(value, **kwargs) - def to_native_types(self, slicer=None, na_rep=None, quoting=None, **kwargs): - """ convert to our native types format, slicing if desired """ + def to_native_types(self, na_rep=None, quoting=None, **kwargs): + """ convert to our native types format """ values = self.values - if slicer is not None: - values = values[:, slicer] mask = isna(values) rvalues = np.empty(values.shape, dtype=object) diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py index 0d581f30e50e7..60691d1fea412 100644 --- a/pandas/io/formats/csvs.py +++ b/pandas/io/formats/csvs.py @@ -132,7 +132,7 @@ def __init__( # preallocate data 2d list self.blocks = self.obj._data.blocks - ncols = sum(b.shape[0] for b in self.blocks) + ncols = self.obj.shape[-1] self.data = [None] * ncols if chunksize is None: @@ -327,10 +327,13 @@ def _save_chunk(self, start_i: int, end_i: int) -> None: # create the data for a chunk slicer = slice(start_i, end_i) - for i in range(len(self.blocks)): - b = self.blocks[i] + + df = self.obj.iloc[slicer] + blocks = df._data.blocks + + for i in range(len(blocks)): + b = blocks[i] d = b.to_native_types( - slicer=slicer, na_rep=self.na_rep, float_format=self.float_format, decimal=self.decimal,
Related upcoming steps: - Dispatch DatetimeBlock.to_native_types to DatetimeArray._format_native_types (identical behavior - Dispatch TimeDeltaBlock.to_native_types to TimedeltaArray._format_native_types (behavior changing, but there is a FIXME in the Block version) - Dispatch FloatBlock.to_native_types to Float64Index._format_native_types - Possibly rename to_native_types to something more informative? (i think there's an issue about deprecating/renaming the Index method) - in io.csvs use `df._data.apply` instead of iterating over blocks. Still touches internals, but its a lighter touch.
https://api.github.com/repos/pandas-dev/pandas/pulls/33248
2020-04-02T22:31:00Z
2020-04-03T17:34:13Z
2020-04-03T17:34:13Z
2020-04-03T17:38:24Z
BUG: Fix droped result column in groupby with as_index False
diff --git a/doc/source/whatsnew/v1.1.0.rst b/doc/source/whatsnew/v1.1.0.rst index 814dbe999d5c1..0e61d1acfb022 100644 --- a/doc/source/whatsnew/v1.1.0.rst +++ b/doc/source/whatsnew/v1.1.0.rst @@ -640,6 +640,43 @@ The method :meth:`core.DataFrameGroupBy.size` would previously ignore ``as_index df.groupby("a", as_index=False).size() +.. _whatsnew_110.api_breaking.groupby_results_lost_as_index_false: + +:meth:`DataFrameGroupby.agg` lost results with ``as_index`` ``False`` when relabeling columns +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Previously :meth:`DataFrameGroupby.agg` lost the result columns, when the ``as_index`` option was +set to ``False`` and the result columns were relabeled. In this case he result values were replaced with +the previous index (:issue:`32240`). + +.. ipython:: python + + df = pd.DataFrame({"key": ["x", "y", "z", "x", "y", "z"], + "val": [1.0, 0.8, 2.0, 3.0, 3.6, 0.75]}) + df + +*Previous behavior*: + +.. code-block:: ipython + + In [2]: grouped = df.groupby("key", as_index=False) + In [3]: result = grouped.agg(min_val=pd.NamedAgg(column="val", aggfunc="min")) + In [4]: result + Out[4]: + min_val + 0 x + 1 y + 2 z + +*New behavior*: + +.. ipython:: python + + grouped = df.groupby("key", as_index=False) + result = grouped.agg(min_val=pd.NamedAgg(column="val", aggfunc="min")) + result + + .. _whatsnew_110.notable_bug_fixes.apply_applymap_first_once: apply and applymap on ``DataFrame`` evaluates first row/column only once diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index b9a8f3d5a5176..1d14361757e4a 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -975,16 +975,16 @@ def aggregate(self, func=None, *args, engine=None, engine_kwargs=None, **kwargs) [self._selected_obj.columns.name] * result.columns.nlevels ).droplevel(-1) - if not self.as_index: - self._insert_inaxis_grouper_inplace(result) - result.index = np.arange(len(result)) - if relabeling: # used reordered index of columns result = result.iloc[:, order] result.columns = columns + if not self.as_index: + self._insert_inaxis_grouper_inplace(result) + result.index = np.arange(len(result)) + return result._convert(datetime=True) agg = aggregate diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index bf465635c0085..40a20c8210052 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -795,6 +795,41 @@ def test_groupby_aggregate_empty_key_empty_return(): tm.assert_frame_equal(result, expected) +def test_grouby_agg_loses_results_with_as_index_false_relabel(): + # GH 32240: When the aggregate function relabels column names and + # as_index=False is specified, the results are dropped. + + df = pd.DataFrame( + {"key": ["x", "y", "z", "x", "y", "z"], "val": [1.0, 0.8, 2.0, 3.0, 3.6, 0.75]} + ) + + grouped = df.groupby("key", as_index=False) + result = grouped.agg(min_val=pd.NamedAgg(column="val", aggfunc="min")) + expected = pd.DataFrame({"key": ["x", "y", "z"], "min_val": [1.0, 0.8, 0.75]}) + tm.assert_frame_equal(result, expected) + + +def test_grouby_agg_loses_results_with_as_index_false_relabel_multiindex(): + # GH 32240: When the aggregate function relabels column names and + # as_index=False is specified, the results are dropped. Check if + # multiindex is returned in the right order + + df = pd.DataFrame( + { + "key": ["x", "y", "x", "y", "x", "x"], + "key1": ["a", "b", "c", "b", "a", "c"], + "val": [1.0, 0.8, 2.0, 3.0, 3.6, 0.75], + } + ) + + grouped = df.groupby(["key", "key1"], as_index=False) + result = grouped.agg(min_val=pd.NamedAgg(column="val", aggfunc="min")) + expected = pd.DataFrame( + {"key": ["x", "x", "y"], "key1": ["a", "c", "b"], "min_val": [1.0, 0.75, 0.8]} + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( "func", [lambda s: s.mean(), lambda s: np.mean(s), lambda s: np.nanmean(s)] )
- [x] closes #32240 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry The aggregate function *lost* the results of the aggregate operation, if the ```as_index=False``` flag was set and one of the result columns is relabeled. The index was reset at first, adding columns to the DataFrame. The relabeling operation only took the columns before resetting the index as input. So the weird error occurred. I changed the order of the index reset and the relabeling. This fixes the issue.
https://api.github.com/repos/pandas-dev/pandas/pulls/33247
2020-04-02T21:27:15Z
2020-07-15T22:19:13Z
2020-07-15T22:19:13Z
2020-09-05T19:04:49Z
BLD: recursive inclusion of DLLs in package data
diff --git a/setup.py b/setup.py index 461ef005c3df3..562273abb3e18 100755 --- a/setup.py +++ b/setup.py @@ -757,7 +757,7 @@ def setup_package(): maintainer=AUTHOR, version=versioneer.get_version(), packages=find_packages(include=["pandas", "pandas.*"]), - package_data={"": ["templates/*", "_libs/*.dll"]}, + package_data={"": ["templates/*", "_libs/**/*.dll"]}, ext_modules=maybe_cythonize(extensions, compiler_directives=directives), maintainer_email=EMAIL, description=DESCRIPTION,
- [x] step 1 towards #32857 Will also make a PR in https://github.com/MacPython/pandas-wheels to add the DLLs to the wheel packaging script
https://api.github.com/repos/pandas-dev/pandas/pulls/33246
2020-04-02T19:58:38Z
2020-04-10T21:05:21Z
2020-04-10T21:05:21Z
2020-05-26T09:37:43Z
CLN: Separate transform tests
diff --git a/pandas/tests/frame/apply/test_frame_apply.py b/pandas/tests/frame/apply/test_frame_apply.py index 5a1e448beb40f..bc09501583e2c 100644 --- a/pandas/tests/frame/apply/test_frame_apply.py +++ b/pandas/tests/frame/apply/test_frame_apply.py @@ -1,7 +1,6 @@ from collections import OrderedDict from datetime import datetime from itertools import chain -import operator import warnings import numpy as np @@ -14,6 +13,7 @@ import pandas._testing as tm from pandas.core.apply import frame_apply from pandas.core.base import SpecificationError +from pandas.tests.frame.common import zip_frames @pytest.fixture @@ -1058,25 +1058,6 @@ def test_consistency_for_boxed(self, box, int_frame_const_col): tm.assert_frame_equal(result, expected) -def zip_frames(frames, axis=1): - """ - take a list of frames, zip them together under the - assumption that these all have the first frames' index/columns. - - Returns - ------- - new_frame : DataFrame - """ - if axis == 1: - columns = frames[0].columns - zipped = [f.loc[:, c] for c in columns for f in frames] - return pd.concat(zipped, axis=1) - else: - index = frames[0].index - zipped = [f.loc[i, :] for i in index for f in frames] - return pd.DataFrame(zipped) - - class TestDataFrameAggregate: def test_agg_transform(self, axis, float_frame): other_axis = 1 if axis in {0, "index"} else 0 @@ -1087,16 +1068,10 @@ def test_agg_transform(self, axis, float_frame): f_sqrt = np.sqrt(float_frame) # ufunc - result = float_frame.transform(np.sqrt, axis=axis) expected = f_sqrt.copy() - tm.assert_frame_equal(result, expected) - result = float_frame.apply(np.sqrt, axis=axis) tm.assert_frame_equal(result, expected) - result = float_frame.transform(np.sqrt, axis=axis) - tm.assert_frame_equal(result, expected) - # list-like result = float_frame.apply([np.sqrt], axis=axis) expected = f_sqrt.copy() @@ -1110,9 +1085,6 @@ def test_agg_transform(self, axis, float_frame): ) tm.assert_frame_equal(result, expected) - result = float_frame.transform([np.sqrt], axis=axis) - tm.assert_frame_equal(result, expected) - # multiple items in list # these are in the order as if we are applying both # functions per series and then concatting @@ -1128,38 +1100,19 @@ def test_agg_transform(self, axis, float_frame): ) tm.assert_frame_equal(result, expected) - result = float_frame.transform([np.abs, "sqrt"], axis=axis) - tm.assert_frame_equal(result, expected) - def test_transform_and_agg_err(self, axis, float_frame): # cannot both transform and agg - msg = "transforms cannot produce aggregated results" - with pytest.raises(ValueError, match=msg): - float_frame.transform(["max", "min"], axis=axis) - msg = "cannot combine transform and aggregation operations" with pytest.raises(ValueError, match=msg): with np.errstate(all="ignore"): float_frame.agg(["max", "sqrt"], axis=axis) - with pytest.raises(ValueError, match=msg): - with np.errstate(all="ignore"): - float_frame.transform(["max", "sqrt"], axis=axis) - df = pd.DataFrame({"A": range(5), "B": 5}) def f(): with np.errstate(all="ignore"): df.agg({"A": ["abs", "sum"], "B": ["mean", "max"]}, axis=axis) - @pytest.mark.parametrize("method", ["abs", "shift", "pct_change", "cumsum", "rank"]) - def test_transform_method_name(self, method): - # GH 19760 - df = pd.DataFrame({"A": [-1, 2]}) - result = df.transform(method) - expected = operator.methodcaller(method)(df) - tm.assert_frame_equal(result, expected) - def test_demo(self): # demonstration tests df = pd.DataFrame({"A": range(5), "B": 5}) diff --git a/pandas/tests/frame/apply/test_frame_transform.py b/pandas/tests/frame/apply/test_frame_transform.py new file mode 100644 index 0000000000000..3a345215482ed --- /dev/null +++ b/pandas/tests/frame/apply/test_frame_transform.py @@ -0,0 +1,72 @@ +import operator + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.tests.frame.common import zip_frames + + +def test_agg_transform(axis, float_frame): + other_axis = 1 if axis in {0, "index"} else 0 + + with np.errstate(all="ignore"): + + f_abs = np.abs(float_frame) + f_sqrt = np.sqrt(float_frame) + + # ufunc + result = float_frame.transform(np.sqrt, axis=axis) + expected = f_sqrt.copy() + tm.assert_frame_equal(result, expected) + + result = float_frame.transform(np.sqrt, axis=axis) + tm.assert_frame_equal(result, expected) + + # list-like + expected = f_sqrt.copy() + if axis in {0, "index"}: + expected.columns = pd.MultiIndex.from_product( + [float_frame.columns, ["sqrt"]] + ) + else: + expected.index = pd.MultiIndex.from_product([float_frame.index, ["sqrt"]]) + result = float_frame.transform([np.sqrt], axis=axis) + tm.assert_frame_equal(result, expected) + + # multiple items in list + # these are in the order as if we are applying both + # functions per series and then concatting + expected = zip_frames([f_abs, f_sqrt], axis=other_axis) + if axis in {0, "index"}: + expected.columns = pd.MultiIndex.from_product( + [float_frame.columns, ["absolute", "sqrt"]] + ) + else: + expected.index = pd.MultiIndex.from_product( + [float_frame.index, ["absolute", "sqrt"]] + ) + result = float_frame.transform([np.abs, "sqrt"], axis=axis) + tm.assert_frame_equal(result, expected) + + +def test_transform_and_agg_err(axis, float_frame): + # cannot both transform and agg + msg = "transforms cannot produce aggregated results" + with pytest.raises(ValueError, match=msg): + float_frame.transform(["max", "min"], axis=axis) + + msg = "cannot combine transform and aggregation operations" + with pytest.raises(ValueError, match=msg): + with np.errstate(all="ignore"): + float_frame.transform(["max", "sqrt"], axis=axis) + + +@pytest.mark.parametrize("method", ["abs", "shift", "pct_change", "cumsum", "rank"]) +def test_transform_method_name(method): + # GH 19760 + df = pd.DataFrame({"A": [-1, 2]}) + result = df.transform(method) + expected = operator.methodcaller(method)(df) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/common.py b/pandas/tests/frame/common.py index 463a140972ab5..73e60ff389038 100644 --- a/pandas/tests/frame/common.py +++ b/pandas/tests/frame/common.py @@ -1,3 +1,8 @@ +from typing import List + +from pandas import DataFrame, concat + + def _check_mixed_float(df, dtype=None): # float16 are most likely to be upcasted to float32 dtypes = dict(A="float32", B="float32", C="float16", D="float64") @@ -29,3 +34,22 @@ def _check_mixed_int(df, dtype=None): assert df.dtypes["C"] == dtypes["C"] if dtypes.get("D"): assert df.dtypes["D"] == dtypes["D"] + + +def zip_frames(frames: List[DataFrame], axis: int = 1) -> DataFrame: + """ + take a list of frames, zip them together under the + assumption that these all have the first frames' index/columns. + + Returns + ------- + new_frame : DataFrame + """ + if axis == 1: + columns = frames[0].columns + zipped = [f.loc[:, c] for c in columns for f in frames] + return concat(zipped, axis=1) + else: + index = frames[0].index + zipped = [f.loc[i, :] for i in index for f in frames] + return DataFrame(zipped) diff --git a/pandas/tests/series/apply/test_series_apply.py b/pandas/tests/series/apply/test_series_apply.py index 308398642895c..b948317f32062 100644 --- a/pandas/tests/series/apply/test_series_apply.py +++ b/pandas/tests/series/apply/test_series_apply.py @@ -209,25 +209,16 @@ def test_transform(self, string_series): f_abs = np.abs(string_series) # ufunc - result = string_series.transform(np.sqrt) expected = f_sqrt.copy() - tm.assert_series_equal(result, expected) - result = string_series.apply(np.sqrt) tm.assert_series_equal(result, expected) # list-like - result = string_series.transform([np.sqrt]) + result = string_series.apply([np.sqrt]) expected = f_sqrt.to_frame().copy() expected.columns = ["sqrt"] tm.assert_frame_equal(result, expected) - result = string_series.transform([np.sqrt]) - tm.assert_frame_equal(result, expected) - - result = string_series.transform(["sqrt"]) - tm.assert_frame_equal(result, expected) - # multiple items in list # these are in the order as if we are applying both functions per # series and then concatting @@ -236,10 +227,6 @@ def test_transform(self, string_series): result = string_series.apply([np.sqrt, np.abs]) tm.assert_frame_equal(result, expected) - result = string_series.transform(["sqrt", "abs"]) - expected.columns = ["sqrt", "abs"] - tm.assert_frame_equal(result, expected) - # dict, provide renaming expected = pd.concat([f_sqrt, f_abs], axis=1) expected.columns = ["foo", "bar"] @@ -250,19 +237,11 @@ def test_transform(self, string_series): def test_transform_and_agg_error(self, string_series): # we are trying to transform with an aggregator - msg = "transforms cannot produce aggregated results" - with pytest.raises(ValueError, match=msg): - string_series.transform(["min", "max"]) - msg = "cannot combine transform and aggregation" with pytest.raises(ValueError, match=msg): with np.errstate(all="ignore"): string_series.agg(["sqrt", "max"]) - with pytest.raises(ValueError, match=msg): - with np.errstate(all="ignore"): - string_series.transform(["sqrt", "max"]) - msg = "cannot perform both aggregation and transformation" with pytest.raises(ValueError, match=msg): with np.errstate(all="ignore"): @@ -463,14 +442,6 @@ def test_agg_cython_table_raises(self, series, func, expected): # e.g. Series('a b'.split()).cumprod() will raise series.agg(func) - def test_transform_none_to_type(self): - # GH34377 - df = pd.DataFrame({"a": [None]}) - - msg = "DataFrame constructor called with incompatible data and dtype" - with pytest.raises(TypeError, match=msg): - df.transform({"a": int}) - class TestSeriesMap: def test_map(self, datetime_series): diff --git a/pandas/tests/series/apply/test_series_transform.py b/pandas/tests/series/apply/test_series_transform.py new file mode 100644 index 0000000000000..8bc3d2dc4d0db --- /dev/null +++ b/pandas/tests/series/apply/test_series_transform.py @@ -0,0 +1,59 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm + + +def test_transform(string_series): + # transforming functions + + with np.errstate(all="ignore"): + f_sqrt = np.sqrt(string_series) + f_abs = np.abs(string_series) + + # ufunc + result = string_series.transform(np.sqrt) + expected = f_sqrt.copy() + tm.assert_series_equal(result, expected) + + # list-like + result = string_series.transform([np.sqrt]) + expected = f_sqrt.to_frame().copy() + expected.columns = ["sqrt"] + tm.assert_frame_equal(result, expected) + + result = string_series.transform([np.sqrt]) + tm.assert_frame_equal(result, expected) + + result = string_series.transform(["sqrt"]) + tm.assert_frame_equal(result, expected) + + # multiple items in list + # these are in the order as if we are applying both functions per + # series and then concatting + expected = pd.concat([f_sqrt, f_abs], axis=1) + result = string_series.transform(["sqrt", "abs"]) + expected.columns = ["sqrt", "abs"] + tm.assert_frame_equal(result, expected) + + +def test_transform_and_agg_error(string_series): + # we are trying to transform with an aggregator + msg = "transforms cannot produce aggregated results" + with pytest.raises(ValueError, match=msg): + string_series.transform(["min", "max"]) + + msg = "cannot combine transform and aggregation operations" + with pytest.raises(ValueError, match=msg): + with np.errstate(all="ignore"): + string_series.transform(["sqrt", "max"]) + + +def test_transform_none_to_type(): + # GH34377 + df = pd.DataFrame({"a": [None]}) + + msg = "DataFrame constructor called with incompatible data and dtype" + with pytest.raises(TypeError, match=msg): + df.transform({"a": int})
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Setup for #35964. There were two tests that are accidental duplicates; I've just copied them over to the transform modules. Will cleanup in #35964.
https://api.github.com/repos/pandas-dev/pandas/pulls/36146
2020-09-05T19:29:24Z
2020-09-06T17:11:05Z
2020-09-06T17:11:05Z
2020-09-10T00:07:40Z
DOC: add userwarning doc about mpl #35684
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index b1229a5d5823d..d7d2e3cf876ca 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -301,7 +301,7 @@ Plotting ^^^^^^^^ - Bug in :meth:`DataFrame.plot` where a marker letter in the ``style`` keyword sometimes causes a ``ValueError`` (:issue:`21003`) -- +- meth:`DataFrame.plot` and meth:`Series.plot` raise ``UserWarning`` about usage of FixedFormatter and FixedLocator (:issue:`35684` and :issue:`35945`) Groupby/resample/rolling ^^^^^^^^^^^^^^^^^^^^^^^^
- [x] closes #35684 - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/36145
2020-09-05T15:39:27Z
2020-09-05T19:50:44Z
2020-09-05T19:50:43Z
2020-09-06T05:16:07Z
STY+CI: check for private function access across modules
diff --git a/Makefile b/Makefile index f26689ab65ba5..4a9a48992f92f 100644 --- a/Makefile +++ b/Makefile @@ -25,3 +25,10 @@ doc: cd doc; \ python make.py clean; \ python make.py html + +check: + python3 scripts/validate_unwanted_patterns.py \ + --validation-type="private_function_across_module" \ + --included-file-extensions="py" \ + --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored \ + pandas/ diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 6006d09bc3e78..9efc53ced1b8f 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -116,6 +116,14 @@ if [[ -z "$CHECK" || "$CHECK" == "lint" ]]; then fi RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Check for use of private module attribute access' ; echo $MSG + if [[ "$GITHUB_ACTIONS" == "true" ]]; then + $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="private_function_across_module" --included-file-extensions="py" --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored --format="##[error]{source_path}:{line_number}:{msg}" pandas/ + else + $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="private_function_across_module" --included-file-extensions="py" --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored pandas/ + fi + RET=$(($RET + $?)) ; echo $MSG "DONE" + echo "isort --version-number" isort --version-number diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index 0a70afda893cf..c4723a5f064c7 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -412,7 +412,7 @@ ctypedef fused algos_t: uint8_t -def _validate_limit(nobs: int, limit=None) -> int: +def validate_limit(nobs: int, limit=None) -> int: """ Check that the `limit` argument is a positive integer. @@ -452,7 +452,7 @@ def pad(ndarray[algos_t] old, ndarray[algos_t] new, limit=None): indexer = np.empty(nright, dtype=np.int64) indexer[:] = -1 - lim = _validate_limit(nright, limit) + lim = validate_limit(nright, limit) if nleft == 0 or nright == 0 or new[nright - 1] < old[0]: return indexer @@ -509,7 +509,7 @@ def pad_inplace(algos_t[:] values, const uint8_t[:] mask, limit=None): if N == 0: return - lim = _validate_limit(N, limit) + lim = validate_limit(N, limit) val = values[0] for i in range(N): @@ -537,7 +537,7 @@ def pad_2d_inplace(algos_t[:, :] values, const uint8_t[:, :] mask, limit=None): if N == 0: return - lim = _validate_limit(N, limit) + lim = validate_limit(N, limit) for j in range(K): fill_count = 0 @@ -593,7 +593,7 @@ def backfill(ndarray[algos_t] old, ndarray[algos_t] new, limit=None) -> ndarray: indexer = np.empty(nright, dtype=np.int64) indexer[:] = -1 - lim = _validate_limit(nright, limit) + lim = validate_limit(nright, limit) if nleft == 0 or nright == 0 or new[0] > old[nleft - 1]: return indexer @@ -651,7 +651,7 @@ def backfill_inplace(algos_t[:] values, const uint8_t[:] mask, limit=None): if N == 0: return - lim = _validate_limit(N, limit) + lim = validate_limit(N, limit) val = values[N - 1] for i in range(N - 1, -1, -1): @@ -681,7 +681,7 @@ def backfill_2d_inplace(algos_t[:, :] values, if N == 0: return - lim = _validate_limit(N, limit) + lim = validate_limit(N, limit) for j in range(K): fill_count = 0 diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index f297c7165208f..50ec3714f454b 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -60,7 +60,7 @@ from pandas.core.indexers import validate_indices if TYPE_CHECKING: - from pandas import Categorical, DataFrame, Series + from pandas import Categorical, DataFrame, Series # noqa:F401 _shared_docs: Dict[str, str] = {} @@ -767,7 +767,7 @@ def value_counts( counts = result._values else: - keys, counts = _value_counts_arraylike(values, dropna) + keys, counts = value_counts_arraylike(values, dropna) result = Series(counts, index=keys, name=name) @@ -780,8 +780,8 @@ def value_counts( return result -# Called once from SparseArray -def _value_counts_arraylike(values, dropna: bool): +# Called once from SparseArray, otherwise could be private +def value_counts_arraylike(values, dropna: bool): """ Parameters ---------- diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 1531f7b292365..47c960dc969d6 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -735,7 +735,7 @@ def value_counts(self, dropna=True): """ from pandas import Index, Series - keys, counts = algos._value_counts_arraylike(self.sp_values, dropna=dropna) + keys, counts = algos.value_counts_arraylike(self.sp_values, dropna=dropna) fcounts = self.sp_index.ngaps if fcounts > 0: if self._null_fill_value and dropna: diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 3bcd4debbf41a..9f4e535dc787d 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -390,7 +390,7 @@ def fillna( mask = isna(self.values) if limit is not None: - limit = libalgos._validate_limit(None, limit=limit) + limit = libalgos.validate_limit(None, limit=limit) mask[mask.cumsum(self.ndim - 1) > limit] = False if not self._can_hold_na: diff --git a/pandas/core/missing.py b/pandas/core/missing.py index 7802c5cbdbfb3..be66b19d10064 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -228,7 +228,7 @@ def interpolate_1d( ) # default limit is unlimited GH #16282 - limit = algos._validate_limit(nobs=None, limit=limit) + limit = algos.validate_limit(nobs=None, limit=limit) # These are sets of index pointers to invalid values... i.e. {0, 1, etc... all_nans = set(np.flatnonzero(invalid)) diff --git a/pandas/plotting/_matplotlib/compat.py b/pandas/plotting/_matplotlib/compat.py index 7f107f18eca25..964596d9b6319 100644 --- a/pandas/plotting/_matplotlib/compat.py +++ b/pandas/plotting/_matplotlib/compat.py @@ -17,8 +17,8 @@ def inner(): return inner -_mpl_ge_2_2_3 = _mpl_version("2.2.3", operator.ge) -_mpl_ge_3_0_0 = _mpl_version("3.0.0", operator.ge) -_mpl_ge_3_1_0 = _mpl_version("3.1.0", operator.ge) -_mpl_ge_3_2_0 = _mpl_version("3.2.0", operator.ge) -_mpl_ge_3_3_0 = _mpl_version("3.3.0", operator.ge) +mpl_ge_2_2_3 = _mpl_version("2.2.3", operator.ge) +mpl_ge_3_0_0 = _mpl_version("3.0.0", operator.ge) +mpl_ge_3_1_0 = _mpl_version("3.1.0", operator.ge) +mpl_ge_3_2_0 = _mpl_version("3.2.0", operator.ge) +mpl_ge_3_3_0 = _mpl_version("3.3.0", operator.ge) diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index f0b35e1cd2a74..17f6696ba3480 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -30,7 +30,7 @@ import pandas.core.common as com from pandas.io.formats.printing import pprint_thing -from pandas.plotting._matplotlib.compat import _mpl_ge_3_0_0 +from pandas.plotting._matplotlib.compat import mpl_ge_3_0_0 from pandas.plotting._matplotlib.converter import register_pandas_matplotlib_converters from pandas.plotting._matplotlib.style import get_standard_colors from pandas.plotting._matplotlib.timeseries import ( @@ -939,7 +939,7 @@ def _plot_colorbar(self, ax: "Axes", **kwds): img = ax.collections[-1] cbar = self.fig.colorbar(img, ax=ax, **kwds) - if _mpl_ge_3_0_0(): + if mpl_ge_3_0_0(): # The workaround below is no longer necessary. return diff --git a/pandas/plotting/_matplotlib/tools.py b/pandas/plotting/_matplotlib/tools.py index 98aaab6838fba..c5b44f37150bb 100644 --- a/pandas/plotting/_matplotlib/tools.py +++ b/pandas/plotting/_matplotlib/tools.py @@ -307,7 +307,7 @@ def handle_shared_axes( sharey: bool, ): if nplots > 1: - if compat._mpl_ge_3_2_0(): + if compat.mpl_ge_3_2_0(): row_num = lambda x: x.get_subplotspec().rowspan.start col_num = lambda x: x.get_subplotspec().colspan.start else: diff --git a/pandas/tests/plotting/common.py b/pandas/tests/plotting/common.py index b753c96af6290..9301a29933d45 100644 --- a/pandas/tests/plotting/common.py +++ b/pandas/tests/plotting/common.py @@ -28,10 +28,10 @@ def setup_method(self, method): mpl.rcdefaults() - self.mpl_ge_2_2_3 = compat._mpl_ge_2_2_3() - self.mpl_ge_3_0_0 = compat._mpl_ge_3_0_0() - self.mpl_ge_3_1_0 = compat._mpl_ge_3_1_0() - self.mpl_ge_3_2_0 = compat._mpl_ge_3_2_0() + self.mpl_ge_2_2_3 = compat.mpl_ge_2_2_3() + self.mpl_ge_3_0_0 = compat.mpl_ge_3_0_0() + self.mpl_ge_3_1_0 = compat.mpl_ge_3_1_0() + self.mpl_ge_3_2_0 = compat.mpl_ge_3_2_0() self.bp_n_objects = 7 self.polycollection_factor = 2 diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 128a7bdb6730a..9a323f2024721 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -51,7 +51,7 @@ def _assert_xtickslabels_visibility(self, axes, expected): @pytest.mark.xfail(reason="Waiting for PR 34334", strict=True) @pytest.mark.slow def test_plot(self): - from pandas.plotting._matplotlib.compat import _mpl_ge_3_1_0 + from pandas.plotting._matplotlib.compat import mpl_ge_3_1_0 df = self.tdf _check_plot_works(df.plot, grid=False) @@ -69,7 +69,7 @@ def test_plot(self): self._check_axes_shape(axes, axes_num=4, layout=(4, 1)) df = DataFrame({"x": [1, 2], "y": [3, 4]}) - if _mpl_ge_3_1_0(): + if mpl_ge_3_1_0(): msg = "'Line2D' object has no property 'blarg'" else: msg = "Unknown property blarg" diff --git a/pandas/tests/plotting/test_misc.py b/pandas/tests/plotting/test_misc.py index 130acaa8bcd58..0208ab3e0225b 100644 --- a/pandas/tests/plotting/test_misc.py +++ b/pandas/tests/plotting/test_misc.py @@ -96,7 +96,7 @@ def test_bootstrap_plot(self): class TestDataFramePlots(TestPlotBase): @td.skip_if_no_scipy def test_scatter_matrix_axis(self): - from pandas.plotting._matplotlib.compat import _mpl_ge_3_0_0 + from pandas.plotting._matplotlib.compat import mpl_ge_3_0_0 scatter_matrix = plotting.scatter_matrix @@ -105,7 +105,7 @@ def test_scatter_matrix_axis(self): # we are plotting multiples on a sub-plot with tm.assert_produces_warning( - UserWarning, raise_on_extra_warnings=_mpl_ge_3_0_0() + UserWarning, raise_on_extra_warnings=mpl_ge_3_0_0() ): axes = _check_plot_works( scatter_matrix, filterwarnings="always", frame=df, range_padding=0.1 diff --git a/scripts/validate_unwanted_patterns.py b/scripts/validate_unwanted_patterns.py index 193fef026a96b..1a6d8cc8b9914 100755 --- a/scripts/validate_unwanted_patterns.py +++ b/scripts/validate_unwanted_patterns.py @@ -16,9 +16,7 @@ import sys import token import tokenize -from typing import IO, Callable, FrozenSet, Iterable, List, Tuple - -PATHS_TO_IGNORE: Tuple[str, ...] = ("asv_bench/env",) +from typing import IO, Callable, FrozenSet, Iterable, List, Set, Tuple def _get_literal_string_prefix_len(token_string: str) -> int: @@ -114,6 +112,58 @@ def bare_pytest_raises(file_obj: IO[str]) -> Iterable[Tuple[int, str]]: ) +PRIVATE_FUNCTIONS_ALLOWED = {"sys._getframe"} # no known alternative + + +def private_function_across_module(file_obj: IO[str]) -> Iterable[Tuple[int, str]]: + """ + Checking that a private function is not used across modules. + Parameters + ---------- + file_obj : IO + File-like object containing the Python code to validate. + Yields + ------ + line_number : int + Line number of the private function that is used across modules. + msg : str + Explenation of the error. + """ + contents = file_obj.read() + tree = ast.parse(contents) + + imported_modules: Set[str] = set() + + for node in ast.walk(tree): + if isinstance(node, (ast.Import, ast.ImportFrom)): + for module in node.names: + module_fqdn = module.name if module.asname is None else module.asname + imported_modules.add(module_fqdn) + + if not isinstance(node, ast.Call): + continue + + try: + module_name = node.func.value.id + function_name = node.func.attr + except AttributeError: + continue + + # Exception section # + + # (Debatable) Class case + if module_name[0].isupper(): + continue + # (Debatable) Dunder methods case + elif function_name.startswith("__") and function_name.endswith("__"): + continue + elif module_name + "." + function_name in PRIVATE_FUNCTIONS_ALLOWED: + continue + + if module_name in imported_modules and function_name.startswith("_"): + yield (node.lineno, f"Private function '{module_name}.{function_name}'") + + def strings_to_concatenate(file_obj: IO[str]) -> Iterable[Tuple[int, str]]: """ This test case is necessary after 'Black' (https://github.com/psf/black), @@ -293,6 +343,7 @@ def main( source_path: str, output_format: str, file_extensions_to_check: str, + excluded_file_paths: str, ) -> bool: """ Main entry point of the script. @@ -305,6 +356,10 @@ def main( Source path representing path to a file/directory. output_format : str Output format of the error message. + file_extensions_to_check : str + Coma seperated values of what file extensions to check. + excluded_file_paths : str + Coma seperated values of what file paths to exclude during the check. Returns ------- @@ -325,6 +380,7 @@ def main( FILE_EXTENSIONS_TO_CHECK: FrozenSet[str] = frozenset( file_extensions_to_check.split(",") ) + PATHS_TO_IGNORE = frozenset(excluded_file_paths.split(",")) if os.path.isfile(source_path): file_path = source_path @@ -362,6 +418,7 @@ def main( if __name__ == "__main__": available_validation_types: List[str] = [ "bare_pytest_raises", + "private_function_across_module", "strings_to_concatenate", "strings_with_wrong_placed_whitespace", ] @@ -389,6 +446,11 @@ def main( default="py,pyx,pxd,pxi", help="Coma seperated file extensions to check.", ) + parser.add_argument( + "--excluded-file-paths", + default="asv_bench/env", + help="Comma separated file extensions to check.", + ) args = parser.parse_args() @@ -398,5 +460,6 @@ def main( source_path=args.path, output_format=args.format, file_extensions_to_check=args.included_file_extensions, + excluded_file_paths=args.excluded_file_paths, ) )
The added checks here are broken off from #36055.
https://api.github.com/repos/pandas-dev/pandas/pulls/36144
2020-09-05T15:03:38Z
2020-09-05T17:53:22Z
2020-09-05T17:53:22Z
2021-04-12T15:30:07Z
CLN: unused case in compare_or_regex_search
diff --git a/pandas/core/array_algos/replace.py b/pandas/core/array_algos/replace.py index 6ac3cc1f9f2fe..09f9aefd64096 100644 --- a/pandas/core/array_algos/replace.py +++ b/pandas/core/array_algos/replace.py @@ -3,7 +3,7 @@ """ import operator import re -from typing import Optional, Pattern, Union +from typing import Pattern, Union import numpy as np @@ -14,14 +14,10 @@ is_numeric_v_string_like, is_scalar, ) -from pandas.core.dtypes.missing import isna def compare_or_regex_search( - a: ArrayLike, - b: Union[Scalar, Pattern], - regex: bool = False, - mask: Optional[ArrayLike] = None, + a: ArrayLike, b: Union[Scalar, Pattern], regex: bool, mask: ArrayLike, ) -> Union[ArrayLike, bool]: """ Compare two array_like inputs of the same shape or two scalar values @@ -33,8 +29,8 @@ def compare_or_regex_search( ---------- a : array_like b : scalar or regex pattern - regex : bool, default False - mask : array_like or None (default) + regex : bool + mask : array_like Returns ------- @@ -68,8 +64,6 @@ def _check_comparison_types( ) # GH#32621 use mask to avoid comparing to NAs - if mask is None and isinstance(a, np.ndarray) and not isinstance(b, np.ndarray): - mask = np.reshape(~(isna(a)), a.shape) if isinstance(a, np.ndarray): a = a[mask]
https://api.github.com/repos/pandas-dev/pandas/pulls/36143
2020-09-05T15:00:00Z
2020-09-05T17:54:30Z
2020-09-05T17:54:30Z
2020-09-05T18:49:02Z
BUG: copying series into empty dataframe does not preserve dataframe index name
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index da261907565a1..c40430256f64b 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -42,6 +42,7 @@ Bug fixes - Bug in :class:`DataFrame` indexing returning an incorrect :class:`Series` in some cases when the series has been altered and a cache not invalidated (:issue:`33675`) - Bug in :meth:`DataFrame.corr` causing subsequent indexing lookups to be incorrect (:issue:`35882`) - Bug in :meth:`import_optional_dependency` returning incorrect package names in cases where package name is different from import name (:issue:`35948`) +- Bug when setting empty :class:`DataFrame` column to a :class:`Series` in preserving name of index in frame (:issue:`31368`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index e1a889bf79d95..59cf4c0e2f81d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3206,9 +3206,11 @@ def _ensure_valid_index(self, value): "and a value that cannot be converted to a Series" ) from err - self._mgr = self._mgr.reindex_axis( - value.index.copy(), axis=1, fill_value=np.nan - ) + # GH31368 preserve name of index + index_copy = value.index.copy() + index_copy.name = self.index.name + + self._mgr = self._mgr.reindex_axis(index_copy, axis=1, fill_value=np.nan) def _box_col_values(self, values, loc: int) -> Series: """ diff --git a/pandas/tests/indexing/test_partial.py b/pandas/tests/indexing/test_partial.py index 350f86b4e9fd0..7afbbc2b9ab2b 100644 --- a/pandas/tests/indexing/test_partial.py +++ b/pandas/tests/indexing/test_partial.py @@ -660,3 +660,15 @@ def test_indexing_timeseries_regression(self): expected = Series(rng, index=rng) tm.assert_series_equal(result, expected) + + def test_index_name_empty(self): + # GH 31368 + df = pd.DataFrame({}, index=pd.RangeIndex(0, name="df_index")) + series = pd.Series(1.23, index=pd.RangeIndex(4, name="series_index")) + + df["series"] = series + expected = pd.DataFrame( + {"series": [1.23] * 4}, index=pd.RangeIndex(4, name="df_index") + ) + + tm.assert_frame_equal(df, expected)
- [x] closes #31368 - [x] tests added / passed `indexing/test_partial.py:TestPartialSetting:test_index_name_empty` - [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/36141
2020-09-05T14:58:57Z
2020-09-08T13:45:09Z
2020-09-08T13:45:09Z
2020-09-18T11:34:07Z
TYP: remove string literals for type annotations in pandas\core\frame.py
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index c48bec9b670ad..8ee782d7c8584 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -420,7 +420,7 @@ class DataFrame(NDFrame): _typ = "dataframe" @property - def _constructor(self) -> Type["DataFrame"]: + def _constructor(self) -> Type[DataFrame]: return DataFrame _constructor_sliced: Type[Series] = Series @@ -1233,7 +1233,7 @@ def __rmatmul__(self, other): # IO methods (to / from other formats) @classmethod - def from_dict(cls, data, orient="columns", dtype=None, columns=None) -> "DataFrame": + def from_dict(cls, data, orient="columns", dtype=None, columns=None) -> DataFrame: """ Construct DataFrame from dict of array-like or dicts. @@ -1671,7 +1671,7 @@ def from_records( columns=None, coerce_float=False, nrows=None, - ) -> "DataFrame": + ) -> DataFrame: """ Convert structured or record ndarray to DataFrame. @@ -2012,7 +2012,7 @@ def _from_arrays( index, dtype: Optional[Dtype] = None, verify_integrity: bool = True, - ) -> "DataFrame": + ) -> DataFrame: """ Create DataFrame from a list of arrays corresponding to the columns. @@ -2720,7 +2720,7 @@ def memory_usage(self, index=True, deep=False) -> Series: ).append(result) return result - def transpose(self, *args, copy: bool = False) -> "DataFrame": + def transpose(self, *args, copy: bool = False) -> DataFrame: """ Transpose index and columns. @@ -2843,7 +2843,7 @@ def transpose(self, *args, copy: bool = False) -> "DataFrame": return result.__finalize__(self, method="transpose") @property - def T(self) -> "DataFrame": + def T(self) -> DataFrame: return self.transpose() # ---------------------------------------------------------------------- @@ -3503,7 +3503,7 @@ def eval(self, expr, inplace=False, **kwargs): return _eval(expr, inplace=inplace, **kwargs) - def select_dtypes(self, include=None, exclude=None) -> "DataFrame": + def select_dtypes(self, include=None, exclude=None) -> DataFrame: """ Return a subset of the DataFrame's columns based on the column dtypes. @@ -3667,7 +3667,7 @@ def insert(self, loc, column, value, allow_duplicates=False) -> None: value = self._sanitize_column(column, value, broadcast=False) self._mgr.insert(loc, column, value, allow_duplicates=allow_duplicates) - def assign(self, **kwargs) -> "DataFrame": + def assign(self, **kwargs) -> DataFrame: r""" Assign new columns to a DataFrame. @@ -3965,7 +3965,7 @@ def _reindex_columns( allow_dups=False, ) - def _reindex_multi(self, axes, copy, fill_value) -> "DataFrame": + def _reindex_multi(self, axes, copy, fill_value) -> DataFrame: """ We are guaranteed non-Nones in the axes. """ @@ -3998,7 +3998,7 @@ def align( limit=None, fill_axis=0, broadcast_axis=None, - ) -> "DataFrame": + ) -> DataFrame: return super().align( other, join=join, @@ -4067,7 +4067,7 @@ def set_axis(self, labels, axis: Axis = 0, inplace: bool = False): ("tolerance", None), ], ) - def reindex(self, *args, **kwargs) -> "DataFrame": + def reindex(self, *args, **kwargs) -> DataFrame: axes = validate_axis_style_args(self, args, kwargs, "labels", "reindex") kwargs.update(axes) # Pop these, since the values are in `kwargs` under different names @@ -4229,7 +4229,7 @@ def rename( inplace: bool = False, level: Optional[Level] = None, errors: str = "ignore", - ) -> Optional["DataFrame"]: + ) -> Optional[DataFrame]: """ Alter axes labels. @@ -4357,7 +4357,7 @@ def fillna( inplace=False, limit=None, downcast=None, - ) -> Optional["DataFrame"]: + ) -> Optional[DataFrame]: return super().fillna( value=value, method=method, @@ -4465,7 +4465,7 @@ def _replace_columnwise( return res.__finalize__(self) @doc(NDFrame.shift, klass=_shared_doc_kwargs["klass"]) - def shift(self, periods=1, freq=None, axis=0, fill_value=None) -> "DataFrame": + def shift(self, periods=1, freq=None, axis=0, fill_value=None) -> DataFrame: return super().shift( periods=periods, freq=freq, axis=axis, fill_value=fill_value ) @@ -4666,7 +4666,7 @@ def reset_index( inplace: bool = False, col_level: Hashable = 0, col_fill: Label = "", - ) -> Optional["DataFrame"]: + ) -> Optional[DataFrame]: """ Reset the index, or a level of it. @@ -4910,20 +4910,20 @@ def _maybe_casted_values(index, labels=None): # Reindex-based selection methods @doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"]) - def isna(self) -> "DataFrame": + def isna(self) -> DataFrame: result = self._constructor(self._data.isna(func=isna)) return result.__finalize__(self, method="isna") @doc(NDFrame.isna, klass=_shared_doc_kwargs["klass"]) - def isnull(self) -> "DataFrame": + def isnull(self) -> DataFrame: return self.isna() @doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"]) - def notna(self) -> "DataFrame": + def notna(self) -> DataFrame: return ~self.isna() @doc(NDFrame.notna, klass=_shared_doc_kwargs["klass"]) - def notnull(self) -> "DataFrame": + def notnull(self) -> DataFrame: return ~self.isna() def dropna(self, axis=0, how="any", thresh=None, subset=None, inplace=False): @@ -5074,7 +5074,7 @@ def drop_duplicates( keep: Union[str, bool] = "first", inplace: bool = False, ignore_index: bool = False, - ) -> Optional["DataFrame"]: + ) -> Optional[DataFrame]: """ Return DataFrame with duplicate rows removed. @@ -5168,7 +5168,7 @@ def duplicated( self, subset: Optional[Union[Hashable, Sequence[Hashable]]] = None, keep: Union[str, bool] = "first", - ) -> "Series": + ) -> Series: """ Return boolean Series denoting duplicate rows. @@ -5619,7 +5619,7 @@ def value_counts( return counts - def nlargest(self, n, columns, keep="first") -> "DataFrame": + def nlargest(self, n, columns, keep="first") -> DataFrame: """ Return the first `n` rows ordered by `columns` in descending order. @@ -5728,7 +5728,7 @@ def nlargest(self, n, columns, keep="first") -> "DataFrame": """ return algorithms.SelectNFrame(self, n=n, keep=keep, columns=columns).nlargest() - def nsmallest(self, n, columns, keep="first") -> "DataFrame": + def nsmallest(self, n, columns, keep="first") -> DataFrame: """ Return the first `n` rows ordered by `columns` in ascending order. @@ -5830,7 +5830,7 @@ def nsmallest(self, n, columns, keep="first") -> "DataFrame": self, n=n, keep=keep, columns=columns ).nsmallest() - def swaplevel(self, i=-2, j=-1, axis=0) -> "DataFrame": + def swaplevel(self, i=-2, j=-1, axis=0) -> DataFrame: """ Swap levels i and j in a MultiIndex on a particular axis. @@ -5861,7 +5861,7 @@ def swaplevel(self, i=-2, j=-1, axis=0) -> "DataFrame": result.columns = result.columns.swaplevel(i, j) return result - def reorder_levels(self, order, axis=0) -> "DataFrame": + def reorder_levels(self, order, axis=0) -> DataFrame: """ Rearrange index levels using input order. May not drop or duplicate levels. @@ -5894,7 +5894,7 @@ def reorder_levels(self, order, axis=0) -> "DataFrame": # ---------------------------------------------------------------------- # Arithmetic / combination related - def _combine_frame(self, other: "DataFrame", func, fill_value=None): + def _combine_frame(self, other: DataFrame, func, fill_value=None): # at this point we have `self._indexed_same(other)` if fill_value is None: @@ -5914,7 +5914,7 @@ def _arith_op(left, right): new_data = ops.dispatch_to_series(self, other, _arith_op) return new_data - def _construct_result(self, result) -> "DataFrame": + def _construct_result(self, result) -> DataFrame: """ Wrap the result of an arithmetic, comparison, or logical operation. @@ -6031,11 +6031,11 @@ def _construct_result(self, result) -> "DataFrame": @Appender(_shared_docs["compare"] % _shared_doc_kwargs) def compare( self, - other: "DataFrame", + other: DataFrame, align_axis: Axis = 1, keep_shape: bool = False, keep_equal: bool = False, - ) -> "DataFrame": + ) -> DataFrame: return super().compare( other=other, align_axis=align_axis, @@ -6044,8 +6044,8 @@ def compare( ) def combine( - self, other: "DataFrame", func, fill_value=None, overwrite=True - ) -> "DataFrame": + self, other: DataFrame, func, fill_value=None, overwrite=True + ) -> DataFrame: """ Perform column-wise combine with another DataFrame. @@ -6212,7 +6212,7 @@ def combine( # convert_objects just in case return self._constructor(result, index=new_index, columns=new_columns) - def combine_first(self, other: "DataFrame") -> "DataFrame": + def combine_first(self, other: DataFrame) -> DataFrame: """ Update null elements with value in the same location in `other`. @@ -6718,7 +6718,7 @@ def groupby( @Substitution("") @Appender(_shared_docs["pivot"]) - def pivot(self, index=None, columns=None, values=None) -> "DataFrame": + def pivot(self, index=None, columns=None, values=None) -> DataFrame: from pandas.core.reshape.pivot import pivot return pivot(self, index=index, columns=columns, values=values) @@ -6870,7 +6870,7 @@ def pivot_table( dropna=True, margins_name="All", observed=False, - ) -> "DataFrame": + ) -> DataFrame: from pandas.core.reshape.pivot import pivot_table return pivot_table( @@ -7056,7 +7056,7 @@ def stack(self, level=-1, dropna=True): def explode( self, column: Union[str, Tuple], ignore_index: bool = False - ) -> "DataFrame": + ) -> DataFrame: """ Transform each element of a list-like to a row, replicating index values. @@ -7211,7 +7211,7 @@ def melt( value_name="value", col_level=None, ignore_index=True, - ) -> "DataFrame": + ) -> DataFrame: return melt( self, @@ -7299,7 +7299,7 @@ def melt( 1 255.0""" ), ) - def diff(self, periods: int = 1, axis: Axis = 0) -> "DataFrame": + def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame: bm_axis = self._get_block_manager_axis(axis) self._consolidate_inplace() @@ -7462,7 +7462,7 @@ def _aggregate(self, arg, axis=0, *args, **kwargs): klass=_shared_doc_kwargs["klass"], axis=_shared_doc_kwargs["axis"], ) - def transform(self, func, axis=0, *args, **kwargs) -> "DataFrame": + def transform(self, func, axis=0, *args, **kwargs) -> DataFrame: axis = self._get_axis_number(axis) if axis == 1: return self.T.transform(func, *args, **kwargs).T @@ -7616,7 +7616,7 @@ def apply(self, func, axis=0, raw=False, result_type=None, args=(), **kwds): ) return op.get_result() - def applymap(self, func) -> "DataFrame": + def applymap(self, func) -> DataFrame: """ Apply a function to a Dataframe elementwise. @@ -7678,7 +7678,7 @@ def infer(x): def append( self, other, ignore_index=False, verify_integrity=False, sort=False - ) -> "DataFrame": + ) -> DataFrame: """ Append rows of `other` to the end of caller, returning a new object. @@ -7818,7 +7818,7 @@ def append( def join( self, other, on=None, how="left", lsuffix="", rsuffix="", sort=False - ) -> "DataFrame": + ) -> DataFrame: """ Join columns of another DataFrame. @@ -8009,7 +8009,7 @@ def merge( copy=True, indicator=False, validate=None, - ) -> "DataFrame": + ) -> DataFrame: from pandas.core.reshape.merge import merge return merge( @@ -8028,7 +8028,7 @@ def merge( validate=validate, ) - def round(self, decimals=0, *args, **kwargs) -> "DataFrame": + def round(self, decimals=0, *args, **kwargs) -> DataFrame: """ Round a DataFrame to a variable number of decimal places. @@ -8142,7 +8142,7 @@ def _series_round(s, decimals): # ---------------------------------------------------------------------- # Statistical methods, etc. - def corr(self, method="pearson", min_periods=1) -> "DataFrame": + def corr(self, method="pearson", min_periods=1) -> DataFrame: """ Compute pairwise correlation of columns, excluding NA/null values. @@ -8233,7 +8233,7 @@ def corr(self, method="pearson", min_periods=1) -> "DataFrame": def cov( self, min_periods: Optional[int] = None, ddof: Optional[int] = 1 - ) -> "DataFrame": + ) -> DataFrame: """ Compute pairwise covariance of columns, excluding NA/null values. @@ -8636,7 +8636,7 @@ def func(values): else: return op(values, axis=axis, skipna=skipna, **kwds) - def _get_data(axis_matters: bool) -> "DataFrame": + def _get_data(axis_matters: bool) -> DataFrame: if filter_type is None: data = self._get_numeric_data() elif filter_type == "bool": @@ -8937,7 +8937,7 @@ def _get_agg_axis(self, axis_num: int) -> Index: else: raise ValueError(f"Axis must be 0 or 1 (got {repr(axis_num)})") - def mode(self, axis=0, numeric_only=False, dropna=True) -> "DataFrame": + def mode(self, axis=0, numeric_only=False, dropna=True) -> DataFrame: """ Get the mode(s) of each element along the selected axis. @@ -9122,7 +9122,7 @@ def quantile(self, q=0.5, axis=0, numeric_only=True, interpolation="linear"): def to_timestamp( self, freq=None, how: str = "start", axis: Axis = 0, copy: bool = True - ) -> "DataFrame": + ) -> DataFrame: """ Cast to DatetimeIndex of timestamps, at *beginning* of period. @@ -9151,7 +9151,7 @@ def to_timestamp( setattr(new_obj, axis_name, new_ax) return new_obj - def to_period(self, freq=None, axis: Axis = 0, copy: bool = True) -> "DataFrame": + def to_period(self, freq=None, axis: Axis = 0, copy: bool = True) -> DataFrame: """ Convert DataFrame from DatetimeIndex to PeriodIndex. @@ -9180,7 +9180,7 @@ def to_period(self, freq=None, axis: Axis = 0, copy: bool = True) -> "DataFrame" setattr(new_obj, axis_name, new_ax) return new_obj - def isin(self, values) -> "DataFrame": + def isin(self, values) -> DataFrame: """ Whether each element in the DataFrame is contained in values. @@ -9287,10 +9287,10 @@ def isin(self, values) -> "DataFrame": _info_axis_number = 1 _info_axis_name = "columns" - index: "Index" = properties.AxisProperty( + index: Index = properties.AxisProperty( axis=1, doc="The index (row labels) of the DataFrame." ) - columns: "Index" = properties.AxisProperty( + columns: Index = properties.AxisProperty( axis=0, doc="The column labels of the DataFrame." )
https://api.github.com/repos/pandas-dev/pandas/pulls/36140
2020-09-05T14:17:16Z
2020-09-05T15:03:54Z
2020-09-05T15:03:54Z
2020-09-05T15:09:24Z
Updated series documentation to close #35406
diff --git a/pandas/core/series.py b/pandas/core/series.py index 9d84ce4b9ab2e..d8fdaa2a60252 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -164,9 +164,9 @@ class Series(base.IndexOpsMixin, generic.NDFrame): index : array-like or Index (1d) Values must be hashable and have the same length as `data`. Non-unique index values are allowed. Will default to - RangeIndex (0, 1, 2, ..., n) if not provided. If both a dict and index - sequence are used, the index will override the keys found in the - dict. + RangeIndex (0, 1, 2, ..., n) if not provided. If data is dict-like + and index is None, then the values in the index are used to + reindex the Series after it is created using the keys in the data. dtype : str, numpy.dtype, or ExtensionDtype, optional Data type for the output Series. If not specified, this will be inferred from `data`.
- [x ] closes #35406 - [x ] tests added / passed - [ x] passes `black pandas` - [ x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Not sure how to do whatsnew entry for this - first contribution! Do let me know how to improve. Output of scripts/validate_docstring.py: ``` ################################################################################ ########################## Docstring (pandas.Series) ########################## ################################################################################ One-dimensional ndarray with axis labels (including time series). Labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Statistical methods from ndarray have been overridden to automatically exclude missing data (currently represented as NaN). Operations between Series (+, -, /, *, **) align values based on their associated index values-- they need not be the same length. The result index will be the sorted union of the two indexes. Parameters ---------- data : array-like, Iterable, dict, or scalar value Contains data stored in Series. .. versionchanged:: 0.23.0 If data is a dict, argument order is maintained for Python 3.6 and later. index : array-like or Index (1d) Values must be hashable and have the same length as `data`. Non-unique index values are allowed. Will default to RangeIndex (0, 1, 2, ..., n) if not provided. If data is dict-like and index is None, then the values in the index are used to reindex the Series after it is created using the keys in the data. dtype : str, numpy.dtype, or ExtensionDtype, optional Data type for the output Series. If not specified, this will be inferred from `data`. See the :ref:`user guide <basics.dtypes>` for more usages. name : str, optional The name to give to the Series. copy : bool, default False Copy input data. ################################################################################ ################################## Validation ################################## ################################################################################ 3 Errors found: Parameters {'fastpath'} not documented See Also section not found No examples section found ```
https://api.github.com/repos/pandas-dev/pandas/pulls/36139
2020-09-05T13:52:12Z
2020-09-05T14:44:27Z
2020-09-05T14:44:27Z
2020-09-13T15:28:37Z
TYP: Check for use of Union[Series, DataFrame] instead of FrameOrSeriesUnion alias
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 6006d09bc3e78..8ee579cd25203 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -230,6 +230,9 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then invgrep -R --include=*.{py,pyx} '!r}' pandas RET=$(($RET + $?)) ; echo $MSG "DONE" + # ------------------------------------------------------------------------- + # Type annotations + MSG='Check for use of comment-based annotation syntax' ; echo $MSG invgrep -R --include="*.py" -P '# type: (?!ignore)' pandas RET=$(($RET + $?)) ; echo $MSG "DONE" @@ -238,6 +241,11 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then invgrep -R --include="*.py" -P '# type:\s?ignore(?!\[)' pandas RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Check for use of Union[Series, DataFrame] instead of FrameOrSeriesUnion alias' ; echo $MSG + invgrep -R --include="*.py" --exclude=_typing.py -E 'Union\[.*(Series.*DataFrame|DataFrame.*Series).*\]' pandas + RET=$(($RET + $?)) ; echo $MSG "DONE" + + # ------------------------------------------------------------------------- MSG='Check for use of foo.__class__ instead of type(foo)' ; echo $MSG invgrep -R --include=*.{py,pyx} '\.__class__' pandas RET=$(($RET + $?)) ; echo $MSG "DONE" diff --git a/pandas/core/apply.py b/pandas/core/apply.py index 99a9e1377563c..bbf832f33065b 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -1,12 +1,12 @@ import abc import inspect -from typing import TYPE_CHECKING, Any, Dict, Iterator, Optional, Tuple, Type, Union +from typing import TYPE_CHECKING, Any, Dict, Iterator, Optional, Tuple, Type import numpy as np from pandas._config import option_context -from pandas._typing import Axis +from pandas._typing import Axis, FrameOrSeriesUnion from pandas.util._decorators import cache_readonly from pandas.core.dtypes.common import is_dict_like, is_list_like, is_sequence @@ -73,7 +73,7 @@ def series_generator(self) -> Iterator["Series"]: @abc.abstractmethod def wrap_results_for_axis( self, results: ResType, res_index: "Index" - ) -> Union["Series", "DataFrame"]: + ) -> FrameOrSeriesUnion: pass # --------------------------------------------------------------- @@ -289,9 +289,7 @@ def apply_series_generator(self) -> Tuple[ResType, "Index"]: return results, res_index - def wrap_results( - self, results: ResType, res_index: "Index" - ) -> Union["Series", "DataFrame"]: + def wrap_results(self, results: ResType, res_index: "Index") -> FrameOrSeriesUnion: from pandas import Series # see if we can infer the results @@ -335,7 +333,7 @@ def result_columns(self) -> "Index": def wrap_results_for_axis( self, results: ResType, res_index: "Index" - ) -> Union["Series", "DataFrame"]: + ) -> FrameOrSeriesUnion: """ return the results for the rows """ if self.result_type == "reduce": @@ -408,9 +406,9 @@ def result_columns(self) -> "Index": def wrap_results_for_axis( self, results: ResType, res_index: "Index" - ) -> Union["Series", "DataFrame"]: + ) -> FrameOrSeriesUnion: """ return the results for the columns """ - result: Union["Series", "DataFrame"] + result: FrameOrSeriesUnion # we have requested to expand if self.result_type == "expand": diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index b855ce65f41b2..260e21b1f2593 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -308,7 +308,7 @@ def _aggregate_multiple_funcs(self, arg): arg = zip(columns, arg) - results: Dict[base.OutputKey, Union[Series, DataFrame]] = {} + results: Dict[base.OutputKey, FrameOrSeriesUnion] = {} for idx, (name, func) in enumerate(arg): obj = self @@ -332,7 +332,7 @@ def _wrap_series_output( self, output: Mapping[base.OutputKey, Union[Series, np.ndarray]], index: Optional[Index], - ) -> Union[Series, DataFrame]: + ) -> FrameOrSeriesUnion: """ Wraps the output of a SeriesGroupBy operation into the expected result. @@ -355,7 +355,7 @@ def _wrap_series_output( indexed_output = {key.position: val for key, val in output.items()} columns = Index(key.label for key in output) - result: Union[Series, DataFrame] + result: FrameOrSeriesUnion if len(output) > 1: result = self.obj._constructor_expanddim(indexed_output, index=index) result.columns = columns @@ -373,7 +373,7 @@ def _wrap_aggregated_output( self, output: Mapping[base.OutputKey, Union[Series, np.ndarray]], index: Optional[Index], - ) -> Union[Series, DataFrame]: + ) -> FrameOrSeriesUnion: """ Wraps the output of a SeriesGroupBy aggregation into the expected result. @@ -1085,7 +1085,7 @@ def blk_func(bvalues: ArrayLike) -> ArrayLike: raise # We get here with a) EADtypes and b) object dtype - obj: Union[Series, DataFrame] + obj: FrameOrSeriesUnion # call our grouper again with only this block if isinstance(bvalues, ExtensionArray): # TODO(EA2D): special case not needed with 2D EAs diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 6678edc3821c8..59ea7781025c4 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -393,7 +393,7 @@ class Grouping: ---------- index : Index grouper : - obj Union[DataFrame, Series]: + obj : DataFrame or Series name : Label level : observed : bool, default False diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 602ff226f8878..f1c5486222ea1 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -6,14 +6,14 @@ import datetime from functools import partial import string -from typing import TYPE_CHECKING, Optional, Tuple, Union +from typing import TYPE_CHECKING, Optional, Tuple import warnings import numpy as np from pandas._libs import Timedelta, hashtable as libhashtable, lib import pandas._libs.join as libjoin -from pandas._typing import ArrayLike, FrameOrSeries +from pandas._typing import ArrayLike, FrameOrSeries, FrameOrSeriesUnion from pandas.errors import MergeError from pandas.util._decorators import Appender, Substitution @@ -51,7 +51,7 @@ from pandas.core.sorting import is_int64_overflow_possible if TYPE_CHECKING: - from pandas import DataFrame, Series # noqa:F401 + from pandas import DataFrame # noqa:F401 @Substitution("\nleft : DataFrame") @@ -575,8 +575,8 @@ class _MergeOperation: def __init__( self, - left: Union["Series", "DataFrame"], - right: Union["Series", "DataFrame"], + left: FrameOrSeriesUnion, + right: FrameOrSeriesUnion, how: str = "inner", on=None, left_on=None, diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 969ac56e41860..842a42f80e1b7 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -12,7 +12,7 @@ import numpy as np -from pandas._typing import Label +from pandas._typing import FrameOrSeriesUnion, Label from pandas.util._decorators import Appender, Substitution from pandas.core.dtypes.cast import maybe_downcast_to_dtype @@ -200,7 +200,7 @@ def pivot_table( def _add_margins( - table: Union["Series", "DataFrame"], + table: FrameOrSeriesUnion, data, values, rows, diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 0913627324c48..e850a101a0a63 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -16,7 +16,7 @@ from pandas._libs import lib, writers as libwriters from pandas._libs.tslibs import timezones -from pandas._typing import ArrayLike, FrameOrSeries, Label +from pandas._typing import ArrayLike, FrameOrSeries, FrameOrSeriesUnion, Label from pandas.compat._optional import import_optional_dependency from pandas.compat.pickle_compat import patch_pickle from pandas.errors import PerformanceWarning @@ -2566,7 +2566,7 @@ class Fixed: pandas_kind: str format_type: str = "fixed" # GH#30962 needed by dask - obj_type: Type[Union[DataFrame, Series]] + obj_type: Type[FrameOrSeriesUnion] ndim: int encoding: str parent: HDFStore @@ -4442,7 +4442,7 @@ class AppendableFrameTable(AppendableTable): pandas_kind = "frame_table" table_type = "appendable_frame" ndim = 2 - obj_type: Type[Union[DataFrame, Series]] = DataFrame + obj_type: Type[FrameOrSeriesUnion] = DataFrame @property def is_transposed(self) -> bool:
https://api.github.com/repos/pandas-dev/pandas/pulls/36137
2020-09-05T12:11:57Z
2020-09-05T14:55:12Z
2020-09-05T14:55:12Z
2020-09-05T15:10:22Z
Backport PR #36114 on branch 1.1.x (REGR: fix consolidation/cache issue with take operation)
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index 39850905f60fa..d1a66256454ca 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -17,6 +17,7 @@ Fixed regressions - Regression in :meth:`DatetimeIndex.intersection` incorrectly raising ``AssertionError`` when intersecting against a list (:issue:`35876`) - Fix regression in updating a column inplace (e.g. using ``df['col'].fillna(.., inplace=True)``) (:issue:`35731`) - Performance regression for :meth:`RangeIndex.format` (:issue:`35712`) +- Fix regression in invalid cache after an indexing operation; this can manifest when setting which does not update the data (:issue:`35521`) - Regression in :meth:`DataFrame.replace` where a ``TypeError`` would be raised when attempting to replace elements of type :class:`Interval` (:issue:`35931`) - Fix regression in pickle roundtrip of the ``closed`` attribute of :class:`IntervalIndex` (:issue:`35658`) - Fixed regression in :meth:`DataFrameGroupBy.agg` where a ``ValueError: buffer source array is read-only`` would be raised when the underlying array is read-only (:issue:`36014`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 67e5759b39808..935bad2624637 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3342,6 +3342,8 @@ class max_speed nv.validate_take(tuple(), kwargs) + self._consolidate_inplace() + new_data = self._mgr.take( indices, axis=self._get_block_manager_axis(axis), verify=True ) diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index b8183eb9f4185..217409d56c3ab 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -640,3 +640,26 @@ def test_update_inplace_sets_valid_block_values(): # smoketest for OP bug from GH#35731 assert df.isnull().sum().sum() == 0 + + +def test_nonconsolidated_item_cache_take(): + # https://github.com/pandas-dev/pandas/issues/35521 + + # create non-consolidated dataframe with object dtype columns + df = pd.DataFrame() + df["col1"] = pd.Series(["a"], dtype=object) + df["col2"] = pd.Series([0], dtype=object) + + # access column (item cache) + df["col1"] == "A" + # take operation + # (regression was that this consolidated but didn't reset item cache, + # resulting in an invalid cache and the .at operation not working properly) + df[df["col2"] == 0] + + # now setting value should update actual dataframe + df.at[0, "col1"] = "A" + + expected = pd.DataFrame({"col1": ["A"], "col2": [0]}, dtype=object) + tm.assert_frame_equal(df, expected) + assert df.at[0, "col1"] == "A"
Backport PR #36114: REGR: fix consolidation/cache issue with take operation
https://api.github.com/repos/pandas-dev/pandas/pulls/36135
2020-09-05T06:05:41Z
2020-09-05T07:56:14Z
2020-09-05T07:56:14Z
2020-09-05T07:56:14Z
BUG: shows correct package name when import_optional_dependency is ca…
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index b8f6d0e52d058..e3aa7194f04ab 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -39,6 +39,7 @@ Bug fixes - Bug in :meth:`Series.dt.isocalendar` and :meth:`DatetimeIndex.isocalendar` that returned incorrect year for certain dates (:issue:`36032`) - Bug in :class:`DataFrame` indexing returning an incorrect :class:`Series` in some cases when the series has been altered and a cache not invalidated (:issue:`33675`) - Bug in :meth:`DataFrame.corr` causing subsequent indexing lookups to be incorrect (:issue:`35882`) +- Bug in :meth:`import_optional_dependency` returning incorrect package names in cases where package name is different from import name (:issue:`35948`) .. --------------------------------------------------------------------------- diff --git a/pandas/compat/_optional.py b/pandas/compat/_optional.py index 689c7c889ef66..40688a3978cfc 100644 --- a/pandas/compat/_optional.py +++ b/pandas/compat/_optional.py @@ -33,6 +33,19 @@ "numba": "0.46.0", } +# A mapping from import name to package name (on PyPI) for packages where +# these two names are different. + +INSTALL_MAPPING = { + "bs4": "beautifulsoup4", + "bottleneck": "Bottleneck", + "lxml.etree": "lxml", + "odf": "odfpy", + "pandas_gbq": "pandas-gbq", + "sqlalchemy": "SQLAlchemy", + "jinja2": "Jinja2", +} + def _get_version(module: types.ModuleType) -> str: version = getattr(module, "__version__", None) @@ -82,9 +95,13 @@ def import_optional_dependency( is False, or when the package's version is too old and `on_version` is ``'warn'``. """ + + package_name = INSTALL_MAPPING.get(name) + install_name = package_name if package_name is not None else name + msg = ( - f"Missing optional dependency '{name}'. {extra} " - f"Use pip or conda to install {name}." + f"Missing optional dependency '{install_name}'. {extra} " + f"Use pip or conda to install {install_name}." ) try: module = importlib.import_module(name)
…lled. fixes #35948 - [x] closes #35948 - [x] tests added / passed - [x] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/36134
2020-09-05T04:19:41Z
2020-09-07T11:16:12Z
2020-09-07T11:16:12Z
2020-09-07T19:30:44Z
BUG: Timestamp == date match stdlib
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index d8bd2efcf17b1..d33686190e0b5 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -156,6 +156,7 @@ Deprecations - Deprecated allowing subclass-specific keyword arguments in the :class:`Index` constructor, use the specific subclass directly instead (:issue:`14093`,:issue:`21311`,:issue:`22315`,:issue:`26974`) - Deprecated ``astype`` of datetimelike (``timedelta64[ns]``, ``datetime64[ns]``, ``Datetime64TZDtype``, ``PeriodDtype``) to integer dtypes, use ``values.view(...)`` instead (:issue:`38544`) - Deprecated keyword ``try_cast`` in :meth:`Series.where`, :meth:`Series.mask`, :meth:`DataFrame.where`, :meth:`DataFrame.mask`; cast results manually if desired (:issue:`38836`) +- Deprecated comparison of :class:`Timestamp` object with ``datetime.date`` objects. Instead of e.g. ``ts <= mydate`` use ``ts <= pd.Timestamp(mydate)`` or ``ts.date() <= mydate`` (:issue:`36131`) - .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 242eb89d1e723..df4677a242758 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -16,6 +16,7 @@ from numpy cimport int8_t, int64_t, ndarray, uint8_t cnp.import_array() from cpython.datetime cimport ( # alias bc `tzinfo` is a kwarg below + PyDate_Check, PyDateTime_Check, PyDateTime_IMPORT, PyDelta_Check, @@ -281,6 +282,20 @@ cdef class _Timestamp(ABCTimestamp): return np.zeros(other.shape, dtype=np.bool_) return NotImplemented + elif PyDate_Check(other): + # returning NotImplemented defers to the `date` implementation + # which incorrectly drops tz and normalizes to midnight + # before comparing + # We follow the stdlib datetime behavior of never being equal + warnings.warn( + "Comparison of Timestamp with datetime.date is deprecated in " + "order to match the standard library behavior. " + "In a future version these will be considered non-comparable." + "Use 'ts == pd.Timestamp(date)' or 'ts.date() == date' instead.", + FutureWarning, + stacklevel=1, + ) + return NotImplemented else: return NotImplemented diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 49eb570c4ffe0..4cbdf61ff8dae 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1429,7 +1429,10 @@ def test_loc_setitem_datetime_coercion(self): assert Timestamp("2008-08-08") == df.loc[0, "c"] assert Timestamp("2008-08-08") == df.loc[1, "c"] df.loc[2, "c"] = date(2005, 5, 5) - assert Timestamp("2005-05-05") == df.loc[2, "c"] + with tm.assert_produces_warning(FutureWarning): + # Comparing Timestamp to date obj is deprecated + assert Timestamp("2005-05-05") == df.loc[2, "c"] + assert Timestamp("2005-05-05").date() == df.loc[2, "c"] def test_loc_setitem_datetimelike_with_inference(self): # GH 7592 diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index 232ebc608e465..385390e9d7b98 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -613,8 +613,13 @@ def test_get_indexer_mixed_dtypes(self, target): ([date(9999, 1, 1), date(9999, 1, 1)], [-1, -1]), ], ) + # FIXME: these warnings are flaky GH#36131 + @pytest.mark.filterwarnings( + "ignore:Comparison of Timestamp with datetime.date:FutureWarning" + ) def test_get_indexer_out_of_bounds_date(self, target, positions): values = DatetimeIndex([Timestamp("2020-01-01"), Timestamp("2020-01-02")]) + result = values.get_indexer(target) expected = np.array(positions, dtype=np.intp) tm.assert_numpy_array_equal(result, expected) diff --git a/pandas/tests/scalar/timestamp/test_comparisons.py b/pandas/tests/scalar/timestamp/test_comparisons.py index 3d1f71def5836..285733dc2c7af 100644 --- a/pandas/tests/scalar/timestamp/test_comparisons.py +++ b/pandas/tests/scalar/timestamp/test_comparisons.py @@ -142,6 +142,42 @@ def test_compare_invalid(self): assert val != np.float64(1) assert val != np.int64(1) + @pytest.mark.parametrize("tz", [None, "US/Pacific"]) + def test_compare_date(self, tz): + # GH#36131 comparing Timestamp with date object is deprecated + ts = Timestamp.now(tz) + dt = ts.to_pydatetime().date() + # These are incorrectly considered as equal because they + # dispatch to the date comparisons which truncates ts + + for left, right in [(ts, dt), (dt, ts)]: + with tm.assert_produces_warning(FutureWarning): + assert left == right + with tm.assert_produces_warning(FutureWarning): + assert not left != right + with tm.assert_produces_warning(FutureWarning): + assert not left < right + with tm.assert_produces_warning(FutureWarning): + assert left <= right + with tm.assert_produces_warning(FutureWarning): + assert not left > right + with tm.assert_produces_warning(FutureWarning): + assert left >= right + + # Once the deprecation is enforced, the following assertions + # can be enabled: + # assert not left == right + # assert left != right + # + # with pytest.raises(TypeError): + # left < right + # with pytest.raises(TypeError): + # left <= right + # with pytest.raises(TypeError): + # left > right + # with pytest.raises(TypeError): + # left >= right + def test_cant_compare_tz_naive_w_aware(self, utc_fixture): # see GH#1404 a = Timestamp("3/12/2012")
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry ATM we have one reasonable behavior `Timestamp("2020-09-04") == date(2020, 9, 4)` and two un-reasonable behaviors: ``Timestamp("2020-09-04").tz_localize("US/Pacific") == date(2020, 9, 4)`, `Timestamp.now() == Timestamp.now().date()`. Since the stdlib datetime doesnt consider `datetime(2020, 9, 4) == date(2020, 9, 4)`, this follows the stdlib and considers them never equal. <s>I'm still getting one test failure locally.</s> cc @mroeschke
https://api.github.com/repos/pandas-dev/pandas/pulls/36131
2020-09-04T22:08:55Z
2021-01-01T20:40:19Z
2021-01-01T20:40:19Z
2021-01-01T21:09:12Z
CLN: De-privatize
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 8dc500dddeafa..e321fdd9b3a9b 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -395,7 +395,7 @@ def _hash_categories(categories, ordered: Ordered = True) -> int: from pandas.core.dtypes.common import DT64NS_DTYPE, is_datetime64tz_dtype from pandas.core.util.hashing import ( - _combine_hash_arrays, + combine_hash_arrays, hash_array, hash_tuples, ) @@ -427,7 +427,7 @@ def _hash_categories(categories, ordered: Ordered = True) -> int: ) else: cat_array = [cat_array] - hashed = _combine_hash_arrays(iter(cat_array), num_items=len(cat_array)) + hashed = combine_hash_arrays(iter(cat_array), num_items=len(cat_array)) return np.bitwise_xor.reduce(hashed) @classmethod diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 6dcb9250812d0..3fd93a8159041 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -354,9 +354,9 @@ def _mpl_repr(self): @property def _formatter_func(self): - from pandas.io.formats.format import _get_format_datetime64 + from pandas.io.formats.format import get_format_datetime64 - formatter = _get_format_datetime64(is_dates_only=self._is_dates_only) + formatter = get_format_datetime64(is_dates_only=self._is_dates_only) return lambda x: f"'{formatter(x, tz=self.tz)}'" # -------------------------------------------------------------------- diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index cfb17b9498a36..fe2fec1c52063 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -2291,7 +2291,7 @@ def need_slice(obj) -> bool: ) -def _non_reducing_slice(slice_): +def non_reducing_slice(slice_): """ Ensure that a slice doesn't reduce to a Series or Scalar. @@ -2330,7 +2330,7 @@ def pred(part) -> bool: return tuple(slice_) -def _maybe_numeric_slice(df, slice_, include_bool=False): +def maybe_numeric_slice(df, slice_, include_bool: bool = False): """ Want nice defaults for background_gradient that don't break with non-numeric data. But if slice_ is passed go with that. diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py index d79b9f4092325..df082c7285ae8 100644 --- a/pandas/core/util/hashing.py +++ b/pandas/core/util/hashing.py @@ -24,7 +24,7 @@ _default_hash_key = "0123456789123456" -def _combine_hash_arrays(arrays, num_items: int): +def combine_hash_arrays(arrays, num_items: int): """ Parameters ---------- @@ -108,7 +108,7 @@ def hash_pandas_object( for _ in [None] ) arrays = itertools.chain([h], index_iter) - h = _combine_hash_arrays(arrays, 2) + h = combine_hash_arrays(arrays, 2) h = Series(h, index=obj.index, dtype="uint64", copy=False) @@ -131,7 +131,7 @@ def hash_pandas_object( # keep `hashes` specifically a generator to keep mypy happy _hashes = itertools.chain(hashes, index_hash_generator) hashes = (x for x in _hashes) - h = _combine_hash_arrays(hashes, num_items) + h = combine_hash_arrays(hashes, num_items) h = Series(h, index=obj.index, dtype="uint64", copy=False) else: @@ -175,7 +175,7 @@ def hash_tuples(vals, encoding="utf8", hash_key: str = _default_hash_key): hashes = ( _hash_categorical(cat, encoding=encoding, hash_key=hash_key) for cat in vals ) - h = _combine_hash_arrays(hashes, len(vals)) + h = combine_hash_arrays(hashes, len(vals)) if is_tuple: h = h[0] diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 3d441f6e737bc..3dc4290953360 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1624,7 +1624,7 @@ def _format_datetime64_dateonly( return x._date_repr -def _get_format_datetime64( +def get_format_datetime64( is_dates_only: bool, nat_rep: str = "NaT", date_format: None = None ) -> Callable: @@ -1656,7 +1656,7 @@ def _format_strings(self) -> List[str]: """ we by definition have a TZ """ values = self.values.astype(object) is_dates_only = _is_dates_only(values) - formatter = self.formatter or _get_format_datetime64( + formatter = self.formatter or get_format_datetime64( is_dates_only, date_format=self.date_format ) fmt_values = [formatter(x) for x in values] diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 3bbb5271bce61..023557dd6494d 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -36,7 +36,7 @@ import pandas.core.common as com from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame -from pandas.core.indexing import _maybe_numeric_slice, _non_reducing_slice +from pandas.core.indexing import maybe_numeric_slice, non_reducing_slice jinja2 = import_optional_dependency("jinja2", extra="DataFrame.style requires jinja2.") @@ -475,7 +475,7 @@ def format(self, formatter, subset=None, na_rep: Optional[str] = None) -> "Style row_locs = range(len(self.data)) col_locs = range(len(self.data.columns)) else: - subset = _non_reducing_slice(subset) + subset = non_reducing_slice(subset) if len(subset) == 1: subset = subset, self.data.columns @@ -633,7 +633,7 @@ def _apply( **kwargs, ) -> "Styler": subset = slice(None) if subset is None else subset - subset = _non_reducing_slice(subset) + subset = non_reducing_slice(subset) data = self.data.loc[subset] if axis is not None: result = data.apply(func, axis=axis, result_type="expand", **kwargs) @@ -725,7 +725,7 @@ def _applymap(self, func: Callable, subset=None, **kwargs) -> "Styler": func = partial(func, **kwargs) # applymap doesn't take kwargs? if subset is None: subset = pd.IndexSlice[:] - subset = _non_reducing_slice(subset) + subset = non_reducing_slice(subset) result = self.data.loc[subset].applymap(func) self._update_ctx(result) return self @@ -985,7 +985,7 @@ def hide_columns(self, subset) -> "Styler": ------- self : Styler """ - subset = _non_reducing_slice(subset) + subset = non_reducing_slice(subset) hidden_df = self.data.loc[subset] self.hidden_columns = self.columns.get_indexer_for(hidden_df.columns) return self @@ -1087,8 +1087,8 @@ def background_gradient( of the data is extended by ``low * (x.max() - x.min())`` and ``high * (x.max() - x.min())`` before normalizing. """ - subset = _maybe_numeric_slice(self.data, subset) - subset = _non_reducing_slice(subset) + subset = maybe_numeric_slice(self.data, subset) + subset = non_reducing_slice(subset) self.apply( self._background_gradient, cmap=cmap, @@ -1322,8 +1322,8 @@ def bar( "(eg: color=['#d65f5f', '#5fba7d'])" ) - subset = _maybe_numeric_slice(self.data, subset) - subset = _non_reducing_slice(subset) + subset = maybe_numeric_slice(self.data, subset) + subset = non_reducing_slice(subset) self.apply( self._bar, subset=subset, @@ -1390,7 +1390,7 @@ def _highlight_handler( axis: Optional[Axis] = None, max_: bool = True, ) -> "Styler": - subset = _non_reducing_slice(_maybe_numeric_slice(self.data, subset)) + subset = non_reducing_slice(maybe_numeric_slice(self.data, subset)) self.apply( self._highlight_extrema, color=color, axis=axis, subset=subset, max_=max_ ) diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 147e4efd74bc3..c1ba7881165f1 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -33,6 +33,13 @@ from pandas.plotting._matplotlib.compat import _mpl_ge_3_0_0 from pandas.plotting._matplotlib.converter import register_pandas_matplotlib_converters from pandas.plotting._matplotlib.style import get_standard_colors +from pandas.plotting._matplotlib.timeseries import ( + decorate_axes, + format_dateaxis, + maybe_convert_index, + maybe_resample, + use_dynamic_x, +) from pandas.plotting._matplotlib.tools import ( create_subplots, flatten_axes, @@ -1074,15 +1081,11 @@ def _is_ts_plot(self) -> bool: return not self.x_compat and self.use_index and self._use_dynamic_x() def _use_dynamic_x(self): - from pandas.plotting._matplotlib.timeseries import _use_dynamic_x - - return _use_dynamic_x(self._get_ax(0), self.data) + return use_dynamic_x(self._get_ax(0), self.data) def _make_plot(self): if self._is_ts_plot(): - from pandas.plotting._matplotlib.timeseries import _maybe_convert_index - - data = _maybe_convert_index(self._get_ax(0), self.data) + data = maybe_convert_index(self._get_ax(0), self.data) x = data.index # dummy, not used plotf = self._ts_plot @@ -1142,24 +1145,18 @@ def _plot( @classmethod def _ts_plot(cls, ax: "Axes", x, data, style=None, **kwds): - from pandas.plotting._matplotlib.timeseries import ( - _decorate_axes, - _maybe_resample, - format_dateaxis, - ) - # accept x to be consistent with normal plot func, # x is not passed to tsplot as it uses data.index as x coordinate # column_num must be in kwds for stacking purpose - freq, data = _maybe_resample(data, ax, kwds) + freq, data = maybe_resample(data, ax, kwds) # Set ax with freq info - _decorate_axes(ax, freq, kwds) + decorate_axes(ax, freq, kwds) # digging deeper if hasattr(ax, "left_ax"): - _decorate_axes(ax.left_ax, freq, kwds) + decorate_axes(ax.left_ax, freq, kwds) if hasattr(ax, "right_ax"): - _decorate_axes(ax.right_ax, freq, kwds) + decorate_axes(ax.right_ax, freq, kwds) ax._plot_data.append((data, cls._kind, kwds)) lines = cls._plot(ax, data.index, data.values, style=style, **kwds) diff --git a/pandas/plotting/_matplotlib/timeseries.py b/pandas/plotting/_matplotlib/timeseries.py index fd89a093d25a4..f8faac6a6a026 100644 --- a/pandas/plotting/_matplotlib/timeseries.py +++ b/pandas/plotting/_matplotlib/timeseries.py @@ -32,7 +32,7 @@ # Plotting functions and monkey patches -def _maybe_resample(series: "Series", ax: "Axes", kwargs): +def maybe_resample(series: "Series", ax: "Axes", kwargs): # resample against axes freq if necessary freq, ax_freq = _get_freq(ax, series) @@ -105,7 +105,7 @@ def _replot_ax(ax: "Axes", freq, kwargs): ax._plot_data = [] ax.clear() - _decorate_axes(ax, freq, kwargs) + decorate_axes(ax, freq, kwargs) lines = [] labels = [] @@ -128,7 +128,7 @@ def _replot_ax(ax: "Axes", freq, kwargs): return lines, labels -def _decorate_axes(ax: "Axes", freq, kwargs): +def decorate_axes(ax: "Axes", freq, kwargs): """Initialize axes for time-series plotting""" if not hasattr(ax, "_plot_data"): ax._plot_data = [] @@ -193,7 +193,7 @@ def _get_freq(ax: "Axes", series: "Series"): return freq, ax_freq -def _use_dynamic_x(ax: "Axes", data: FrameOrSeriesUnion) -> bool: +def use_dynamic_x(ax: "Axes", data: FrameOrSeriesUnion) -> bool: freq = _get_index_freq(data.index) ax_freq = _get_ax_freq(ax) @@ -235,7 +235,7 @@ def _get_index_freq(index: "Index") -> Optional[BaseOffset]: return freq -def _maybe_convert_index(ax: "Axes", data): +def maybe_convert_index(ax: "Axes", data): # tsplot converts automatically, but don't want to convert index # over and over for DataFrames if isinstance(data.index, (ABCDatetimeIndex, ABCPeriodIndex)): diff --git a/pandas/tests/indexing/multiindex/test_slice.py b/pandas/tests/indexing/multiindex/test_slice.py index 532bb4f2e6dac..ec0391a2ccc26 100644 --- a/pandas/tests/indexing/multiindex/test_slice.py +++ b/pandas/tests/indexing/multiindex/test_slice.py @@ -6,7 +6,7 @@ import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series, Timestamp import pandas._testing as tm -from pandas.core.indexing import _non_reducing_slice +from pandas.core.indexing import non_reducing_slice from pandas.tests.indexing.common import _mklbl @@ -739,7 +739,7 @@ def test_non_reducing_slice_on_multiindex(self): df = pd.DataFrame(dic, index=[0, 1]) idx = pd.IndexSlice slice_ = idx[:, idx["b", "d"]] - tslice_ = _non_reducing_slice(slice_) + tslice_ = non_reducing_slice(slice_) result = df.loc[tslice_] expected = pd.DataFrame({("b", "d"): [4, 1]}) diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 5b7f013d5de31..a080c5d169215 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -12,7 +12,7 @@ import pandas as pd from pandas import DataFrame, Index, NaT, Series import pandas._testing as tm -from pandas.core.indexing import _maybe_numeric_slice, _non_reducing_slice +from pandas.core.indexing import maybe_numeric_slice, non_reducing_slice from pandas.tests.indexing.common import _mklbl # ------------------------------------------------------------------------ @@ -822,7 +822,7 @@ def test_range_in_series_indexing(self, size): def test_non_reducing_slice(self, slc): df = DataFrame([[0, 1], [2, 3]]) - tslice_ = _non_reducing_slice(slc) + tslice_ = non_reducing_slice(slc) assert isinstance(df.loc[tslice_], DataFrame) def test_list_slice(self): @@ -831,18 +831,18 @@ def test_list_slice(self): df = DataFrame({"A": [1, 2], "B": [3, 4]}, index=["A", "B"]) expected = pd.IndexSlice[:, ["A"]] for subset in slices: - result = _non_reducing_slice(subset) + result = non_reducing_slice(subset) tm.assert_frame_equal(df.loc[result], df.loc[expected]) def test_maybe_numeric_slice(self): df = DataFrame({"A": [1, 2], "B": ["c", "d"], "C": [True, False]}) - result = _maybe_numeric_slice(df, slice_=None) + result = maybe_numeric_slice(df, slice_=None) expected = pd.IndexSlice[:, ["A"]] assert result == expected - result = _maybe_numeric_slice(df, None, include_bool=True) + result = maybe_numeric_slice(df, None, include_bool=True) expected = pd.IndexSlice[:, ["A", "C"]] - result = _maybe_numeric_slice(df, [1]) + result = maybe_numeric_slice(df, [1]) expected = [1] assert result == expected
https://api.github.com/repos/pandas-dev/pandas/pulls/36130
2020-09-04T21:47:24Z
2020-09-05T02:51:04Z
2020-09-05T02:51:04Z
2020-09-05T14:10:44Z
CLN: remove unused args/kwargs
diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 53edd056a6802..173ff99912f05 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1084,6 +1084,7 @@ def blk_func(bvalues: ArrayLike) -> ArrayLike: assert how == "ohlc" raise + # We get here with a) EADtypes and b) object dtype obj: Union[Series, DataFrame] # call our grouper again with only this block if isinstance(bvalues, ExtensionArray): diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 651af2d314251..6ef2e67030881 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1012,6 +1012,8 @@ def _agg_general( # raised in _get_cython_function, in some cases can # be trimmed by implementing cython funcs for more dtypes pass + else: + raise # apply a non-cython aggregation result = self.aggregate(lambda x: npfunc(x, axis=self.axis)) diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index c076b6e2e181b..e9525f03368fa 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -601,7 +601,7 @@ def _transform( return result - def agg_series(self, obj: Series, func: F, *args, **kwargs): + def agg_series(self, obj: Series, func: F): # Caller is responsible for checking ngroups != 0 assert self.ngroups != 0 @@ -649,7 +649,7 @@ def _aggregate_series_fast(self, obj: Series, func: F): result, counts = grouper.get_result() return result, counts - def _aggregate_series_pure_python(self, obj: Series, func: F, *args, **kwargs): + def _aggregate_series_pure_python(self, obj: Series, func: F): group_index, _, ngroups = self.group_info counts = np.zeros(ngroups, dtype=int) @@ -658,7 +658,7 @@ def _aggregate_series_pure_python(self, obj: Series, func: F, *args, **kwargs): splitter = get_splitter(obj, group_index, ngroups, axis=0) for label, group in splitter: - res = func(group, *args, **kwargs) + res = func(group) if result is None: if isinstance(res, (Series, Index, np.ndarray)): @@ -835,7 +835,7 @@ def groupings(self) -> "List[grouper.Grouping]": for lvl, name in zip(self.levels, self.names) ] - def agg_series(self, obj: Series, func: F, *args, **kwargs): + def agg_series(self, obj: Series, func: F): # Caller is responsible for checking ngroups != 0 assert self.ngroups != 0 assert len(self.bins) > 0 # otherwise we'd get IndexError in get_result
https://api.github.com/repos/pandas-dev/pandas/pulls/36129
2020-09-04T21:02:11Z
2020-09-05T03:11:40Z
2020-09-05T03:11:40Z
2020-09-05T14:08:13Z
CLN: remove xfails/skips for no-longer-supported numpys
diff --git a/pandas/plotting/_matplotlib/style.py b/pandas/plotting/_matplotlib/style.py index 904a760a03e58..3e0954ef3d74d 100644 --- a/pandas/plotting/_matplotlib/style.py +++ b/pandas/plotting/_matplotlib/style.py @@ -11,7 +11,7 @@ def get_standard_colors( - num_colors=None, colormap=None, color_type: str = "default", color=None + num_colors: int, colormap=None, color_type: str = "default", color=None ): import matplotlib.pyplot as plt diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index 04215bfe1bedb..ece9367cea7fe 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -194,8 +194,7 @@ def test_constructor_inferred_fill_value(self, data, fill_value): @pytest.mark.parametrize("format", ["coo", "csc", "csr"]) @pytest.mark.parametrize( - "size", - [pytest.param(0, marks=td.skip_if_np_lt("1.16", reason="NumPy-11383")), 10], + "size", [0, 10], ) @td.skip_if_no_scipy def test_from_spmatrix(self, size, format): @@ -904,7 +903,6 @@ def test_all(self, data, pos, neg): ([1.0, 2.0, 1.0], 1.0, 0.0), ], ) - @td.skip_if_np_lt("1.15") # prior didn't dispatch def test_numpy_all(self, data, pos, neg): # GH 17570 out = np.all(SparseArray(data)) @@ -956,7 +954,6 @@ def test_any(self, data, pos, neg): ([0.0, 2.0, 0.0], 2.0, 0.0), ], ) - @td.skip_if_np_lt("1.15") # prior didn't dispatch def test_numpy_any(self, data, pos, neg): # GH 17570 out = np.any(SparseArray(data)) diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index b0ba0d991c9b0..f21b1d3dfe487 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -1060,54 +1060,14 @@ def test_any_all_bool_only(self): (np.any, {"A": pd.Series([0.0, 1.0], dtype="float")}, True), (np.all, {"A": pd.Series([0, 1], dtype=int)}, False), (np.any, {"A": pd.Series([0, 1], dtype=int)}, True), - pytest.param( - np.all, - {"A": pd.Series([0, 1], dtype="M8[ns]")}, - False, - marks=[td.skip_if_np_lt("1.15")], - ), - pytest.param( - np.any, - {"A": pd.Series([0, 1], dtype="M8[ns]")}, - True, - marks=[td.skip_if_np_lt("1.15")], - ), - pytest.param( - np.all, - {"A": pd.Series([1, 2], dtype="M8[ns]")}, - True, - marks=[td.skip_if_np_lt("1.15")], - ), - pytest.param( - np.any, - {"A": pd.Series([1, 2], dtype="M8[ns]")}, - True, - marks=[td.skip_if_np_lt("1.15")], - ), - pytest.param( - np.all, - {"A": pd.Series([0, 1], dtype="m8[ns]")}, - False, - marks=[td.skip_if_np_lt("1.15")], - ), - pytest.param( - np.any, - {"A": pd.Series([0, 1], dtype="m8[ns]")}, - True, - marks=[td.skip_if_np_lt("1.15")], - ), - pytest.param( - np.all, - {"A": pd.Series([1, 2], dtype="m8[ns]")}, - True, - marks=[td.skip_if_np_lt("1.15")], - ), - pytest.param( - np.any, - {"A": pd.Series([1, 2], dtype="m8[ns]")}, - True, - marks=[td.skip_if_np_lt("1.15")], - ), + pytest.param(np.all, {"A": pd.Series([0, 1], dtype="M8[ns]")}, False,), + pytest.param(np.any, {"A": pd.Series([0, 1], dtype="M8[ns]")}, True,), + pytest.param(np.all, {"A": pd.Series([1, 2], dtype="M8[ns]")}, True,), + pytest.param(np.any, {"A": pd.Series([1, 2], dtype="M8[ns]")}, True,), + pytest.param(np.all, {"A": pd.Series([0, 1], dtype="m8[ns]")}, False,), + pytest.param(np.any, {"A": pd.Series([0, 1], dtype="m8[ns]")}, True,), + pytest.param(np.all, {"A": pd.Series([1, 2], dtype="m8[ns]")}, True,), + pytest.param(np.any, {"A": pd.Series([1, 2], dtype="m8[ns]")}, True,), (np.all, {"A": pd.Series([0, 1], dtype="category")}, False), (np.any, {"A": pd.Series([0, 1], dtype="category")}, True), (np.all, {"A": pd.Series([1, 2], dtype="category")}, True), @@ -1120,8 +1080,6 @@ def test_any_all_bool_only(self): "B": pd.Series([10, 20], dtype="m8[ns]"), }, True, - # In 1.13.3 and 1.14 np.all(df) returns a Timedelta here - marks=[td.skip_if_np_lt("1.15")], ), ], ) diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index 753b8b6eda9c5..c40935b2cc5dd 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -11,10 +11,6 @@ class TestToCSV: - @pytest.mark.xfail( - (3, 6, 5) > sys.version_info, - reason=("Python csv library bug (see https://bugs.python.org/issue32255)"), - ) def test_to_csv_with_single_column(self): # see gh-18676, https://bugs.python.org/issue32255 # diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index ab8618eb0a7d4..e39083b709f38 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -3,8 +3,6 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - import pandas as pd from pandas import DataFrame, Series import pandas._testing as tm @@ -130,7 +128,6 @@ def test_is_monotonic(self): @pytest.mark.parametrize("func", [np.any, np.all]) @pytest.mark.parametrize("kwargs", [dict(keepdims=True), dict(out=object())]) - @td.skip_if_np_lt("1.15") def test_validate_any_all_out_keepdims_raises(self, kwargs, func): s = pd.Series([1, 2]) param = list(kwargs)[0] @@ -144,7 +141,6 @@ def test_validate_any_all_out_keepdims_raises(self, kwargs, func): with pytest.raises(ValueError, match=msg): func(s, **kwargs) - @td.skip_if_np_lt("1.15") def test_validate_sum_initial(self): s = pd.Series([1, 2]) msg = ( @@ -167,7 +163,6 @@ def test_validate_median_initial(self): # method instead of the ufunc. s.median(overwrite_input=True) - @td.skip_if_np_lt("1.15") def test_validate_stat_keepdims(self): s = pd.Series([1, 2]) msg = (
https://api.github.com/repos/pandas-dev/pandas/pulls/36128
2020-09-04T20:37:37Z
2020-09-04T21:57:25Z
2020-09-04T21:57:25Z
2020-09-04T22:03:52Z
Backport PR #36050 on branch 1.1.x (BUG: incorrect year returned in isocalendar for certain dates)
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index 232d0c4b4bbcd..39850905f60fa 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -33,6 +33,7 @@ Bug fixes - Bug in :meth:`DataFrame.apply` with ``result_type="reduce"`` returning with incorrect index (:issue:`35683`) - Bug in :meth:`DateTimeIndex.format` and :meth:`PeriodIndex.format` with ``name=True`` setting the first item to ``"None"`` where it should be ``""`` (:issue:`35712`) - Bug in :meth:`Float64Index.__contains__` incorrectly raising ``TypeError`` instead of returning ``False`` (:issue:`35788`) +- Bug in :meth:`Series.dt.isocalendar` and :meth:`DatetimeIndex.isocalendar` that returned incorrect year for certain dates (:issue:`36032`) - Bug in :class:`DataFrame` indexing returning an incorrect :class:`Series` in some cases when the series has been altered and a cache not invalidated (:issue:`33675`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/ccalendar.pyx b/pandas/_libs/tslibs/ccalendar.pyx index 6cce2f5e1fd95..d8c83daa661a3 100644 --- a/pandas/_libs/tslibs/ccalendar.pyx +++ b/pandas/_libs/tslibs/ccalendar.pyx @@ -201,10 +201,10 @@ cpdef iso_calendar_t get_iso_calendar(int year, int month, int day) nogil: iso_week = 1 iso_year = year - if iso_week == 1 and doy > 7: + if iso_week == 1 and month == 12: iso_year += 1 - elif iso_week >= 52 and doy < 7: + elif iso_week >= 52 and month == 1: iso_year -= 1 return iso_year, iso_week, dow + 1 diff --git a/pandas/tests/series/test_datetime_values.py b/pandas/tests/series/test_datetime_values.py index d2ad9c8c398ea..723bd303b1974 100644 --- a/pandas/tests/series/test_datetime_values.py +++ b/pandas/tests/series/test_datetime_values.py @@ -682,6 +682,9 @@ def test_setitem_with_different_tz(self): [[pd.NaT], [[np.NaN, np.NaN, np.NaN]]], [["2019-12-31", "2019-12-29"], [[2020, 1, 2], [2019, 52, 7]]], [["2010-01-01", pd.NaT], [[2009, 53, 5], [np.NaN, np.NaN, np.NaN]]], + # see GH#36032 + [["2016-01-08", "2016-01-04"], [[2016, 1, 5], [2016, 1, 1]]], + [["2016-01-07", "2016-01-01"], [[2016, 1, 4], [2015, 53, 5]]], ], ) def test_isocalendar(self, input_series, expected_output): diff --git a/pandas/tests/tslibs/test_ccalendar.py b/pandas/tests/tslibs/test_ccalendar.py index aab86d3a2df69..1ff700fdc23a3 100644 --- a/pandas/tests/tslibs/test_ccalendar.py +++ b/pandas/tests/tslibs/test_ccalendar.py @@ -1,10 +1,13 @@ from datetime import date, datetime +from hypothesis import given, strategies as st import numpy as np import pytest from pandas._libs.tslibs import ccalendar +import pandas as pd + @pytest.mark.parametrize( "date_tuple,expected", @@ -48,3 +51,15 @@ def test_dt_correct_iso_8601_year_week_and_day(input_date_tuple, expected_iso_tu expected_from_date_isocalendar = date(*input_date_tuple).isocalendar() assert result == expected_from_date_isocalendar assert result == expected_iso_tuple + + +@given( + st.datetimes( + min_value=pd.Timestamp.min.to_pydatetime(warn=False), + max_value=pd.Timestamp.max.to_pydatetime(warn=False), + ) +) +def test_isocalendar(dt): + expected = dt.isocalendar() + result = ccalendar.get_iso_calendar(dt.year, dt.month, dt.day) + assert result == expected
Backport PR #36050: BUG: incorrect year returned in isocalendar for certain dates
https://api.github.com/repos/pandas-dev/pandas/pulls/36127
2020-09-04T20:29:38Z
2020-09-04T21:58:13Z
2020-09-04T21:58:13Z
2020-09-04T21:58:14Z
DOC: add missing data handling info to pd.Categorical docstring
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 27b1afdb438cb..ef363ca6b0187 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -280,6 +280,19 @@ class Categorical(NDArrayBackedExtensionArray, PandasObject): ['a', 'b', 'c', 'a', 'b', 'c'] Categories (3, object): ['a', 'b', 'c'] + Missing values are not included as a category. + + >>> c = pd.Categorical([1, 2, 3, 1, 2, 3, np.nan]) + >>> c + [1, 2, 3, 1, 2, 3, NaN] + Categories (3, int64): [1, 2, 3] + + However, their presence is indicated in the `codes` attribute + by code `-1`. + + >>> c.codes + array([ 0, 1, 2, 0, 1, 2, -1], dtype=int8) + Ordered `Categoricals` can be sorted according to the custom order of the categories and can have a min and max value.
- [x] closes #35162 - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/36125
2020-09-04T19:21:33Z
2020-09-05T10:50:58Z
2020-09-05T10:50:58Z
2020-09-05T10:50:58Z
Bug 29764 groupby loses index name sometimes
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index e65daa439a225..7ff946574c778 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -311,6 +311,7 @@ Groupby/resample/rolling - Bug in :meth:`DataFrameGroupby.apply` would drop a :class:`CategoricalIndex` when grouped on. (:issue:`35792`) - Bug when subsetting columns on a :class:`~pandas.core.groupby.DataFrameGroupBy` (e.g. ``df.groupby('a')[['b']])``) would reset the attributes ``axis``, ``dropna``, ``group_keys``, ``level``, ``mutated``, ``sort``, and ``squeeze`` to their default values. (:issue:`9959`) - Bug in :meth:`DataFrameGroupby.tshift` failing to raise ``ValueError`` when a frequency cannot be inferred for the index of a group (:issue:`35937`) +- Bug in :meth:`DataFrame.groupby` does not always maintain column index name for ``any``, ``all``, ``bfill``, ``ffill``, ``shift`` (:issue:`29764`) - Reshaping diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 537feace59fcb..a58f28880945f 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -1694,6 +1694,7 @@ def _wrap_transformed_output( """ indexed_output = {key.position: val for key, val in output.items()} columns = Index(key.label for key in output) + columns.name = self.obj.columns.name result = self.obj._constructor(indexed_output) result.columns = columns diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index eec9e8064d584..e0196df7ceac0 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -2111,3 +2111,26 @@ def test_subsetting_columns_keeps_attrs(klass, attr, value): expected = df.groupby("a", **{attr: value}) result = expected[["b"]] if klass is DataFrame else expected["b"] assert getattr(result, attr) == getattr(expected, attr) + + +@pytest.mark.parametrize("func", ["sum", "any", "shift"]) +def test_groupby_column_index_name_lost(func): + # GH: 29764 groupby loses index sometimes + expected = pd.Index(["a"], name="idx") + df = pd.DataFrame([[1]], columns=expected) + df_grouped = df.groupby([1]) + result = getattr(df_grouped, func)().columns + tm.assert_index_equal(result, expected) + + +@pytest.mark.parametrize("func", ["ffill", "bfill"]) +def test_groupby_column_index_name_lost_fill_funcs(func): + # GH: 29764 groupby loses index sometimes + df = pd.DataFrame( + [[1, 1.0, -1.0], [1, np.nan, np.nan], [1, 2.0, -2.0]], + columns=pd.Index(["type", "a", "b"], name="idx"), + ) + df_grouped = df.groupby(["type"])[["a", "b"]] + result = getattr(df_grouped, func)().columns + expected = pd.Index(["a", "b"], name="idx") + tm.assert_index_equal(result, expected)
- [x] closes #29764 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry´ Issue was fixed for sum and any with c9144ca54dcc924995acae3d9dcb890a5802d7c0. So the only thing left was to add the index name in `_wrap_transformed_output`. I kept the tests from #33111, to show, that alle cases are now handled correctly. I hope it is okay, to add a new PR for this?
https://api.github.com/repos/pandas-dev/pandas/pulls/36121
2020-09-04T16:42:54Z
2020-09-05T03:18:13Z
2020-09-05T03:18:12Z
2020-09-05T19:04:08Z
TYP: io
diff --git a/pandas/io/excel/_util.py b/pandas/io/excel/_util.py index 285aeaf7d4c6e..a4b5b61734ab7 100644 --- a/pandas/io/excel/_util.py +++ b/pandas/io/excel/_util.py @@ -1,3 +1,5 @@ +from typing import List + from pandas.compat._optional import import_optional_dependency from pandas.core.dtypes.common import is_integer, is_list_like @@ -56,7 +58,7 @@ def get_writer(engine_name): raise ValueError(f"No Excel writer '{engine_name}'") from err -def _excel2num(x): +def _excel2num(x: str) -> int: """ Convert Excel column name like 'AB' to 0-based column index. @@ -88,7 +90,7 @@ def _excel2num(x): return index - 1 -def _range2cols(areas): +def _range2cols(areas: str) -> List[int]: """ Convert comma separated list of column names and ranges to indices. @@ -109,12 +111,12 @@ def _range2cols(areas): >>> _range2cols('A,C,Z:AB') [0, 2, 25, 26, 27] """ - cols = [] + cols: List[int] = [] for rng in areas.split(","): if ":" in rng: - rng = rng.split(":") - cols.extend(range(_excel2num(rng[0]), _excel2num(rng[1]) + 1)) + rngs = rng.split(":") + cols.extend(range(_excel2num(rngs[0]), _excel2num(rngs[1]) + 1)) else: cols.append(_excel2num(rng)) diff --git a/pandas/io/formats/css.py b/pandas/io/formats/css.py index 4d6f03489725f..2e9ee192a1182 100644 --- a/pandas/io/formats/css.py +++ b/pandas/io/formats/css.py @@ -3,6 +3,7 @@ """ import re +from typing import Optional import warnings @@ -93,6 +94,7 @@ def __call__(self, declarations_str, inherited=None): props[prop] = val # 2. resolve relative font size + font_size: Optional[float] if props.get("font-size"): if "font-size" in inherited: em_pt = inherited["font-size"] @@ -173,10 +175,11 @@ def _error(): warnings.warn(f"Unhandled size: {repr(in_val)}", CSSWarning) return self.size_to_pt("1!!default", conversions=conversions) - try: - val, unit = re.match(r"^(\S*?)([a-zA-Z%!].*)", in_val).groups() - except AttributeError: + match = re.match(r"^(\S*?)([a-zA-Z%!].*)", in_val) + if match is None: return _error() + + val, unit = match.groups() if val == "": # hack for 'large' etc. val = 1 diff --git a/setup.cfg b/setup.cfg index 29c731848de8e..e7d7df7ff19a2 100644 --- a/setup.cfg +++ b/setup.cfg @@ -279,9 +279,6 @@ check_untyped_defs=False [mypy-pandas.io.formats.console] check_untyped_defs=False -[mypy-pandas.io.formats.css] -check_untyped_defs=False - [mypy-pandas.io.formats.csvs] check_untyped_defs=False
@simonjayhawkins are there any typing-related areas that you'd suggest I prioritize?
https://api.github.com/repos/pandas-dev/pandas/pulls/36120
2020-09-04T16:17:42Z
2020-09-04T17:34:50Z
2020-09-04T17:34:50Z
2020-09-04T17:53:49Z
Backport PR #36118 on branch 1.1.x (REGR: ensure closed attribute of IntervalIndex is preserved in pickle roundtrip)
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index 7195f3d7a3885..232d0c4b4bbcd 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -18,8 +18,9 @@ Fixed regressions - Fix regression in updating a column inplace (e.g. using ``df['col'].fillna(.., inplace=True)``) (:issue:`35731`) - Performance regression for :meth:`RangeIndex.format` (:issue:`35712`) - Regression in :meth:`DataFrame.replace` where a ``TypeError`` would be raised when attempting to replace elements of type :class:`Interval` (:issue:`35931`) +- Fix regression in pickle roundtrip of the ``closed`` attribute of :class:`IntervalIndex` (:issue:`35658`) - Fixed regression in :meth:`DataFrameGroupBy.agg` where a ``ValueError: buffer source array is read-only`` would be raised when the underlying array is read-only (:issue:`36014`) - +- .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 446e57d58a779..dcf89f24ebaf2 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -190,7 +190,7 @@ def func(intvidx_self, other, sort=False): class IntervalIndex(IntervalMixin, ExtensionIndex): _typ = "intervalindex" _comparables = ["name"] - _attributes = ["name"] + _attributes = ["name", "closed"] # we would like our indexing holder to defer to us _defer_to_indexing = True diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index 2755b186f3eae..a20e542b1edd7 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -874,6 +874,13 @@ def test_get_value_non_scalar_errors(self, key): with tm.assert_produces_warning(FutureWarning): idx.get_value(s, key) + @pytest.mark.parametrize("closed", ["left", "right", "both"]) + def test_pickle_round_trip_closed(self, closed): + # https://github.com/pandas-dev/pandas/issues/35658 + idx = IntervalIndex.from_tuples([(1, 2), (2, 3)], closed=closed) + result = tm.round_trip_pickle(idx) + tm.assert_index_equal(result, idx) + def test_dir(): # GH#27571 dir(interval_index) should not raise
Backport PR #36118: REGR: ensure closed attribute of IntervalIndex is preserved in pickle roundtrip
https://api.github.com/repos/pandas-dev/pandas/pulls/36119
2020-09-04T15:59:58Z
2020-09-04T17:49:50Z
2020-09-04T17:49:50Z
2020-09-04T17:49:50Z
REGR: ensure closed attribute of IntervalIndex is preserved in pickle roundtrip
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index 7195f3d7a3885..232d0c4b4bbcd 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -18,8 +18,9 @@ Fixed regressions - Fix regression in updating a column inplace (e.g. using ``df['col'].fillna(.., inplace=True)``) (:issue:`35731`) - Performance regression for :meth:`RangeIndex.format` (:issue:`35712`) - Regression in :meth:`DataFrame.replace` where a ``TypeError`` would be raised when attempting to replace elements of type :class:`Interval` (:issue:`35931`) +- Fix regression in pickle roundtrip of the ``closed`` attribute of :class:`IntervalIndex` (:issue:`35658`) - Fixed regression in :meth:`DataFrameGroupBy.agg` where a ``ValueError: buffer source array is read-only`` would be raised when the underlying array is read-only (:issue:`36014`) - +- .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 08f9bd51de77b..419ff81a2a478 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -193,7 +193,7 @@ def func(intvidx_self, other, sort=False): class IntervalIndex(IntervalMixin, ExtensionIndex): _typ = "intervalindex" _comparables = ["name"] - _attributes = ["name"] + _attributes = ["name", "closed"] # we would like our indexing holder to defer to us _defer_to_indexing = True diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index 2755b186f3eae..a20e542b1edd7 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -874,6 +874,13 @@ def test_get_value_non_scalar_errors(self, key): with tm.assert_produces_warning(FutureWarning): idx.get_value(s, key) + @pytest.mark.parametrize("closed", ["left", "right", "both"]) + def test_pickle_round_trip_closed(self, closed): + # https://github.com/pandas-dev/pandas/issues/35658 + idx = IntervalIndex.from_tuples([(1, 2), (2, 3)], closed=closed) + result = tm.round_trip_pickle(idx) + tm.assert_index_equal(result, idx) + def test_dir(): # GH#27571 dir(interval_index) should not raise
Closes #35658 cc @jbrockmendel (I suppose the long term way would rather to properly pickle the IntervalArray itself and restore from that, instead of restoring from the left/right arrays, but would rather leave such a change for 1.2)
https://api.github.com/repos/pandas-dev/pandas/pulls/36118
2020-09-04T14:30:02Z
2020-09-04T15:17:10Z
2020-09-04T15:17:10Z
2020-09-04T15:59:48Z
Backport PR #36061 on branch 1.1.x (BUG: groupby and agg on read-only array gives ValueError: buffer source array is read-only)
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index ac9fe9d2fca26..7195f3d7a3885 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -18,7 +18,7 @@ Fixed regressions - Fix regression in updating a column inplace (e.g. using ``df['col'].fillna(.., inplace=True)``) (:issue:`35731`) - Performance regression for :meth:`RangeIndex.format` (:issue:`35712`) - Regression in :meth:`DataFrame.replace` where a ``TypeError`` would be raised when attempting to replace elements of type :class:`Interval` (:issue:`35931`) -- +- Fixed regression in :meth:`DataFrameGroupBy.agg` where a ``ValueError: buffer source array is read-only`` would be raised when the underlying array is read-only (:issue:`36014`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 38cb973d6dde9..a83634aad3ce2 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -229,7 +229,7 @@ def group_cumprod_float64(float64_t[:, :] out, @cython.boundscheck(False) @cython.wraparound(False) def group_cumsum(numeric[:, :] out, - numeric[:, :] values, + ndarray[numeric, ndim=2] values, const int64_t[:] labels, int ngroups, is_datetimelike, @@ -472,7 +472,7 @@ ctypedef fused complexfloating_t: @cython.boundscheck(False) def _group_add(complexfloating_t[:, :] out, int64_t[:] counts, - complexfloating_t[:, :] values, + ndarray[complexfloating_t, ndim=2] values, const int64_t[:] labels, Py_ssize_t min_count=0): """ @@ -483,8 +483,9 @@ def _group_add(complexfloating_t[:, :] out, complexfloating_t val, count complexfloating_t[:, :] sumx int64_t[:, :] nobs + Py_ssize_t len_values = len(values), len_labels = len(labels) - if len(values) != len(labels): + if len_values != len_labels: raise ValueError("len(index) != len(labels)") nobs = np.zeros((<object>out).shape, dtype=np.int64) @@ -530,7 +531,7 @@ group_add_complex128 = _group_add['double complex'] @cython.boundscheck(False) def _group_prod(floating[:, :] out, int64_t[:] counts, - floating[:, :] values, + ndarray[floating, ndim=2] values, const int64_t[:] labels, Py_ssize_t min_count=0): """ @@ -541,8 +542,9 @@ def _group_prod(floating[:, :] out, floating val, count floating[:, :] prodx int64_t[:, :] nobs + Py_ssize_t len_values = len(values), len_labels = len(labels) - if not len(values) == len(labels): + if len_values != len_labels: raise ValueError("len(index) != len(labels)") nobs = np.zeros((<object>out).shape, dtype=np.int64) @@ -582,7 +584,7 @@ group_prod_float64 = _group_prod['double'] @cython.cdivision(True) def _group_var(floating[:, :] out, int64_t[:] counts, - floating[:, :] values, + ndarray[floating, ndim=2] values, const int64_t[:] labels, Py_ssize_t min_count=-1, int64_t ddof=1): @@ -591,10 +593,11 @@ def _group_var(floating[:, :] out, floating val, ct, oldmean floating[:, :] mean int64_t[:, :] nobs + Py_ssize_t len_values = len(values), len_labels = len(labels) assert min_count == -1, "'min_count' only used in add and prod" - if not len(values) == len(labels): + if len_values != len_labels: raise ValueError("len(index) != len(labels)") nobs = np.zeros((<object>out).shape, dtype=np.int64) @@ -639,7 +642,7 @@ group_var_float64 = _group_var['double'] @cython.boundscheck(False) def _group_mean(floating[:, :] out, int64_t[:] counts, - floating[:, :] values, + ndarray[floating, ndim=2] values, const int64_t[:] labels, Py_ssize_t min_count=-1): cdef: @@ -647,10 +650,11 @@ def _group_mean(floating[:, :] out, floating val, count floating[:, :] sumx int64_t[:, :] nobs + Py_ssize_t len_values = len(values), len_labels = len(labels) assert min_count == -1, "'min_count' only used in add and prod" - if not len(values) == len(labels): + if len_values != len_labels: raise ValueError("len(index) != len(labels)") nobs = np.zeros((<object>out).shape, dtype=np.int64) @@ -689,7 +693,7 @@ group_mean_float64 = _group_mean['double'] @cython.boundscheck(False) def _group_ohlc(floating[:, :] out, int64_t[:] counts, - floating[:, :] values, + ndarray[floating, ndim=2] values, const int64_t[:] labels, Py_ssize_t min_count=-1): """ @@ -740,7 +744,7 @@ group_ohlc_float64 = _group_ohlc['double'] @cython.boundscheck(False) @cython.wraparound(False) def group_quantile(ndarray[float64_t] out, - numeric[:] values, + ndarray[numeric, ndim=1] values, ndarray[int64_t] labels, ndarray[uint8_t] mask, float64_t q, @@ -1072,7 +1076,7 @@ def group_nth(rank_t[:, :] out, @cython.boundscheck(False) @cython.wraparound(False) def group_rank(float64_t[:, :] out, - rank_t[:, :] values, + ndarray[rank_t, ndim=2] values, const int64_t[:] labels, int ngroups, bint is_datetimelike, object ties_method="average", @@ -1424,7 +1428,7 @@ def group_min(groupby_t[:, :] out, @cython.boundscheck(False) @cython.wraparound(False) def group_cummin(groupby_t[:, :] out, - groupby_t[:, :] values, + ndarray[groupby_t, ndim=2] values, const int64_t[:] labels, int ngroups, bint is_datetimelike): @@ -1484,7 +1488,7 @@ def group_cummin(groupby_t[:, :] out, @cython.boundscheck(False) @cython.wraparound(False) def group_cummax(groupby_t[:, :] out, - groupby_t[:, :] values, + ndarray[groupby_t, ndim=2] values, const int64_t[:] labels, int ngroups, bint is_datetimelike): diff --git a/pandas/tests/groupby/aggregate/test_cython.py b/pandas/tests/groupby/aggregate/test_cython.py index 5ddda264642de..87ebd8b5a27fb 100644 --- a/pandas/tests/groupby/aggregate/test_cython.py +++ b/pandas/tests/groupby/aggregate/test_cython.py @@ -236,3 +236,44 @@ def test_cython_with_timestamp_and_nat(op, data): result = df.groupby("a").aggregate(op) tm.assert_frame_equal(expected, result) + + +@pytest.mark.parametrize( + "agg", + [ + "min", + "max", + "count", + "sum", + "prod", + "var", + "mean", + "median", + "ohlc", + "cumprod", + "cumsum", + "shift", + "any", + "all", + "quantile", + "first", + "last", + "rank", + "cummin", + "cummax", + ], +) +def test_read_only_buffer_source_agg(agg): + # https://github.com/pandas-dev/pandas/issues/36014 + df = DataFrame( + { + "sepal_length": [5.1, 4.9, 4.7, 4.6, 5.0], + "species": ["setosa", "setosa", "setosa", "setosa", "setosa"], + } + ) + df._mgr.blocks[0].values.flags.writeable = False + + result = df.groupby(["species"]).agg({"sepal_length": agg}) + expected = df.copy().groupby(["species"]).agg({"sepal_length": agg}) + + tm.assert_equal(result, expected)
Backport PR #36061: BUG: groupby and agg on read-only array gives ValueError: buffer source array is read-only
https://api.github.com/repos/pandas-dev/pandas/pulls/36117
2020-09-04T14:28:47Z
2020-09-04T15:14:26Z
2020-09-04T15:14:26Z
2020-09-04T17:59:04Z
REGR: append tz-aware DataFrame with tz-naive values
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index 232d0c4b4bbcd..981bba1a30ff8 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -16,6 +16,7 @@ Fixed regressions ~~~~~~~~~~~~~~~~~ - Regression in :meth:`DatetimeIndex.intersection` incorrectly raising ``AssertionError`` when intersecting against a list (:issue:`35876`) - Fix regression in updating a column inplace (e.g. using ``df['col'].fillna(.., inplace=True)``) (:issue:`35731`) +- Fix regression in :meth:`DataFrame.append` mixing tz-aware and tz-naive datetime columns (:issue:`35460`) - Performance regression for :meth:`RangeIndex.format` (:issue:`35712`) - Regression in :meth:`DataFrame.replace` where a ``TypeError`` would be raised when attempting to replace elements of type :class:`Interval` (:issue:`35931`) - Fix regression in pickle roundtrip of the ``closed`` attribute of :class:`IntervalIndex` (:issue:`35658`) diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 9902016475b22..dd005752a4832 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -148,15 +148,17 @@ def is_nonempty(x) -> bool: any_ea = any(is_extension_array_dtype(x.dtype) for x in to_concat) if any_ea: + # we ignore axis here, as internally concatting with EAs is always + # for axis=0 if not single_dtype: target_dtype = find_common_type([x.dtype for x in to_concat]) to_concat = [_cast_to_common_type(arr, target_dtype) for arr in to_concat] - if isinstance(to_concat[0], ExtensionArray) and axis == 0: + if isinstance(to_concat[0], ExtensionArray): cls = type(to_concat[0]) return cls._concat_same_type(to_concat) else: - return np.concatenate(to_concat, axis=axis) + return np.concatenate(to_concat) elif _contains_datetime or "timedelta" in typs: return concat_datetime(to_concat, axis=axis, typs=typs) diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 88839d2211f81..a13a0d73d434f 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -24,7 +24,7 @@ from pandas.core.dtypes.missing import isna import pandas.core.algorithms as algos -from pandas.core.arrays import ExtensionArray +from pandas.core.arrays import DatetimeArray, ExtensionArray from pandas.core.internals.blocks import make_block from pandas.core.internals.managers import BlockManager @@ -335,9 +335,13 @@ def _concatenate_join_units(join_units, concat_axis, copy): # the non-EA values are 2D arrays with shape (1, n) to_concat = [t if isinstance(t, ExtensionArray) else t[0, :] for t in to_concat] concat_values = concat_compat(to_concat, axis=0) - if not isinstance(concat_values, ExtensionArray): + if not isinstance(concat_values, ExtensionArray) or ( + isinstance(concat_values, DatetimeArray) and concat_values.tz is None + ): # if the result of concat is not an EA but an ndarray, reshape to # 2D to put it a non-EA Block + # special case DatetimeArray, which *is* an EA, but is put in a + # consolidated 2D block concat_values = np.atleast_2d(concat_values) else: concat_values = concat_compat(to_concat, axis=concat_axis) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index 38cf2cc2402a1..90705f827af25 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -1110,6 +1110,23 @@ def test_append_empty_frame_to_series_with_dateutil_tz(self): result = df.append([s, s], ignore_index=True) tm.assert_frame_equal(result, expected) + def test_append_empty_tz_frame_with_datetime64ns(self): + # https://github.com/pandas-dev/pandas/issues/35460 + df = pd.DataFrame(columns=["a"]).astype("datetime64[ns, UTC]") + + # pd.NaT gets inferred as tz-naive, so append result is tz-naive + result = df.append({"a": pd.NaT}, ignore_index=True) + expected = pd.DataFrame({"a": [pd.NaT]}).astype("datetime64[ns]") + tm.assert_frame_equal(result, expected) + + # also test with typed value to append + df = pd.DataFrame(columns=["a"]).astype("datetime64[ns, UTC]") + result = df.append( + pd.Series({"a": pd.NaT}, dtype="datetime64[ns]"), ignore_index=True + ) + expected = pd.DataFrame({"a": [pd.NaT]}).astype("datetime64[ns]") + tm.assert_frame_equal(result, expected) + class TestConcatenate: def test_concat_copy(self):
Closes #35460
https://api.github.com/repos/pandas-dev/pandas/pulls/36115
2020-09-04T14:00:20Z
2020-09-06T16:58:33Z
2020-09-06T16:58:33Z
2021-01-28T22:36:17Z
REGR: fix consolidation/cache issue with take operation
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index 7195f3d7a3885..f88198528fdf9 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -17,6 +17,7 @@ Fixed regressions - Regression in :meth:`DatetimeIndex.intersection` incorrectly raising ``AssertionError`` when intersecting against a list (:issue:`35876`) - Fix regression in updating a column inplace (e.g. using ``df['col'].fillna(.., inplace=True)``) (:issue:`35731`) - Performance regression for :meth:`RangeIndex.format` (:issue:`35712`) +- Fix regression in invalid cache after an indexing operation; this can manifest when setting which does not update the data (:issue:`35521`) - Regression in :meth:`DataFrame.replace` where a ``TypeError`` would be raised when attempting to replace elements of type :class:`Interval` (:issue:`35931`) - Fixed regression in :meth:`DataFrameGroupBy.agg` where a ``ValueError: buffer source array is read-only`` would be raised when the underlying array is read-only (:issue:`36014`) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 6c8780a0fc186..2af323ccc1dd3 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3534,6 +3534,8 @@ class max_speed nv.validate_take(tuple(), kwargs) + self._consolidate_inplace() + new_data = self._mgr.take( indices, axis=self._get_block_manager_axis(axis), verify=True ) diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index 00cfa6265934f..4a85da72bc8b1 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -658,3 +658,26 @@ def test_update_inplace_sets_valid_block_values(): # smoketest for OP bug from GH#35731 assert df.isnull().sum().sum() == 0 + + +def test_nonconsolidated_item_cache_take(): + # https://github.com/pandas-dev/pandas/issues/35521 + + # create non-consolidated dataframe with object dtype columns + df = pd.DataFrame() + df["col1"] = pd.Series(["a"], dtype=object) + df["col2"] = pd.Series([0], dtype=object) + + # access column (item cache) + df["col1"] == "A" + # take operation + # (regression was that this consolidated but didn't reset item cache, + # resulting in an invalid cache and the .at operation not working properly) + df[df["col2"] == 0] + + # now setting value should update actual dataframe + df.at[0, "col1"] = "A" + + expected = pd.DataFrame({"col1": ["A"], "col2": [0]}, dtype=object) + tm.assert_frame_equal(df, expected) + assert df.at[0, "col1"] == "A"
Closes #35521 @jbrockmendel the "short term" fix for 1.1.2
https://api.github.com/repos/pandas-dev/pandas/pulls/36114
2020-09-04T13:14:06Z
2020-09-04T20:48:44Z
2020-09-04T20:48:43Z
2020-09-05T06:04:33Z
DOC: sync doc/source/whatsnew/v1.1.2.rst on 1.1.x
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index 8695ff8d11e6d..ac9fe9d2fca26 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -20,6 +20,7 @@ Fixed regressions - Regression in :meth:`DataFrame.replace` where a ``TypeError`` would be raised when attempting to replace elements of type :class:`Interval` (:issue:`35931`) - + .. --------------------------------------------------------------------------- .. _whatsnew_112.bug_fixes:
~~don't merge this yet. I'll make sure a test is failing first~~
https://api.github.com/repos/pandas-dev/pandas/pulls/36112
2020-09-04T09:28:13Z
2020-09-04T11:44:22Z
2020-09-04T11:44:22Z
2020-09-04T11:44:29Z
CLN: use IS64 instead of is_platform_32bit #36108
diff --git a/pandas/_libs/missing.pyx b/pandas/_libs/missing.pyx index 771e8053ac9be..abf38265ddc6d 100644 --- a/pandas/_libs/missing.pyx +++ b/pandas/_libs/missing.pyx @@ -18,7 +18,7 @@ from pandas._libs.tslibs.nattype cimport ( from pandas._libs.tslibs.np_datetime cimport get_datetime64_value, get_timedelta64_value from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op -from pandas.compat import is_platform_32bit +from pandas.compat import IS64 cdef: float64_t INF = <float64_t>np.inf @@ -26,7 +26,7 @@ cdef: int64_t NPY_NAT = util.get_nat() - bint is_32bit = is_platform_32bit() + bint is_32bit = not IS64 cpdef bint checknull(object val): diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index ab2835932c95d..f2018a5c01711 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -8,7 +8,6 @@ * platform checker """ import platform -import struct import sys import warnings @@ -20,14 +19,6 @@ IS64 = sys.maxsize > 2 ** 32 -# ---------------------------------------------------------------------------- -# functions largely based / taken from the six module - -# Much of the code in this module comes from Benjamin Peterson's six library. -# The license for this library can be found in LICENSES/SIX and the code can be -# found at https://bitbucket.org/gutworth/six - - def set_function_name(f: F, name: str, cls) -> F: """ Bind the name/qualname attributes of the function. @@ -38,7 +29,6 @@ def set_function_name(f: F, name: str, cls) -> F: return f -# https://github.com/pandas-dev/pandas/pull/9123 def is_platform_little_endian() -> bool: """ Checking if the running platform is little endian. @@ -72,7 +62,7 @@ def is_platform_linux() -> bool: bool True if the running platform is linux. """ - return sys.platform == "linux2" + return sys.platform == "linux" def is_platform_mac() -> bool: @@ -87,18 +77,6 @@ def is_platform_mac() -> bool: return sys.platform == "darwin" -def is_platform_32bit() -> bool: - """ - Checking if the running platform is 32-bit. - - Returns - ------- - bool - True if the running platform is 32-bit. - """ - return struct.calcsize("P") * 8 < 64 - - def _import_lzma(): """ Importing the `lzma` module. diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index b1c31a6f90133..8b5d0c7ade56c 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -6,11 +6,12 @@ import numpy as np import pytest +from pandas.compat import IS64, is_platform_windows import pandas.util._test_decorators as td from pandas.util._test_decorators import async_mark, skip_if_no import pandas as pd -from pandas import Categorical, DataFrame, Series, compat, date_range, timedelta_range +from pandas import Categorical, DataFrame, Series, date_range, timedelta_range import pandas._testing as tm @@ -254,7 +255,7 @@ def test_itertuples(self, float_frame): assert list(dfaa.itertuples()) == [(0, 1, 1), (1, 2, 2), (2, 3, 3)] # repr with int on 32-bit/windows - if not (compat.is_platform_windows() or compat.is_platform_32bit()): + if not (is_platform_windows() or not IS64): assert ( repr(list(df.itertuples(name=None))) == "[(0, 1, 4), (1, 2, 5), (2, 3, 6)]" diff --git a/pandas/tests/indexes/interval/test_interval_tree.py b/pandas/tests/indexes/interval/test_interval_tree.py index 476ec1dd10b4b..ab6eac482211d 100644 --- a/pandas/tests/indexes/interval/test_interval_tree.py +++ b/pandas/tests/indexes/interval/test_interval_tree.py @@ -4,8 +4,8 @@ import pytest from pandas._libs.interval import IntervalTree +from pandas.compat import IS64 -from pandas import compat import pandas._testing as tm @@ -14,9 +14,7 @@ def skipif_32bit(param): Skip parameters in a parametrize on 32bit systems. Specifically used here to skip leaf_size parameters related to GH 23440. """ - marks = pytest.mark.skipif( - compat.is_platform_32bit(), reason="GH 23440: int type mismatch on 32bit" - ) + marks = pytest.mark.skipif(not IS64, reason="GH 23440: int type mismatch on 32bit") return pytest.param(param, marks=marks) @@ -181,7 +179,7 @@ def test_is_overlapping_trivial(self, closed, left, right): tree = IntervalTree(left, right, closed=closed) assert tree.is_overlapping is False - @pytest.mark.skipif(compat.is_platform_32bit(), reason="GH 23440") + @pytest.mark.skipif(not IS64, reason="GH 23440") def test_construction_overflow(self): # GH 25485 left, right = np.arange(101, dtype="int64"), [np.iinfo(np.int64).max] * 101 diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 1512c88a68778..1c5f00ff754a4 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -5,7 +5,7 @@ import numpy as np import pytest -import pandas.compat as compat +from pandas.compat import IS64, is_platform_windows import pandas as pd import pandas._testing as tm @@ -1041,7 +1041,7 @@ def test_replace_series(self, how, to_key, from_key): from_key == "complex128" and to_key in ("int64", "float64") ): - if compat.is_platform_32bit() or compat.is_platform_windows(): + if not IS64 or is_platform_windows(): pytest.skip(f"32-bit platform buggy: {from_key} -> {to_key}") # Expected: do not downcast by replacement diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 1bbfe4d7d74af..22942ed75d0f3 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -18,7 +18,7 @@ import pytest import pytz -from pandas.compat import is_platform_32bit, is_platform_windows +from pandas.compat import IS64, is_platform_windows import pandas.util._test_decorators as td import pandas as pd @@ -41,7 +41,7 @@ import pandas.io.formats.format as fmt import pandas.io.formats.printing as printing -use_32bit_repr = is_platform_windows() or is_platform_32bit() +use_32bit_repr = is_platform_windows() or not IS64 @pytest.fixture(params=["string", "pathlike", "buffer"]) diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 2022abbaee323..59d64e1a6e909 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -9,7 +9,7 @@ import numpy as np import pytest -from pandas.compat import is_platform_32bit, is_platform_windows +from pandas.compat import IS64, is_platform_windows import pandas.util._test_decorators as td import pandas as pd @@ -154,7 +154,7 @@ def test_roundtrip_intframe(self, orient, convert_axes, numpy, dtype, int_frame) expected = int_frame if ( numpy - and (is_platform_32bit() or is_platform_windows()) + and (not IS64 or is_platform_windows()) and not dtype and orient != "split" ): @@ -361,9 +361,7 @@ def test_frame_infinity(self, orient, inf, dtype): 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" - ) + @pytest.mark.skipif(not IS64, reason="not compliant on 32-bit, xref #15865") @pytest.mark.parametrize( "value,precision,expected_val", [ diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index f969cbca9f427..e2007e07c572a 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -15,7 +15,7 @@ import pandas._libs.json as ujson from pandas._libs.tslib import Timestamp -import pandas.compat as compat +from pandas.compat import IS64, is_platform_windows from pandas import DataFrame, DatetimeIndex, Index, NaT, Series, Timedelta, date_range import pandas._testing as tm @@ -53,7 +53,7 @@ def get_int32_compat_dtype(numpy, orient): # See GH#32527 dtype = np.int64 if not ((numpy is None or orient == "index") or (numpy is True and orient is None)): - if compat.is_platform_windows(): + if is_platform_windows(): dtype = np.int32 else: dtype = np.intp @@ -62,9 +62,7 @@ def get_int32_compat_dtype(numpy, orient): class TestUltraJSONTests: - @pytest.mark.skipif( - compat.is_platform_32bit(), reason="not compliant on 32-bit, xref #15865" - ) + @pytest.mark.skipif(not IS64, reason="not compliant on 32-bit, xref #15865") def test_encode_decimal(self): sut = decimal.Decimal("1337.1337") encoded = ujson.encode(sut, double_precision=15) @@ -561,7 +559,7 @@ def test_encode_long_conversion(self): assert long_input == ujson.decode(output) @pytest.mark.parametrize("bigNum", [sys.maxsize + 1, -(sys.maxsize + 2)]) - @pytest.mark.xfail(not compat.IS64, reason="GH-35288") + @pytest.mark.xfail(not IS64, reason="GH-35288") def test_dumps_ints_larger_than_maxsize(self, bigNum): # GH34395 bigNum = sys.maxsize + 1 @@ -703,7 +701,7 @@ def test_int_array(self, any_int_dtype): tm.assert_numpy_array_equal(arr_input, arr_output) def test_int_max(self, any_int_dtype): - if any_int_dtype in ("int64", "uint64") and compat.is_platform_32bit(): + if any_int_dtype in ("int64", "uint64") and not IS64: pytest.skip("Cannot test 64-bit integer on 32-bit platform") klass = np.dtype(any_int_dtype).type diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 59c6a5d53e7bb..72a679d980641 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -8,6 +8,7 @@ from pandas._libs import algos as libalgos, hashtable as ht from pandas._libs.groupby import group_var_float32, group_var_float64 +from pandas.compat import IS64 from pandas.compat.numpy import np_array_datetime64_compat import pandas.util._test_decorators as td @@ -29,7 +30,6 @@ IntervalIndex, Series, Timestamp, - compat, ) import pandas._testing as tm import pandas.core.algorithms as algos @@ -1137,7 +1137,7 @@ def test_dropna(self): ) # 32-bit linux has a different ordering - if not compat.is_platform_32bit(): + if IS64: result = Series([10.3, 5.0, 5.0, None]).value_counts(dropna=False) expected = Series([2, 1, 1], index=[5.0, 10.3, np.nan]) tm.assert_series_equal(result, expected) @@ -1170,7 +1170,7 @@ def test_value_counts_uint64(self): result = algos.value_counts(arr) # 32-bit linux has a different ordering - if not compat.is_platform_32bit(): + if IS64: tm.assert_series_equal(result, expected) diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py index ca7b99492bbf7..78facd6694635 100644 --- a/pandas/util/_test_decorators.py +++ b/pandas/util/_test_decorators.py @@ -31,7 +31,7 @@ def test_foo(): import numpy as np import pytest -from pandas.compat import is_platform_32bit, is_platform_windows +from pandas.compat import IS64, is_platform_windows from pandas.compat._optional import import_optional_dependency from pandas.compat.numpy import _np_version @@ -180,7 +180,7 @@ def skip_if_no(package: str, min_version: Optional[str] = None): _skip_if_no_mpl(), reason="Missing matplotlib dependency" ) skip_if_mpl = pytest.mark.skipif(not _skip_if_no_mpl(), reason="matplotlib is present") -skip_if_32bit = pytest.mark.skipif(is_platform_32bit(), reason="skipping for 32 bit") +skip_if_32bit = pytest.mark.skipif(not IS64, reason="skipping for 32 bit") skip_if_windows = pytest.mark.skipif(is_platform_windows(), reason="Running on Windows") skip_if_windows_python_3 = pytest.mark.skipif( is_platform_windows(), reason="not used on win32"
- [x] closes #36108 - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff`
https://api.github.com/repos/pandas-dev/pandas/pulls/36109
2020-09-04T05:30:05Z
2020-09-04T14:32:42Z
2020-09-04T14:32:42Z
2020-09-06T05:16:50Z
STY: de-privatize funcs imported cross-module
diff --git a/pandas/_libs/indexing.pyx b/pandas/_libs/indexing.pyx index f9aedeb8ad93e..7966fe8d4f045 100644 --- a/pandas/_libs/indexing.pyx +++ b/pandas/_libs/indexing.pyx @@ -1,4 +1,4 @@ -cdef class _NDFrameIndexerBase: +cdef class NDFrameIndexerBase: """ A base class for _NDFrameIndexer for fast instantiation and attribute access. """ diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 7478179df3b75..aeb1be121bc9e 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -771,7 +771,7 @@ class _timelex: _DATEUTIL_LEXER_SPLIT = _timelex.split -def _format_is_iso(f) -> bint: +def format_is_iso(f: str) -> bint: """ Does format match the iso8601 set that can be handled by the C parser? Generally of form YYYY-MM-DDTHH:MM:SS - date separator can be different @@ -789,7 +789,7 @@ def _format_is_iso(f) -> bint: return False -def _guess_datetime_format( +def guess_datetime_format( dt_str, bint dayfirst=False, dt_str_parse=du_parse, diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 8b2bb7832b5d0..1bea3a9eb137e 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -602,9 +602,9 @@ def astype(self, dtype, copy=True): # Rendering Methods def _format_native_types(self, na_rep="NaT", date_format=None, **kwargs): - from pandas.io.formats.format import _get_format_datetime64_from_values + from pandas.io.formats.format import get_format_datetime64_from_values - fmt = _get_format_datetime64_from_values(self, date_format) + fmt = get_format_datetime64_from_values(self, date_format) return tslib.format_array_from_datetime( self.asi8.ravel(), tz=self.tz, format=fmt, na_rep=na_rep diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 3e21d01355dda..2d694c469b3a9 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -379,14 +379,14 @@ def median( # Rendering Methods def _formatter(self, boxed=False): - from pandas.io.formats.format import _get_format_timedelta64 + from pandas.io.formats.format import get_format_timedelta64 - return _get_format_timedelta64(self, box=True) + return get_format_timedelta64(self, box=True) def _format_native_types(self, na_rep="NaT", date_format=None, **kwargs): - from pandas.io.formats.format import _get_format_timedelta64 + from pandas.io.formats.format import get_format_timedelta64 - formatter = _get_format_timedelta64(self._data, na_rep) + formatter = get_format_timedelta64(self._data, na_rep) return np.array([formatter(x) for x in self._data.ravel()]).reshape(self.shape) # ---------------------------------------------------------------- diff --git a/pandas/core/common.py b/pandas/core/common.py index 6fd4700ab7f3f..279d512e5a046 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -31,7 +31,7 @@ ABCIndexClass, ABCSeries, ) -from pandas.core.dtypes.inference import _iterable_not_string +from pandas.core.dtypes.inference import iterable_not_string from pandas.core.dtypes.missing import isna, isnull, notnull # noqa @@ -61,7 +61,7 @@ def flatten(l): flattened : generator """ for el in l: - if _iterable_not_string(el): + if iterable_not_string(el): for s in flatten(el): yield s else: diff --git a/pandas/core/computation/common.py b/pandas/core/computation/common.py index 327ec21c3c11c..8a9583c465f50 100644 --- a/pandas/core/computation/common.py +++ b/pandas/core/computation/common.py @@ -5,7 +5,7 @@ from pandas._config import get_option -def _ensure_decoded(s): +def ensure_decoded(s): """ If we have bytes, decode them to unicode. """ diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index e55df1e1d8155..b2144c45c6323 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -15,7 +15,7 @@ from pandas.core.dtypes.common import is_list_like, is_scalar import pandas.core.common as com -from pandas.core.computation.common import _ensure_decoded, result_type_many +from pandas.core.computation.common import ensure_decoded, result_type_many from pandas.core.computation.scope import _DEFAULT_GLOBALS from pandas.io.formats.printing import pprint_thing, pprint_thing_encoded @@ -466,7 +466,7 @@ def stringify(value): v = rhs.value if isinstance(v, (int, float)): v = stringify(v) - v = Timestamp(_ensure_decoded(v)) + v = Timestamp(ensure_decoded(v)) if v.tz is not None: v = v.tz_convert("UTC") self.rhs.update(v) @@ -475,7 +475,7 @@ def stringify(value): v = lhs.value if isinstance(v, (int, float)): v = stringify(v) - v = Timestamp(_ensure_decoded(v)) + v = Timestamp(ensure_decoded(v)) if v.tz is not None: v = v.tz_convert("UTC") self.lhs.update(v) diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index f1b11a6869c2b..8dd7c1a22d0ae 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -14,7 +14,7 @@ import pandas as pd import pandas.core.common as com from pandas.core.computation import expr, ops, scope as _scope -from pandas.core.computation.common import _ensure_decoded +from pandas.core.computation.common import ensure_decoded from pandas.core.computation.expr import BaseExprVisitor from pandas.core.computation.ops import UndefinedVariableError, is_term from pandas.core.construction import extract_array @@ -189,12 +189,12 @@ def stringify(value): encoder = pprint_thing return encoder(value) - kind = _ensure_decoded(self.kind) - meta = _ensure_decoded(self.meta) + kind = ensure_decoded(self.kind) + meta = ensure_decoded(self.meta) if kind == "datetime64" or kind == "datetime": if isinstance(v, (int, float)): v = stringify(v) - v = _ensure_decoded(v) + v = ensure_decoded(v) v = Timestamp(v) if v.tz is not None: v = v.tz_convert("UTC") diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 1e70ff90fcd44..3d85ddc7a9abc 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -635,8 +635,8 @@ def is_dtype_equal(source, target) -> bool: False """ try: - source = _get_dtype(source) - target = _get_dtype(target) + source = get_dtype(source) + target = get_dtype(target) return source == target except (TypeError, AttributeError): @@ -984,10 +984,10 @@ def is_datetime64_ns_dtype(arr_or_dtype) -> bool: if arr_or_dtype is None: return False try: - tipo = _get_dtype(arr_or_dtype) + tipo = get_dtype(arr_or_dtype) except TypeError: if is_datetime64tz_dtype(arr_or_dtype): - tipo = _get_dtype(arr_or_dtype.dtype) + tipo = get_dtype(arr_or_dtype.dtype) else: return False return tipo == DT64NS_DTYPE or getattr(tipo, "base", None) == DT64NS_DTYPE @@ -1372,7 +1372,7 @@ def is_bool_dtype(arr_or_dtype) -> bool: if arr_or_dtype is None: return False try: - dtype = _get_dtype(arr_or_dtype) + dtype = get_dtype(arr_or_dtype) except TypeError: return False @@ -1558,13 +1558,13 @@ def _is_dtype(arr_or_dtype, condition) -> bool: if arr_or_dtype is None: return False try: - dtype = _get_dtype(arr_or_dtype) + dtype = get_dtype(arr_or_dtype) except (TypeError, ValueError, UnicodeEncodeError): return False return condition(dtype) -def _get_dtype(arr_or_dtype) -> DtypeObj: +def get_dtype(arr_or_dtype) -> DtypeObj: """ Get the dtype instance associated with an array or dtype object. @@ -1695,7 +1695,7 @@ def infer_dtype_from_object(dtype): try: return infer_dtype_from_object(getattr(np, dtype)) except (AttributeError, TypeError): - # Handles cases like _get_dtype(int) i.e., + # Handles cases like get_dtype(int) i.e., # Python objects that are valid dtypes # (unlike user-defined types, in general) # diff --git a/pandas/core/dtypes/inference.py b/pandas/core/dtypes/inference.py index d1607b5ede6c3..329c4445b05bc 100644 --- a/pandas/core/dtypes/inference.py +++ b/pandas/core/dtypes/inference.py @@ -68,7 +68,7 @@ def is_number(obj) -> bool: return isinstance(obj, (Number, np.number)) -def _iterable_not_string(obj) -> bool: +def iterable_not_string(obj) -> bool: """ Check if the object is an iterable but not a string. @@ -83,11 +83,11 @@ def _iterable_not_string(obj) -> bool: Examples -------- - >>> _iterable_not_string([1, 2, 3]) + >>> iterable_not_string([1, 2, 3]) True - >>> _iterable_not_string("foo") + >>> iterable_not_string("foo") False - >>> _iterable_not_string(1) + >>> iterable_not_string(1) False """ return isinstance(obj, abc.Iterable) and not isinstance(obj, str) diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index f59bb31af2828..163500525dbd8 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -338,7 +338,7 @@ def notna(obj): notnull = notna -def _isna_compat(arr, fill_value=np.nan) -> bool: +def isna_compat(arr, fill_value=np.nan) -> bool: """ Parameters ---------- @@ -496,7 +496,7 @@ def array_equals(left: ArrayLike, right: ArrayLike) -> bool: return array_equivalent(left, right, dtype_equal=True) -def _infer_fill_value(val): +def infer_fill_value(val): """ infer the fill value for the nan/NaT from the provided scalar/ndarray/list-like if we are a NaT, return the correct dtyped @@ -516,11 +516,11 @@ def _infer_fill_value(val): return np.nan -def _maybe_fill(arr, fill_value=np.nan): +def maybe_fill(arr, fill_value=np.nan): """ if we have a compatible fill_value and arr dtype, then fill """ - if _isna_compat(arr, fill_value): + if isna_compat(arr, fill_value): arr.fill(fill_value) return arr diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 4dd5b7f30e7f0..c076b6e2e181b 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -37,7 +37,7 @@ is_timedelta64_dtype, needs_i8_conversion, ) -from pandas.core.dtypes.missing import _maybe_fill, isna +from pandas.core.dtypes.missing import isna, maybe_fill import pandas.core.algorithms as algorithms from pandas.core.base import SelectionMixin @@ -524,13 +524,11 @@ def _cython_operation( codes, _, _ = self.group_info if kind == "aggregate": - result = _maybe_fill( - np.empty(out_shape, dtype=out_dtype), fill_value=np.nan - ) + result = maybe_fill(np.empty(out_shape, dtype=out_dtype), fill_value=np.nan) counts = np.zeros(self.ngroups, dtype=np.int64) result = self._aggregate(result, counts, values, codes, func, min_count) elif kind == "transform": - result = _maybe_fill( + result = maybe_fill( np.empty_like(values, dtype=out_dtype), fill_value=np.nan ) diff --git a/pandas/core/indexes/timedeltas.py b/pandas/core/indexes/timedeltas.py index dccc8369c5366..85c8396dfd1fe 100644 --- a/pandas/core/indexes/timedeltas.py +++ b/pandas/core/indexes/timedeltas.py @@ -177,9 +177,9 @@ def _simple_new(cls, values: TimedeltaArray, name: Label = None): @property def _formatter_func(self): - from pandas.io.formats.format import _get_format_timedelta64 + from pandas.io.formats.format import get_format_timedelta64 - return _get_format_timedelta64(self, box=True) + return get_format_timedelta64(self, box=True) # ------------------------------------------------------------------- diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index dd81823055390..cfb17b9498a36 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -4,7 +4,7 @@ from pandas._config.config import option_context -from pandas._libs.indexing import _NDFrameIndexerBase +from pandas._libs.indexing import NDFrameIndexerBase from pandas._libs.lib import item_from_zerodim from pandas.errors import AbstractMethodError, InvalidIndexError from pandas.util._decorators import doc @@ -22,7 +22,7 @@ ) from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes.generic import ABCDataFrame, ABCMultiIndex, ABCSeries -from pandas.core.dtypes.missing import _infer_fill_value, isna +from pandas.core.dtypes.missing import infer_fill_value, isna import pandas.core.common as com from pandas.core.construction import array as pd_array @@ -583,7 +583,7 @@ def iat(self) -> "_iAtIndexer": return _iAtIndexer("iat", self) -class _LocationIndexer(_NDFrameIndexerBase): +class _LocationIndexer(NDFrameIndexerBase): _valid_types: str axis = None @@ -1604,7 +1604,7 @@ def _setitem_with_indexer(self, indexer, value): return # add a new item with the dtype setup - self.obj[key] = _infer_fill_value(value) + self.obj[key] = infer_fill_value(value) new_indexer = convert_from_missing_indexer_tuple( indexer, self.obj.axes @@ -2017,7 +2017,7 @@ def _align_frame(self, indexer, df: ABCDataFrame): raise ValueError("Incompatible indexer with DataFrame") -class _ScalarAccessIndexer(_NDFrameIndexerBase): +class _ScalarAccessIndexer(NDFrameIndexerBase): """ Access scalars quickly. """ diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index ad388ef3f53b0..b2305736f9d46 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -56,7 +56,7 @@ ABCPandasArray, ABCSeries, ) -from pandas.core.dtypes.missing import _isna_compat, is_valid_nat_for_dtype, isna +from pandas.core.dtypes.missing import is_valid_nat_for_dtype, isna, isna_compat import pandas.core.algorithms as algos from pandas.core.array_algos.transforms import shift @@ -487,7 +487,7 @@ def _maybe_downcast(self, blocks: List["Block"], downcast=None) -> List["Block"] ): return blocks - return _extend_blocks([b.downcast(downcast) for b in blocks]) + return extend_blocks([b.downcast(downcast) for b in blocks]) def downcast(self, dtypes=None): """ try to downcast each item to the dict of dtypes if present """ @@ -2474,7 +2474,7 @@ def _maybe_downcast(self, blocks: List["Block"], downcast=None) -> List["Block"] return blocks # split and convert the blocks - return _extend_blocks([b.convert(datetime=True, numeric=False) for b in blocks]) + return extend_blocks([b.convert(datetime=True, numeric=False) for b in blocks]) def _can_hold_element(self, element: Any) -> bool: return True @@ -2503,7 +2503,7 @@ def replace(self, to_replace, value, inplace=False, regex=False, convert=True): result = b._replace_single( to_rep, v, inplace=inplace, regex=regex, convert=convert ) - result_blocks = _extend_blocks(result, result_blocks) + result_blocks = extend_blocks(result, result_blocks) blocks = result_blocks return result_blocks @@ -2514,7 +2514,7 @@ def replace(self, to_replace, value, inplace=False, regex=False, convert=True): result = b._replace_single( to_rep, value, inplace=inplace, regex=regex, convert=convert ) - result_blocks = _extend_blocks(result, result_blocks) + result_blocks = extend_blocks(result, result_blocks) blocks = result_blocks return result_blocks @@ -2769,7 +2769,7 @@ def make_block(values, placement, klass=None, ndim=None, dtype=None): # ----------------------------------------------------------------- -def _extend_blocks(result, blocks=None): +def extend_blocks(result, blocks=None): """ return a new extended blocks, given the result """ if blocks is None: blocks = [] @@ -2860,7 +2860,7 @@ def _putmask_smart(v: np.ndarray, mask: np.ndarray, n) -> np.ndarray: else: # make sure that we have a nullable type # if we have nulls - if not _isna_compat(v, nn[0]): + if not isna_compat(v, nn[0]): pass elif not (is_float_dtype(nn.dtype) or is_integer_dtype(nn.dtype)): # only compare integers/floats diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 88839d2211f81..b45f0890cafa4 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -10,7 +10,7 @@ from pandas.core.dtypes.cast import maybe_promote from pandas.core.dtypes.common import ( - _get_dtype, + get_dtype, is_categorical_dtype, is_datetime64_dtype, is_datetime64tz_dtype, @@ -200,7 +200,7 @@ def dtype(self): if not self.needs_filling: return self.block.dtype else: - return _get_dtype(maybe_promote(self.block.dtype, self.block.fill_value)[0]) + return get_dtype(maybe_promote(self.block.dtype, self.block.fill_value)[0]) @cache_readonly def is_na(self): diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 2e3098d94afcb..753b949f7c802 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -54,8 +54,8 @@ DatetimeTZBlock, ExtensionBlock, ObjectValuesExtensionBlock, - _extend_blocks, _safe_reshape, + extend_blocks, get_block_type, make_block, ) @@ -406,7 +406,7 @@ def apply( if not ignore_failures: raise continue - result_blocks = _extend_blocks(applied, result_blocks) + result_blocks = extend_blocks(applied, result_blocks) if ignore_failures: return self._combine(result_blocks) @@ -1868,7 +1868,7 @@ def _consolidate(blocks): merged_blocks = _merge_blocks( list(group_blocks), dtype=dtype, can_consolidate=_can_consolidate ) - new_blocks = _extend_blocks(merged_blocks, new_blocks) + new_blocks = extend_blocks(merged_blocks, new_blocks) return new_blocks diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index e3f16a3ef4f90..6fdde22a1c514 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -13,7 +13,7 @@ from pandas.core.dtypes.cast import _int64_max, maybe_upcast_putmask from pandas.core.dtypes.common import ( - _get_dtype, + get_dtype, is_any_int_dtype, is_bool_dtype, is_complex, @@ -678,7 +678,7 @@ def _get_counts_nanvar( count : scalar or array d : scalar or array """ - dtype = _get_dtype(dtype) + dtype = get_dtype(dtype) count = _get_counts(value_counts, mask, axis, dtype=dtype) d = count - dtype.type(ddof) @@ -1234,7 +1234,7 @@ def _get_counts( ------- count : scalar or array """ - dtype = _get_dtype(dtype) + dtype = get_dtype(dtype) if axis is None: if mask is not None: n = mask.size - mask.sum() diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 8724f7674f0c8..33ce5ed49b9c2 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -14,7 +14,7 @@ import pandas.core.common as com from pandas.core.indexes.api import Index, MultiIndex from pandas.core.reshape.concat import concat -from pandas.core.reshape.util import _tile_compat +from pandas.core.reshape.util import tile_compat from pandas.core.shared_docs import _shared_docs from pandas.core.tools.numeric import to_numeric @@ -136,7 +136,7 @@ def melt( result = frame._constructor(mdata, columns=mcolumns) if not ignore_index: - result.index = _tile_compat(frame.index, K) + result.index = tile_compat(frame.index, K) return result diff --git a/pandas/core/reshape/util.py b/pandas/core/reshape/util.py index 6949270317f7c..a1bf3f8ee4119 100644 --- a/pandas/core/reshape/util.py +++ b/pandas/core/reshape/util.py @@ -48,10 +48,10 @@ def cartesian_product(X): # if any factor is empty, the cartesian product is empty b = np.zeros_like(cumprodX) - return [_tile_compat(np.repeat(x, b[i]), np.product(a[i])) for i, x in enumerate(X)] + return [tile_compat(np.repeat(x, b[i]), np.product(a[i])) for i, x in enumerate(X)] -def _tile_compat(arr, num: int): +def tile_compat(arr, num: int): """ Index compat for np.tile. diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 8fcc5f74ea897..09a53d5a10ae6 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -20,8 +20,8 @@ from pandas._libs.tslibs import Timestamp, conversion, parsing from pandas._libs.tslibs.parsing import ( # noqa DateParseError, - _format_is_iso, - _guess_datetime_format, + format_is_iso, + guess_datetime_format, ) from pandas._libs.tslibs.strptime import array_strptime from pandas._typing import ArrayLike, Label, Timezone @@ -73,7 +73,7 @@ def _guess_datetime_format_for_array(arr, **kwargs): # Try to guess the format based on the first non-NaN element non_nan_elements = notna(arr).nonzero()[0] if len(non_nan_elements): - return _guess_datetime_format(arr[non_nan_elements[0]], **kwargs) + return guess_datetime_format(arr[non_nan_elements[0]], **kwargs) def should_cache( @@ -387,7 +387,7 @@ def _convert_listlike_datetimes( # datetime strings, so in those cases don't use the inferred # format because this path makes process slower in this # special case - format_is_iso8601 = _format_is_iso(format) + format_is_iso8601 = format_is_iso(format) if format_is_iso8601: require_iso8601 = not infer_datetime_format format = None diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 461ef6823918e..3d441f6e737bc 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1473,7 +1473,7 @@ def _format_strings(self) -> List[str]: fmt_values = format_array_from_datetime( values.asi8.ravel(), - format=_get_format_datetime64_from_values(values, self.date_format), + format=get_format_datetime64_from_values(values, self.date_format), na_rep=self.nat_rep, ).reshape(values.shape) return fmt_values.tolist() @@ -1636,7 +1636,7 @@ def _get_format_datetime64( return lambda x, tz=None: _format_datetime64(x, tz=tz, nat_rep=nat_rep) -def _get_format_datetime64_from_values( +def get_format_datetime64_from_values( values: Union[np.ndarray, DatetimeArray, DatetimeIndex], date_format: Optional[str] ) -> Optional[str]: """ given values and a date_format, return a string format """ @@ -1677,13 +1677,13 @@ def __init__( self.box = box def _format_strings(self) -> List[str]: - formatter = self.formatter or _get_format_timedelta64( + formatter = self.formatter or get_format_timedelta64( self.values, nat_rep=self.nat_rep, box=self.box ) return [formatter(x) for x in self.values] -def _get_format_timedelta64( +def get_format_timedelta64( values: Union[np.ndarray, TimedeltaIndex, TimedeltaArray], nat_rep: str = "NaT", box: bool = False, diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index a6c526fcb008a..2db9a9a403e1c 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -649,8 +649,8 @@ def test_is_complex_dtype(): (IntervalDtype(), IntervalDtype()), ], ) -def test__get_dtype(input_param, result): - assert com._get_dtype(input_param) == result +def test_get_dtype(input_param, result): + assert com.get_dtype(input_param) == result @pytest.mark.parametrize( @@ -664,12 +664,12 @@ def test__get_dtype(input_param, result): (pd.DataFrame([1, 2]), "data type not understood"), ], ) -def test__get_dtype_fails(input_param, expected_error_message): +def test_get_dtype_fails(input_param, expected_error_message): # python objects # 2020-02-02 npdev changed error message expected_error_message += f"|Cannot interpret '{input_param}' as a data type" with pytest.raises(TypeError, match=expected_error_message): - com._get_dtype(input_param) + com.get_dtype(input_param) @pytest.mark.parametrize( diff --git a/pandas/tests/tslibs/test_parsing.py b/pandas/tests/tslibs/test_parsing.py index dc7421ea63464..70fa724464226 100644 --- a/pandas/tests/tslibs/test_parsing.py +++ b/pandas/tests/tslibs/test_parsing.py @@ -148,14 +148,14 @@ def test_parsers_month_freq(date_str, expected): ], ) def test_guess_datetime_format_with_parseable_formats(string, fmt): - result = parsing._guess_datetime_format(string) + result = parsing.guess_datetime_format(string) assert result == fmt @pytest.mark.parametrize("dayfirst,expected", [(True, "%d/%m/%Y"), (False, "%m/%d/%Y")]) def test_guess_datetime_format_with_dayfirst(dayfirst, expected): ambiguous_string = "01/01/2011" - result = parsing._guess_datetime_format(ambiguous_string, dayfirst=dayfirst) + result = parsing.guess_datetime_format(ambiguous_string, dayfirst=dayfirst) assert result == expected @@ -169,7 +169,7 @@ def test_guess_datetime_format_with_dayfirst(dayfirst, expected): ], ) def test_guess_datetime_format_with_locale_specific_formats(string, fmt): - result = parsing._guess_datetime_format(string) + result = parsing.guess_datetime_format(string) assert result == fmt @@ -189,7 +189,7 @@ def test_guess_datetime_format_with_locale_specific_formats(string, fmt): def test_guess_datetime_format_invalid_inputs(invalid_dt): # A datetime string must include a year, month and a day for it to be # guessable, in addition to being a string that looks like a datetime. - assert parsing._guess_datetime_format(invalid_dt) is None + assert parsing.guess_datetime_format(invalid_dt) is None @pytest.mark.parametrize( @@ -205,7 +205,7 @@ def test_guess_datetime_format_invalid_inputs(invalid_dt): ) def test_guess_datetime_format_no_padding(string, fmt): # see gh-11142 - result = parsing._guess_datetime_format(string) + result = parsing.guess_datetime_format(string) assert result == fmt
https://api.github.com/repos/pandas-dev/pandas/pulls/36107
2020-09-04T03:15:36Z
2020-09-04T20:51:22Z
2020-09-04T20:51:22Z
2020-09-04T20:53:46Z
BUG: DataFrame.any with axis=1 and bool_only=True
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 2aac2596c18cb..ba556c8dcca54 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -246,6 +246,7 @@ Timezones Numeric ^^^^^^^ - Bug in :func:`to_numeric` where float precision was incorrect (:issue:`31364`) +- Bug in :meth:`DataFrame.any` with ``axis=1`` and ``bool_only=True`` ignoring the ``bool_only`` keyword (:issue:`32432`) - Conversion diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 59cf4c0e2f81d..3eed10917843b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -8639,15 +8639,12 @@ def func(values): else: return op(values, axis=axis, skipna=skipna, **kwds) - def _get_data(axis_matters: bool) -> DataFrame: + def _get_data() -> DataFrame: if filter_type is None: data = self._get_numeric_data() elif filter_type == "bool": - if axis_matters: - # GH#25101, GH#24434 - data = self._get_bool_data() if axis == 0 else self - else: - data = self._get_bool_data() + # GH#25101, GH#24434 + data = self._get_bool_data() else: # pragma: no cover msg = ( f"Generating numeric_only data with filter_type {filter_type} " @@ -8659,7 +8656,7 @@ def _get_data(axis_matters: bool) -> DataFrame: if numeric_only is not None: df = self if numeric_only is True: - df = _get_data(axis_matters=True) + df = _get_data() if axis == 1: df = df.T axis = 0 @@ -8720,8 +8717,7 @@ def blk_func(values): except TypeError: # e.g. in nanops trying to convert strs to float - # TODO: why doesnt axis matter here? - data = _get_data(axis_matters=False) + data = _get_data() labels = data._get_agg_axis(axis) values = data.values diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index a112bc80b60b0..bbf2d9f1f0784 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -914,6 +914,13 @@ def test_all_any_boolean(self): tm.assert_series_equal(s.all(level=0), Series([False, True, False])) tm.assert_series_equal(s.any(level=0), Series([False, True, True])) + def test_any_axis1_bool_only(self): + # GH#32432 + df = pd.DataFrame({"A": [True, False], "B": [1, 2]}) + result = df.any(axis=1, bool_only=True) + expected = pd.Series([True, False]) + tm.assert_series_equal(result, expected) + def test_timedelta64_analytics(self): # index min/max
- [x] closes #32432 - [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/36106
2020-09-04T02:55:33Z
2020-09-11T01:11:44Z
2020-09-11T01:11:44Z
2020-09-11T01:20:21Z
STY: De-privatize functions in io.excel imported elsewhere
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 9bc1d7fedcb31..74eb65521f5b2 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -24,11 +24,11 @@ validate_header_arg, ) from pandas.io.excel._util import ( - _fill_mi_header, - _get_default_writer, - _maybe_convert_usecols, - _pop_header_name, + fill_mi_header, + get_default_writer, get_writer, + maybe_convert_usecols, + pop_header_name, ) from pandas.io.parsers import TextParser @@ -454,7 +454,7 @@ def parse( sheet = self.get_sheet_by_index(asheetname) data = self.get_sheet_data(sheet, convert_float) - usecols = _maybe_convert_usecols(usecols) + usecols = maybe_convert_usecols(usecols) if not data: output[asheetname] = DataFrame() @@ -473,10 +473,10 @@ def parse( if is_integer(skiprows): row += skiprows - data[row], control_row = _fill_mi_header(data[row], control_row) + data[row], control_row = fill_mi_header(data[row], control_row) if index_col is not None: - header_name, _ = _pop_header_name(data[row], index_col) + header_name, _ = pop_header_name(data[row], index_col) header_names.append(header_name) if is_list_like(index_col): @@ -645,7 +645,7 @@ def __new__(cls, path, engine=None, **kwargs): try: engine = config.get_option(f"io.excel.{ext}.writer") if engine == "auto": - engine = _get_default_writer(ext) + engine = get_default_writer(ext) except KeyError as err: raise ValueError(f"No engine for filetype: '{ext}'") from err cls = get_writer(engine) diff --git a/pandas/io/excel/_odswriter.py b/pandas/io/excel/_odswriter.py index f39391ae1fe7f..e7684012c1d4c 100644 --- a/pandas/io/excel/_odswriter.py +++ b/pandas/io/excel/_odswriter.py @@ -5,7 +5,7 @@ import pandas._libs.json as json from pandas.io.excel._base import ExcelWriter -from pandas.io.excel._util import _validate_freeze_panes +from pandas.io.excel._util import validate_freeze_panes from pandas.io.formats.excel import ExcelCell @@ -59,7 +59,7 @@ def write_cells( wks = Table(name=sheet_name) self.sheets[sheet_name] = wks - if _validate_freeze_panes(freeze_panes): + if validate_freeze_panes(freeze_panes): assert freeze_panes is not None self._create_freeze_panes(sheet_name, freeze_panes) diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py index 3c67902d41baa..89b581da6ed31 100644 --- a/pandas/io/excel/_openpyxl.py +++ b/pandas/io/excel/_openpyxl.py @@ -6,7 +6,7 @@ from pandas.compat._optional import import_optional_dependency from pandas.io.excel._base import ExcelWriter, _BaseExcelReader -from pandas.io.excel._util import _validate_freeze_panes +from pandas.io.excel._util import validate_freeze_panes if TYPE_CHECKING: from openpyxl.descriptors.serialisable import Serialisable @@ -385,7 +385,7 @@ def write_cells( wks.title = sheet_name self.sheets[sheet_name] = wks - if _validate_freeze_panes(freeze_panes): + if validate_freeze_panes(freeze_panes): wks.freeze_panes = wks.cell( row=freeze_panes[0] + 1, column=freeze_panes[1] + 1 ) diff --git a/pandas/io/excel/_util.py b/pandas/io/excel/_util.py index 285aeaf7d4c6e..0d67e6cd2f32b 100644 --- a/pandas/io/excel/_util.py +++ b/pandas/io/excel/_util.py @@ -21,7 +21,7 @@ def register_writer(klass): _writers[engine_name] = klass -def _get_default_writer(ext): +def get_default_writer(ext): """ Return the default writer for the given extension. @@ -121,7 +121,7 @@ def _range2cols(areas): return cols -def _maybe_convert_usecols(usecols): +def maybe_convert_usecols(usecols): """ Convert `usecols` into a compatible format for parsing in `parsers.py`. @@ -150,7 +150,7 @@ def _maybe_convert_usecols(usecols): return usecols -def _validate_freeze_panes(freeze_panes): +def validate_freeze_panes(freeze_panes): if freeze_panes is not None: if len(freeze_panes) == 2 and all( isinstance(item, int) for item in freeze_panes @@ -167,15 +167,7 @@ def _validate_freeze_panes(freeze_panes): return False -def _trim_excel_header(row): - # trim header row so auto-index inference works - # xlrd uses '' , openpyxl None - while len(row) > 0 and (row[0] == "" or row[0] is None): - row = row[1:] - return row - - -def _fill_mi_header(row, control_row): +def fill_mi_header(row, control_row): """ Forward fill blank entries in row but only inside the same parent index. @@ -208,7 +200,7 @@ def _fill_mi_header(row, control_row): return row, control_row -def _pop_header_name(row, index_col): +def pop_header_name(row, index_col): """ Pop the header name for MultiIndex parsing. diff --git a/pandas/io/excel/_xlsxwriter.py b/pandas/io/excel/_xlsxwriter.py index bdbb006ae93dc..53f0c94d12e4c 100644 --- a/pandas/io/excel/_xlsxwriter.py +++ b/pandas/io/excel/_xlsxwriter.py @@ -3,7 +3,7 @@ import pandas._libs.json as json from pandas.io.excel._base import ExcelWriter -from pandas.io.excel._util import _validate_freeze_panes +from pandas.io.excel._util import validate_freeze_panes class _XlsxStyler: @@ -208,7 +208,7 @@ def write_cells( style_dict = {"null": None} - if _validate_freeze_panes(freeze_panes): + if validate_freeze_panes(freeze_panes): wks.freeze_panes(*(freeze_panes)) for cell in cells: diff --git a/pandas/io/excel/_xlwt.py b/pandas/io/excel/_xlwt.py index e1f72eb533c51..faebe526d17bd 100644 --- a/pandas/io/excel/_xlwt.py +++ b/pandas/io/excel/_xlwt.py @@ -3,7 +3,7 @@ import pandas._libs.json as json from pandas.io.excel._base import ExcelWriter -from pandas.io.excel._util import _validate_freeze_panes +from pandas.io.excel._util import validate_freeze_panes if TYPE_CHECKING: from xlwt import XFStyle @@ -48,7 +48,7 @@ def write_cells( wks = self.book.add_sheet(sheet_name) self.sheets[sheet_name] = wks - if _validate_freeze_panes(freeze_panes): + if validate_freeze_panes(freeze_panes): wks.set_panes_frozen(True) wks.set_horz_split_pos(freeze_panes[0]) wks.set_vert_split_pos(freeze_panes[1])
xref #36055
https://api.github.com/repos/pandas-dev/pandas/pulls/36104
2020-09-04T01:09:10Z
2020-09-04T20:52:14Z
2020-09-04T20:52:14Z
2020-09-04T20:56:48Z
CLN removing trailing commas
diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index a7e3162ed7b73..1edcc937f72c3 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -2349,9 +2349,6 @@ def date_format(dt): def format_query(sql, *args): - """ - - """ processed_args = [] for arg in args: if isinstance(arg, float) and isna(arg): diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 6d7fec803a8e0..88f61390957a6 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -1153,7 +1153,7 @@ def test_read_chunks_117( from_frame = parsed.iloc[pos : pos + chunksize, :].copy() from_frame = self._convert_categorical(from_frame) tm.assert_frame_equal( - from_frame, chunk, check_dtype=False, check_datetimelike_compat=True, + from_frame, chunk, check_dtype=False, check_datetimelike_compat=True ) pos += chunksize @@ -1251,7 +1251,7 @@ def test_read_chunks_115( from_frame = parsed.iloc[pos : pos + chunksize, :].copy() from_frame = self._convert_categorical(from_frame) tm.assert_frame_equal( - from_frame, chunk, check_dtype=False, check_datetimelike_compat=True, + from_frame, chunk, check_dtype=False, check_datetimelike_compat=True ) pos += chunksize diff --git a/pandas/tests/plotting/test_frame.py b/pandas/tests/plotting/test_frame.py index 9ab697cb57690..128a7bdb6730a 100644 --- a/pandas/tests/plotting/test_frame.py +++ b/pandas/tests/plotting/test_frame.py @@ -1321,7 +1321,7 @@ def test_scatter_with_c_column_name_with_colors(self, cmap): def test_plot_scatter_with_s(self): # this refers to GH 32904 - df = DataFrame(np.random.random((10, 3)) * 100, columns=["a", "b", "c"],) + df = DataFrame(np.random.random((10, 3)) * 100, columns=["a", "b", "c"]) ax = df.plot.scatter(x="a", y="b", s="c") tm.assert_numpy_array_equal(df["c"].values, right=ax.collections[0].get_sizes()) @@ -1716,7 +1716,7 @@ def test_hist_df(self): def test_hist_weights(self, weights): # GH 33173 np.random.seed(0) - df = pd.DataFrame(dict(zip(["A", "B"], np.random.randn(2, 100,)))) + df = pd.DataFrame(dict(zip(["A", "B"], np.random.randn(2, 100)))) ax1 = _check_plot_works(df.plot, kind="hist", weights=weights) ax2 = _check_plot_works(df.plot, kind="hist") diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index e7637a598403f..59a0183304c76 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -124,7 +124,7 @@ def test_resample_integerarray(): result = ts.resample("3T").mean() expected = Series( - [1, 4, 7], index=pd.date_range("1/1/2000", periods=3, freq="3T"), dtype="Int64", + [1, 4, 7], index=pd.date_range("1/1/2000", periods=3, freq="3T"), dtype="Int64" ) tm.assert_series_equal(result, expected) @@ -764,7 +764,7 @@ def test_resample_origin(): @pytest.mark.parametrize( - "origin", ["invalid_value", "epch", "startday", "startt", "2000-30-30", object()], + "origin", ["invalid_value", "epch", "startday", "startt", "2000-30-30", object()] ) def test_resample_bad_origin(origin): rng = date_range("2000-01-01 00:00:00", "2000-01-01 02:00", freq="s") @@ -777,9 +777,7 @@ def test_resample_bad_origin(origin): ts.resample("5min", origin=origin) -@pytest.mark.parametrize( - "offset", ["invalid_value", "12dayys", "2000-30-30", object()], -) +@pytest.mark.parametrize("offset", ["invalid_value", "12dayys", "2000-30-30", object()]) def test_resample_bad_offset(offset): rng = date_range("2000-01-01 00:00:00", "2000-01-01 02:00", freq="s") ts = Series(np.random.randn(len(rng)), index=rng) @@ -1595,7 +1593,7 @@ def test_downsample_dst_at_midnight(): "America/Havana", ambiguous=True ) dti = pd.DatetimeIndex(dti, freq="D") - expected = DataFrame([7.5, 28.0, 44.5], index=dti,) + expected = DataFrame([7.5, 28.0, 44.5], index=dti) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/reshape/merge/test_merge_index_as_string.py b/pandas/tests/reshape/merge/test_merge_index_as_string.py index 08614d04caf4b..d20d93370ec7e 100644 --- a/pandas/tests/reshape/merge/test_merge_index_as_string.py +++ b/pandas/tests/reshape/merge/test_merge_index_as_string.py @@ -29,7 +29,7 @@ def df2(): @pytest.fixture(params=[[], ["outer"], ["outer", "inner"]]) def left_df(request, df1): - """ Construct left test DataFrame with specified levels + """Construct left test DataFrame with specified levels (any of 'outer', 'inner', and 'v1') """ levels = request.param @@ -41,7 +41,7 @@ def left_df(request, df1): @pytest.fixture(params=[[], ["outer"], ["outer", "inner"]]) def right_df(request, df2): - """ Construct right test DataFrame with specified levels + """Construct right test DataFrame with specified levels (any of 'outer', 'inner', and 'v2') """ levels = request.param diff --git a/pandas/tests/reshape/test_crosstab.py b/pandas/tests/reshape/test_crosstab.py index 6f5550a6f8209..1aadcfdc30f1b 100644 --- a/pandas/tests/reshape/test_crosstab.py +++ b/pandas/tests/reshape/test_crosstab.py @@ -354,7 +354,7 @@ def test_crosstab_normalize(self): crosstab(df.a, df.b, normalize="columns"), ) tm.assert_frame_equal( - crosstab(df.a, df.b, normalize=0), crosstab(df.a, df.b, normalize="index"), + crosstab(df.a, df.b, normalize=0), crosstab(df.a, df.b, normalize="index") ) row_normal_margins = DataFrame( @@ -377,7 +377,7 @@ def test_crosstab_normalize(self): crosstab(df.a, df.b, normalize="index", margins=True), row_normal_margins ) tm.assert_frame_equal( - crosstab(df.a, df.b, normalize="columns", margins=True), col_normal_margins, + crosstab(df.a, df.b, normalize="columns", margins=True), col_normal_margins ) tm.assert_frame_equal( crosstab(df.a, df.b, normalize=True, margins=True), all_normal_margins diff --git a/pandas/tests/reshape/test_get_dummies.py b/pandas/tests/reshape/test_get_dummies.py index c003bfa6a239a..ce13762ea8f86 100644 --- a/pandas/tests/reshape/test_get_dummies.py +++ b/pandas/tests/reshape/test_get_dummies.py @@ -161,7 +161,7 @@ def test_get_dummies_unicode(self, sparse): s = [e, eacute, eacute] res = get_dummies(s, prefix="letter", sparse=sparse) exp = DataFrame( - {"letter_e": [1, 0, 0], f"letter_{eacute}": [0, 1, 1]}, dtype=np.uint8, + {"letter_e": [1, 0, 0], f"letter_{eacute}": [0, 1, 1]}, dtype=np.uint8 ) if sparse: exp = exp.apply(SparseArray, fill_value=0)
This PR is related to #35925, both current and new versions of black passes these formatting, also I'd like to mention that there seem to be a reported [bug](https://github.com/psf/black/issues/1629) in newer version of black which throws error after removing trailing comma from `pandas/tests/scalar/timestamp/test_constructors.py` that's why I didn't change this formatting. ```diff diff --git a/pandas/tests/scalar/timestamp/test_constructors.py b/pandas/tests/scalar/timestamp/test_constructors.py index 316a299ba..c70eacdfa 100644 --- a/pandas/tests/scalar/timestamp/test_constructors.py +++ b/pandas/tests/scalar/timestamp/test_constructors.py @@ -267,7 +267,7 @@ class TestTimestampConstructors: hour=1, minute=2, second=3, - microsecond=999999, + microsecond=999999 ) ) == repr(Timestamp("2015-11-12 01:02:03.999999")) ~ ``` The workaround to this is after removing trailing comma from above code run black with --fast which will add trailing comma back again and and will not format afterwards on re-running black without --fast
https://api.github.com/repos/pandas-dev/pandas/pulls/36101
2020-09-03T19:56:42Z
2020-09-05T12:39:12Z
2020-09-05T12:39:12Z
2020-09-05T12:39:23Z
TYP: misc fixes for numpy types 2
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index e6b4cb598989b..1489e08d82bf0 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -651,7 +651,7 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj, If False, scalar belongs to pandas extension types is inferred as object """ - dtype = np.dtype(object) + dtype: DtypeObj = np.dtype(object) # a 1-element ndarray if isinstance(val, np.ndarray): diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 1e70ff90fcd44..0bf032725547e 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -108,7 +108,7 @@ def ensure_str(value: Union[bytes, Any]) -> str: return value -def ensure_int_or_float(arr: ArrayLike, copy: bool = False) -> np.array: +def ensure_int_or_float(arr: ArrayLike, copy: bool = False) -> np.ndarray: """ Ensure that an dtype array of some integer dtype has an int64 dtype if possible. @@ -1388,8 +1388,7 @@ def is_bool_dtype(arr_or_dtype) -> bool: # guess this return arr_or_dtype.is_object and arr_or_dtype.inferred_type == "boolean" elif is_extension_array_dtype(arr_or_dtype): - dtype = getattr(arr_or_dtype, "dtype", arr_or_dtype) - return dtype._is_boolean + return getattr(arr_or_dtype, "dtype", arr_or_dtype)._is_boolean return issubclass(dtype.type, np.bool_) diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 01e20f49917ac..602ff226f8878 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -1870,7 +1870,7 @@ def _right_outer_join(x, y, max_groups): def _factorize_keys( lk: ArrayLike, rk: ArrayLike, sort: bool = True, how: str = "inner" -) -> Tuple[np.array, np.array, int]: +) -> Tuple[np.ndarray, np.ndarray, int]: """ Encode left and right keys as enumerated types.
``` pandas\core\dtypes\cast.py:681: error: Incompatible types in assignment (expression has type "DatetimeTZDtype", variable has type "dtype") [assignment] pandas\core\dtypes\cast.py:715: error: Incompatible types in assignment (expression has type "IntervalDtype", variable has type "dtype") [assignment] pandas\core\dtypes\common.py:1392: error: Item "dtype" of "Union[dtype, ExtensionDtype]" has no attribute "_is_boolean" [union-attr] pandas\core\dtypes\common.py:111: error: Function "numpy.array" is not valid as a type [valid-type] pandas\core\reshape\merge.py:1873: error: Function "numpy.array" is not valid as a type [valid-type] ```
https://api.github.com/repos/pandas-dev/pandas/pulls/36099
2020-09-03T18:37:42Z
2020-09-04T17:03:46Z
2020-09-04T17:03:46Z
2020-09-04T17:05:36Z
TYP: misc fixes for numpy types
diff --git a/pandas/_typing.py b/pandas/_typing.py index f8af92e07c674..74bfc9134c3af 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -62,7 +62,7 @@ # other Dtype = Union[ - "ExtensionDtype", str, np.dtype, Type[Union[str, float, int, complex, bool]] + "ExtensionDtype", str, np.dtype, Type[Union[str, float, int, complex, bool, object]] ] DtypeObj = Union[np.dtype, "ExtensionDtype"] FilePathOrBuffer = Union[str, Path, IO[AnyStr], IOBase] diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 9d75d21c5637a..f297c7165208f 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -6,7 +6,7 @@ import operator from textwrap import dedent -from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union +from typing import TYPE_CHECKING, Dict, Optional, Tuple, Union, cast from warnings import catch_warnings, simplefilter, warn import numpy as np @@ -60,7 +60,7 @@ from pandas.core.indexers import validate_indices if TYPE_CHECKING: - from pandas import DataFrame, Series + from pandas import Categorical, DataFrame, Series _shared_docs: Dict[str, str] = {} @@ -429,8 +429,7 @@ def isin(comps: AnyArrayLike, values: AnyArrayLike) -> np.ndarray: if is_categorical_dtype(comps): # TODO(extension) # handle categoricals - # error: "ExtensionArray" has no attribute "isin" [attr-defined] - return comps.isin(values) # type: ignore[attr-defined] + return cast("Categorical", comps).isin(values) comps, dtype = _ensure_data(comps) values, _ = _ensure_data(values, dtype=dtype) diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 27b1afdb438cb..ec85ec47d625c 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -2316,7 +2316,7 @@ def _concat_same_type(self, to_concat): return union_categoricals(to_concat) - def isin(self, values): + def isin(self, values) -> np.ndarray: """ Check whether `values` are contained in Categorical. diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 02b8ed17244cd..9d6c2789af25b 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -335,7 +335,7 @@ def array( return result -def extract_array(obj, extract_numpy: bool = False): +def extract_array(obj: AnyArrayLike, extract_numpy: bool = False) -> ArrayLike: """ Extract the ndarray or ExtensionArray from a Series or Index. @@ -383,7 +383,9 @@ def extract_array(obj, extract_numpy: bool = False): if extract_numpy and isinstance(obj, ABCPandasArray): obj = obj.to_numpy() - return obj + # error: Incompatible return value type (got "Index", expected "ExtensionArray") + # error: Incompatible return value type (got "Series", expected "ExtensionArray") + return obj # type: ignore[return-value] def sanitize_array( diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index e6b4cb598989b..2316ba8a5be67 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1488,7 +1488,7 @@ def find_common_type(types: List[DtypeObj]) -> DtypeObj: if has_bools: for t in types: if is_integer_dtype(t) or is_float_dtype(t) or is_complex_dtype(t): - return object + return np.dtype("object") return np.find_common_type(types, []) @@ -1550,7 +1550,7 @@ def construct_1d_arraylike_from_scalar( elif isinstance(dtype, np.dtype) and dtype.kind in ("U", "S"): # we need to coerce to object dtype to avoid # to allow numpy to take our string as a scalar value - dtype = object + dtype = np.dtype("object") if not isna(value): value = ensure_str(value)
``` pandas/core/dtypes/cast.py:1491: error: Incompatible return value type (got "Type[object]", expected "Union[dtype, ExtensionDtype]") [return-value] pandas/core/dtypes/cast.py:1553: error: Incompatible types in assignment (expression has type "Type[object]", variable has type "Union[dtype, ExtensionDtype]") [assignment] pandas/core/construction.py:601: error: Incompatible default for argument "dtype_if_empty" (default has type "Type[object]", argument has type "Union[ExtensionDtype, str, dtype, Type[str], Type[float], Type[int], Type[complex], Type[bool]]") [assignment] pandas/core/generic.py:6217: error: Argument "dtype_if_empty" to "create_series_with_explicit_dtype" has incompatible type "Type[object]"; expected "Union[ExtensionDtype, str, dtype, Type[str], Type[float], Type[int], Type[complex], Type[bool]]" [arg-type] pandas/tests/arrays/sparse/test_dtype.py:97: error: Argument 1 to "SparseDtype" has incompatible type "Type[object]"; expected "Union[ExtensionDtype, str, dtype, Type[str], Type[float], Type[int], Type[complex], Type[bool]]" [arg-type] pandas/tests/arrays/sparse/test_dtype.py:172: error: Argument 1 to "SparseDtype" has incompatible type "Type[object]"; expected "Union[ExtensionDtype, str, dtype, Type[str], Type[float], Type[int], Type[complex], Type[bool]]" [arg-type] pandas/tests/arrays/sparse/test_combine_concat.py:44: error: Argument 1 to "SparseDtype" has incompatible type "Type[object]"; expected "Union[ExtensionDtype, str, dtype, Type[str], Type[float], Type[int], Type[complex], Type[bool]]" [arg-type] pandas/tests/arrays/sparse/test_array.py:561: error: Argument 1 to "SparseDtype" has incompatible type "Type[object]"; expected "Union[ExtensionDtype, str, dtype, Type[str], Type[float], Type[int], Type[complex], Type[bool]]" [arg-type] ```
https://api.github.com/repos/pandas-dev/pandas/pulls/36098
2020-09-03T18:00:13Z
2020-09-05T02:56:31Z
2020-09-05T02:56:31Z
2020-09-05T07:31:32Z
Backport PR #36086 on branch 1.1.x (DOC: minor fixes to whatsnew\v1.1.2.rst)
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index 17d51c9121f43..8695ff8d11e6d 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -29,9 +29,9 @@ Bug fixes - Bug in :meth:`DataFrame.eval` with ``object`` dtype column binary operations (:issue:`35794`) - Bug in :class:`Series` constructor raising a ``TypeError`` when constructing sparse datetime64 dtypes (:issue:`35762`) - Bug in :meth:`DataFrame.apply` with ``result_type="reduce"`` returning with incorrect index (:issue:`35683`) -- Bug in :meth:`DateTimeIndex.format` and :meth:`PeriodIndex.format` with ``name=True`` setting the first item to ``"None"`` where it should bw ``""`` (:issue:`35712`) +- Bug in :meth:`DateTimeIndex.format` and :meth:`PeriodIndex.format` with ``name=True`` setting the first item to ``"None"`` where it should be ``""`` (:issue:`35712`) - Bug in :meth:`Float64Index.__contains__` incorrectly raising ``TypeError`` instead of returning ``False`` (:issue:`35788`) -- Bug in :class:`DataFrame` indexing returning an incorrect :class:`Series` in some cases when the series has been altered and a cache not invalidated (:issue:`36051`) +- Bug in :class:`DataFrame` indexing returning an incorrect :class:`Series` in some cases when the series has been altered and a cache not invalidated (:issue:`33675`) .. --------------------------------------------------------------------------- @@ -39,7 +39,7 @@ Bug fixes Other ~~~~~ -- :meth:`factorize` now supports ``na_sentinel=None`` to include NaN in the uniques of the values and remove ``dropna`` keyword which was unintentionally exposed to public facing API in 1.1 version from :meth:`factorize`(:issue:`35667`) +- :meth:`factorize` now supports ``na_sentinel=None`` to include NaN in the uniques of the values and remove ``dropna`` keyword which was unintentionally exposed to public facing API in 1.1 version from :meth:`factorize` (:issue:`35667`) .. ---------------------------------------------------------------------------
Backport PR #36086: DOC: minor fixes to whatsnew\v1.1.2.rst
https://api.github.com/repos/pandas-dev/pandas/pulls/36095
2020-09-03T16:30:25Z
2020-09-03T18:02:50Z
2020-09-03T18:02:50Z
2020-09-03T18:02:50Z
BUG: extra leading space in to_string when index=False
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 8b28a4439e1da..b7f2729eed1ab 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -214,8 +214,6 @@ Performance improvements Bug fixes ~~~~~~~~~ -- Bug in :meth:`DataFrameGroupBy.apply` raising error with ``np.nan`` group(s) when ``dropna=False`` (:issue:`35889`) -- Categorical ^^^^^^^^^^^ @@ -257,7 +255,7 @@ Conversion Strings ^^^^^^^ - +- Bug in :meth:`Series.to_string`, :meth:`DataFrame.to_string`, and :meth:`DataFrame.to_latex` adding a leading space when ``index=False`` (:issue:`24980`) - - @@ -313,6 +311,7 @@ Groupby/resample/rolling - Bug when subsetting columns on a :class:`~pandas.core.groupby.DataFrameGroupBy` (e.g. ``df.groupby('a')[['b']])``) would reset the attributes ``axis``, ``dropna``, ``group_keys``, ``level``, ``mutated``, ``sort``, and ``squeeze`` to their default values. (:issue:`9959`) - Bug in :meth:`DataFrameGroupby.tshift` failing to raise ``ValueError`` when a frequency cannot be inferred for the index of a group (:issue:`35937`) - Bug in :meth:`DataFrame.groupby` does not always maintain column index name for ``any``, ``all``, ``bfill``, ``ffill``, ``shift`` (:issue:`29764`) +- Bug in :meth:`DataFrameGroupBy.apply` raising error with ``np.nan`` group(s) when ``dropna=False`` (:issue:`35889`) - Reshaping diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 3dc4290953360..e19a6933f39d4 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -345,6 +345,7 @@ def _get_formatted_values(self) -> List[str]: None, float_format=self.float_format, na_rep=self.na_rep, + leading_space=self.index, ) def to_string(self) -> str: @@ -960,6 +961,7 @@ def _format_col(self, i: int) -> List[str]: na_rep=self.na_rep, space=self.col_space.get(frame.columns[i]), decimal=self.decimal, + leading_space=self.index, ) def to_html( @@ -1111,7 +1113,7 @@ def format_array( space: Optional[Union[str, int]] = None, justify: str = "right", decimal: str = ".", - leading_space: Optional[bool] = None, + leading_space: Optional[bool] = True, quoting: Optional[int] = None, ) -> List[str]: """ @@ -1127,7 +1129,7 @@ def format_array( space justify decimal - leading_space : bool, optional + leading_space : bool, optional, default True Whether the array should be formatted with a leading space. When an array as a column of a Series or DataFrame, we do want the leading space to pad between columns. @@ -1194,7 +1196,7 @@ def __init__( decimal: str = ".", quoting: Optional[int] = None, fixed_width: bool = True, - leading_space: Optional[bool] = None, + leading_space: Optional[bool] = True, ): self.values = values self.digits = digits @@ -1395,9 +1397,11 @@ def format_values_with(float_format): float_format: Optional[FloatFormatType] if self.float_format is None: if self.fixed_width: - float_format = partial( - "{value: .{digits:d}f}".format, digits=self.digits - ) + if self.leading_space is True: + fmt_str = "{value: .{digits:d}f}" + else: + fmt_str = "{value:.{digits:d}f}" + float_format = partial(fmt_str.format, digits=self.digits) else: float_format = self.float_format else: @@ -1429,7 +1433,11 @@ def format_values_with(float_format): ).any() if has_small_values or (too_long and has_large_values): - float_format = partial("{value: .{digits:d}e}".format, digits=self.digits) + if self.leading_space is True: + fmt_str = "{value: .{digits:d}e}" + else: + fmt_str = "{value:.{digits:d}e}" + float_format = partial(fmt_str.format, digits=self.digits) formatted_values = format_values_with(float_format) return formatted_values @@ -1444,7 +1452,11 @@ def _format_strings(self) -> List[str]: class IntArrayFormatter(GenericArrayFormatter): def _format_strings(self) -> List[str]: - formatter = self.formatter or (lambda x: f"{x: d}") + if self.leading_space is False: + formatter_str = lambda x: f"{x:d}".format(x=x) + else: + formatter_str = lambda x: f"{x: d}".format(x=x) + formatter = self.formatter or formatter_str fmt_values = [formatter(x) for x in self.values] return fmt_values diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 22942ed75d0f3..0c04c58afe24e 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1546,11 +1546,11 @@ def test_to_string_no_index(self): df_s = df.to_string(index=False) # Leading space is expected for positive numbers. - expected = " x y z\n 11 33 AAA\n 22 -44 " + expected = " x y z\n11 33 AAA\n22 -44 " assert df_s == expected df_s = df[["y", "x", "z"]].to_string(index=False) - expected = " y x z\n 33 11 AAA\n-44 22 " + expected = " y x z\n 33 11 AAA\n-44 22 " assert df_s == expected def test_to_string_line_width_no_index(self): @@ -1565,7 +1565,7 @@ def test_to_string_line_width_no_index(self): df = DataFrame({"x": [11, 22, 33], "y": [4, 5, 6]}) df_s = df.to_string(line_width=1, index=False) - expected = " x \\\n 11 \n 22 \n 33 \n\n y \n 4 \n 5 \n 6 " + expected = " x \\\n11 \n22 \n33 \n\n y \n 4 \n 5 \n 6 " assert df_s == expected @@ -2269,7 +2269,7 @@ def test_to_string_without_index(self): # GH 11729 Test index=False option s = Series([1, 2, 3, 4]) result = s.to_string(index=False) - expected = " 1\n" + " 2\n" + " 3\n" + " 4" + expected = "1\n" + "2\n" + "3\n" + "4" assert result == expected def test_unicode_name_in_footer(self): @@ -3391,3 +3391,37 @@ def test_filepath_or_buffer_bad_arg_raises(float_frame, method): msg = "buf is not a file name and it has no write method" with pytest.raises(TypeError, match=msg): getattr(float_frame, method)(buf=object()) + + +@pytest.mark.parametrize( + "input_array, expected", + [ + ("a", "a"), + (["a", "b"], "a\nb"), + ([1, "a"], "1\na"), + (1, "1"), + ([0, -1], " 0\n-1"), + (1.0, "1.0"), + ([" a", " b"], " a\n b"), + ([".1", "1"], ".1\n 1"), + (["10", "-10"], " 10\n-10"), + ], +) +def test_format_remove_leading_space_series(input_array, expected): + # GH: 24980 + s = pd.Series(input_array).to_string(index=False) + assert s == expected + + +@pytest.mark.parametrize( + "input_array, expected", + [ + ({"A": ["a"]}, "A\na"), + ({"A": ["a", "b"], "B": ["c", "dd"]}, "A B\na c\nb dd"), + ({"A": ["a", 1], "B": ["aa", 1]}, "A B\na aa\n1 1"), + ], +) +def test_format_remove_leading_space_dataframe(input_array, expected): + # GH: 24980 + df = pd.DataFrame(input_array).to_string(index=False) + assert df == expected diff --git a/pandas/tests/io/formats/test_to_latex.py b/pandas/tests/io/formats/test_to_latex.py index 96a9ed2b86cf4..9dfd851e91c65 100644 --- a/pandas/tests/io/formats/test_to_latex.py +++ b/pandas/tests/io/formats/test_to_latex.py @@ -50,10 +50,10 @@ def test_to_latex(self, float_frame): withoutindex_result = df.to_latex(index=False) withoutindex_expected = r"""\begin{tabular}{rl} \toprule - a & b \\ + a & b \\ \midrule - 1 & b1 \\ - 2 & b2 \\ + 1 & b1 \\ + 2 & b2 \\ \bottomrule \end{tabular} """ @@ -413,7 +413,7 @@ def test_to_latex_longtable(self): withoutindex_result = df.to_latex(index=False, longtable=True) withoutindex_expected = r"""\begin{longtable}{rl} \toprule - a & b \\ + a & b \\ \midrule \endhead \midrule @@ -423,8 +423,8 @@ def test_to_latex_longtable(self): \bottomrule \endlastfoot - 1 & b1 \\ - 2 & b2 \\ + 1 & b1 \\ + 2 & b2 \\ \end{longtable} """ @@ -663,8 +663,8 @@ def test_to_latex_no_header(self): withoutindex_result = df.to_latex(index=False, header=False) withoutindex_expected = r"""\begin{tabular}{rl} \toprule - 1 & b1 \\ - 2 & b2 \\ +1 & b1 \\ +2 & b2 \\ \bottomrule \end{tabular} """ @@ -690,10 +690,10 @@ def test_to_latex_specified_header(self): withoutindex_result = df.to_latex(header=["AA", "BB"], index=False) withoutindex_expected = r"""\begin{tabular}{rl} \toprule -AA & BB \\ +AA & BB \\ \midrule - 1 & b1 \\ - 2 & b2 \\ + 1 & b1 \\ + 2 & b2 \\ \bottomrule \end{tabular} """
- [x] closes #24980 - [x] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This PR is mainly from #29670 contributed by @charlesdong1991, and I made a few changes on his work. The code have passed all tests modified and added in `test_format.py` and `test_to_latex.py`. Any comment is welcomed!
https://api.github.com/repos/pandas-dev/pandas/pulls/36094
2020-09-03T16:14:40Z
2020-09-06T17:49:28Z
2020-09-06T17:49:27Z
2020-09-06T17:49:33Z
BUG: df.replace with numeric values and str to_replace
diff --git a/doc/source/user_guide/missing_data.rst b/doc/source/user_guide/missing_data.rst index 2e68a0598bb71..28206192dd161 100644 --- a/doc/source/user_guide/missing_data.rst +++ b/doc/source/user_guide/missing_data.rst @@ -689,32 +689,6 @@ You can also operate on the DataFrame in place: df.replace(1.5, np.nan, inplace=True) -.. warning:: - - When replacing multiple ``bool`` or ``datetime64`` objects, the first - argument to ``replace`` (``to_replace``) must match the type of the value - being replaced. For example, - - .. code-block:: python - - >>> s = pd.Series([True, False, True]) - >>> s.replace({'a string': 'new value', True: False}) # raises - TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str' - - will raise a ``TypeError`` because one of the ``dict`` keys is not of the - correct type for replacement. - - However, when replacing a *single* object such as, - - .. ipython:: python - - s = pd.Series([True, False, True]) - s.replace('a string', 'another string') - - the original ``NDFrame`` object will be returned untouched. We're working on - unifying this API, but for backwards compatibility reasons we cannot break - the latter behavior. See :issue:`6354` for more details. - Missing data casting rules and indexing --------------------------------------- diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index e65daa439a225..ff806f7ce5ceb 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -337,6 +337,7 @@ ExtensionArray Other ^^^^^ - Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` incorrectly raising ``AssertionError`` instead of ``ValueError`` when invalid parameter combinations are passed (:issue:`36045`) +- Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` with numeric values and string ``to_replace`` (:issue:`34789`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/array_algos/replace.py b/pandas/core/array_algos/replace.py new file mode 100644 index 0000000000000..6ac3cc1f9f2fe --- /dev/null +++ b/pandas/core/array_algos/replace.py @@ -0,0 +1,95 @@ +""" +Methods used by Block.replace and related methods. +""" +import operator +import re +from typing import Optional, Pattern, Union + +import numpy as np + +from pandas._typing import ArrayLike, Scalar + +from pandas.core.dtypes.common import ( + is_datetimelike_v_numeric, + is_numeric_v_string_like, + is_scalar, +) +from pandas.core.dtypes.missing import isna + + +def compare_or_regex_search( + a: ArrayLike, + b: Union[Scalar, Pattern], + regex: bool = False, + mask: Optional[ArrayLike] = None, +) -> Union[ArrayLike, bool]: + """ + Compare two array_like inputs of the same shape or two scalar values + + Calls operator.eq or re.search, depending on regex argument. If regex is + True, perform an element-wise regex matching. + + Parameters + ---------- + a : array_like + b : scalar or regex pattern + regex : bool, default False + mask : array_like or None (default) + + Returns + ------- + mask : array_like of bool + """ + + def _check_comparison_types( + result: Union[ArrayLike, bool], a: ArrayLike, b: Union[Scalar, Pattern] + ): + """ + Raises an error if the two arrays (a,b) cannot be compared. + Otherwise, returns the comparison result as expected. + """ + if is_scalar(result) and isinstance(a, np.ndarray): + type_names = [type(a).__name__, type(b).__name__] + + if isinstance(a, np.ndarray): + type_names[0] = f"ndarray(dtype={a.dtype})" + + raise TypeError( + f"Cannot compare types {repr(type_names[0])} and {repr(type_names[1])}" + ) + + if not regex: + op = lambda x: operator.eq(x, b) + else: + op = np.vectorize( + lambda x: bool(re.search(b, x)) + if isinstance(x, str) and isinstance(b, (str, Pattern)) + else False + ) + + # GH#32621 use mask to avoid comparing to NAs + if mask is None and isinstance(a, np.ndarray) and not isinstance(b, np.ndarray): + mask = np.reshape(~(isna(a)), a.shape) + if isinstance(a, np.ndarray): + a = a[mask] + + if is_numeric_v_string_like(a, b): + # GH#29553 avoid deprecation warnings from numpy + return np.zeros(a.shape, dtype=bool) + + elif is_datetimelike_v_numeric(a, b): + # GH#29553 avoid deprecation warnings from numpy + _check_comparison_types(False, a, b) + return False + + result = op(a) + + if isinstance(result, np.ndarray) and mask is not None: + # The shape of the mask can differ to that of the result + # since we may compare only a subset of a's or b's elements + tmp = np.zeros(mask.shape, dtype=np.bool_) + tmp[mask] = result + result = tmp + + _check_comparison_types(result, a, b) + return result diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 6c8780a0fc186..7b8072279ce69 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -6559,20 +6559,6 @@ def replace( 1 new new 2 bait xyz - Note that when replacing multiple ``bool`` or ``datetime64`` objects, - the data types in the `to_replace` parameter must match the data - type of the value being replaced: - - >>> df = pd.DataFrame({{'A': [True, False, True], - ... 'B': [False, True, False]}}) - >>> df.replace({{'a string': 'new value', True: False}}) # raises - Traceback (most recent call last): - ... - TypeError: Cannot compare types 'ndarray(dtype=bool)' and 'str' - - This raises a ``TypeError`` because one of the ``dict`` keys is not of - the correct type for replacement. - Compare the behavior of ``s.replace({{'a': None}})`` and ``s.replace('a', None)`` to understand the peculiarities of the `to_replace` parameter: diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index ad388ef3f53b0..30ea2766e5133 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -11,7 +11,7 @@ from pandas._libs.internals import BlockPlacement from pandas._libs.tslibs import conversion from pandas._libs.tslibs.timezones import tz_compare -from pandas._typing import ArrayLike +from pandas._typing import ArrayLike, Scalar from pandas.util._validators import validate_bool_kwarg from pandas.core.dtypes.cast import ( @@ -59,6 +59,7 @@ from pandas.core.dtypes.missing import _isna_compat, is_valid_nat_for_dtype, isna import pandas.core.algorithms as algos +from pandas.core.array_algos.replace import compare_or_regex_search from pandas.core.array_algos.transforms import shift from pandas.core.arrays import ( Categorical, @@ -792,7 +793,6 @@ def _replace_list( self, src_list: List[Any], dest_list: List[Any], - masks: List[np.ndarray], inplace: bool = False, regex: bool = False, ) -> List["Block"]: @@ -801,11 +801,28 @@ def _replace_list( """ src_len = len(src_list) - 1 + def comp(s: Scalar, mask: np.ndarray, regex: bool = False) -> np.ndarray: + """ + Generate a bool array by perform an equality check, or perform + an element-wise regular expression matching + """ + if isna(s): + return ~mask + + s = com.maybe_box_datetimelike(s) + return compare_or_regex_search(self.values, s, regex, mask) + + # Calculate the mask once, prior to the call of comp + # in order to avoid repeating the same computations + mask = ~isna(self.values) + + masks = [comp(s, mask, regex) for s in src_list] + rb = [self if inplace else self.copy()] for i, (src, dest) in enumerate(zip(src_list, dest_list)): new_rb: List["Block"] = [] for blk in rb: - m = masks[i][blk.mgr_locs.indexer] + m = masks[i] convert = i == src_len # only convert once at the end result = blk._replace_coerce( mask=m, @@ -2908,7 +2925,9 @@ def _extract_bool_array(mask: ArrayLike) -> np.ndarray: """ if isinstance(mask, ExtensionArray): # We could have BooleanArray, Sparse[bool], ... - mask = np.asarray(mask, dtype=np.bool_) + # Except for BooleanArray, this is equivalent to just + # np.asarray(mask, dtype=bool) + mask = mask.to_numpy(dtype=bool, na_value=False) assert isinstance(mask, np.ndarray), type(mask) assert mask.dtype == bool, mask.dtype diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 2e3098d94afcb..248cfb2490c9e 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1,14 +1,11 @@ from collections import defaultdict import itertools -import operator -import re from typing import ( Any, DefaultDict, Dict, List, Optional, - Pattern, Sequence, Tuple, TypeVar, @@ -19,7 +16,7 @@ import numpy as np from pandas._libs import internals as libinternals, lib -from pandas._typing import ArrayLike, DtypeObj, Label, Scalar +from pandas._typing import ArrayLike, DtypeObj, Label from pandas.util._validators import validate_bool_kwarg from pandas.core.dtypes.cast import ( @@ -29,12 +26,9 @@ ) from pandas.core.dtypes.common import ( DT64NS_DTYPE, - is_datetimelike_v_numeric, is_dtype_equal, is_extension_array_dtype, is_list_like, - is_numeric_v_string_like, - is_scalar, ) from pandas.core.dtypes.concat import concat_compat from pandas.core.dtypes.dtypes import ExtensionDtype @@ -44,7 +38,6 @@ import pandas.core.algorithms as algos from pandas.core.arrays.sparse import SparseDtype from pandas.core.base import PandasObject -import pandas.core.common as com from pandas.core.construction import extract_array from pandas.core.indexers import maybe_convert_indices from pandas.core.indexes.api import Index, ensure_index @@ -628,31 +621,10 @@ def replace_list( """ do a list replace """ inplace = validate_bool_kwarg(inplace, "inplace") - # figure out our mask apriori to avoid repeated replacements - values = self.as_array() - - def comp(s: Scalar, mask: np.ndarray, regex: bool = False): - """ - Generate a bool array by perform an equality check, or perform - an element-wise regular expression matching - """ - if isna(s): - return ~mask - - s = com.maybe_box_datetimelike(s) - return _compare_or_regex_search(values, s, regex, mask) - - # Calculate the mask once, prior to the call of comp - # in order to avoid repeating the same computations - mask = ~isna(values) - - masks = [comp(s, mask, regex) for s in src_list] - bm = self.apply( "_replace_list", src_list=src_list, dest_list=dest_list, - masks=masks, inplace=inplace, regex=regex, ) @@ -1900,80 +1872,6 @@ def _merge_blocks( return blocks -def _compare_or_regex_search( - a: ArrayLike, - b: Union[Scalar, Pattern], - regex: bool = False, - mask: Optional[ArrayLike] = None, -) -> Union[ArrayLike, bool]: - """ - Compare two array_like inputs of the same shape or two scalar values - - Calls operator.eq or re.search, depending on regex argument. If regex is - True, perform an element-wise regex matching. - - Parameters - ---------- - a : array_like - b : scalar or regex pattern - regex : bool, default False - mask : array_like or None (default) - - Returns - ------- - mask : array_like of bool - """ - - def _check_comparison_types( - result: Union[ArrayLike, bool], a: ArrayLike, b: Union[Scalar, Pattern] - ): - """ - Raises an error if the two arrays (a,b) cannot be compared. - Otherwise, returns the comparison result as expected. - """ - if is_scalar(result) and isinstance(a, np.ndarray): - type_names = [type(a).__name__, type(b).__name__] - - if isinstance(a, np.ndarray): - type_names[0] = f"ndarray(dtype={a.dtype})" - - raise TypeError( - f"Cannot compare types {repr(type_names[0])} and {repr(type_names[1])}" - ) - - if not regex: - op = lambda x: operator.eq(x, b) - else: - op = np.vectorize( - lambda x: bool(re.search(b, x)) - if isinstance(x, str) and isinstance(b, (str, Pattern)) - else False - ) - - # GH#32621 use mask to avoid comparing to NAs - if mask is None and isinstance(a, np.ndarray) and not isinstance(b, np.ndarray): - mask = np.reshape(~(isna(a)), a.shape) - if isinstance(a, np.ndarray): - a = a[mask] - - if is_datetimelike_v_numeric(a, b) or is_numeric_v_string_like(a, b): - # GH#29553 avoid deprecation warnings from numpy - _check_comparison_types(False, a, b) - return False - - result = op(a) - - if isinstance(result, np.ndarray) and mask is not None: - # The shape of the mask can differ to that of the result - # since we may compare only a subset of a's or b's elements - tmp = np.zeros(mask.shape, dtype=np.bool_) - tmp[mask] = result - result = tmp - - _check_comparison_types(result, a, b) - return result - - def _fast_count_smallints(arr: np.ndarray) -> np.ndarray: """Faster version of set(arr) for sequences of small numbers.""" counts = np.bincount(arr.astype(np.int_)) diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index 83dfd42ae2a6e..ea2488dfc0877 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -1131,8 +1131,19 @@ def test_replace_bool_with_bool(self): def test_replace_with_dict_with_bool_keys(self): df = DataFrame({0: [True, False], 1: [False, True]}) - with pytest.raises(TypeError, match="Cannot compare types .+"): - df.replace({"asdf": "asdb", True: "yes"}) + result = df.replace({"asdf": "asdb", True: "yes"}) + expected = DataFrame({0: ["yes", False], 1: [False, "yes"]}) + tm.assert_frame_equal(result, expected) + + def test_replace_dict_strings_vs_ints(self): + # GH#34789 + df = pd.DataFrame({"Y0": [1, 2], "Y1": [3, 4]}) + result = df.replace({"replace_string": "test"}) + + tm.assert_frame_equal(result, df) + + result = df["Y0"].replace({"replace_string": "test"}) + tm.assert_series_equal(result, df["Y0"]) def test_replace_truthy(self): df = DataFrame({"a": [True, True]}) diff --git a/pandas/tests/series/methods/test_replace.py b/pandas/tests/series/methods/test_replace.py index ccaa005369a1c..e255d46e81851 100644 --- a/pandas/tests/series/methods/test_replace.py +++ b/pandas/tests/series/methods/test_replace.py @@ -218,8 +218,9 @@ def test_replace_bool_with_bool(self): def test_replace_with_dict_with_bool_keys(self): s = pd.Series([True, False, True]) - with pytest.raises(TypeError, match="Cannot compare types .+"): - s.replace({"asdf": "asdb", True: "yes"}) + result = s.replace({"asdf": "asdb", True: "yes"}) + expected = pd.Series(["yes", False, "yes"]) + tm.assert_series_equal(result, expected) def test_replace2(self): N = 100
- [x] closes #34789 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry We also avoid copies by not calling `self.as_array` and instead moving the mask-finding to the block level.
https://api.github.com/repos/pandas-dev/pandas/pulls/36093
2020-09-03T15:57:21Z
2020-09-05T03:21:50Z
2020-09-05T03:21:50Z
2020-09-05T03:41:43Z
CI: unpin numpy for CI / Checks github action
diff --git a/environment.yml b/environment.yml index f54bf41c14c75..ebf22bbf067a6 100644 --- a/environment.yml +++ b/environment.yml @@ -3,7 +3,7 @@ channels: - conda-forge dependencies: # required - - numpy>=1.16.5, <1.20 # gh-39513 + - numpy>=1.16.5 - python=3 - python-dateutil>=2.7.3 - pytz diff --git a/pandas/compat/numpy/__init__.py b/pandas/compat/numpy/__init__.py index 1d8077da76469..e551f05efa31b 100644 --- a/pandas/compat/numpy/__init__.py +++ b/pandas/compat/numpy/__init__.py @@ -43,7 +43,9 @@ def np_datetime64_compat(s, *args, **kwargs): warning, when need to pass '2015-01-01 09:00:00' """ s = tz_replacer(s) - return np.datetime64(s, *args, **kwargs) + # error: No overload variant of "datetime64" matches argument types "Any", + # "Tuple[Any, ...]", "Dict[str, Any]" + return np.datetime64(s, *args, **kwargs) # type: ignore[call-overload] def np_array_datetime64_compat(arr, *args, **kwargs): diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py index 0a4e03fa97402..a8a761b5f4aac 100644 --- a/pandas/core/aggregation.py +++ b/pandas/core/aggregation.py @@ -181,7 +181,9 @@ def normalize_keyword_aggregation(kwargs: dict) -> Tuple[dict, List[str], List[i # get the new index of columns by comparison col_idx_order = Index(uniquified_aggspec).get_indexer(uniquified_order) - return aggspec, columns, col_idx_order + # error: Incompatible return value type (got "Tuple[defaultdict[Any, Any], + # Any, ndarray]", expected "Tuple[Dict[Any, Any], List[str], List[int]]") + return aggspec, columns, col_idx_order # type: ignore[return-value] def _make_unique_kwarg_list( diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 04eef635dc79b..57e57f48fdfe5 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -157,7 +157,10 @@ def _ensure_data(values: ArrayLike) -> Tuple[np.ndarray, DtypeObj]: with catch_warnings(): simplefilter("ignore", np.ComplexWarning) values = ensure_float64(values) - return values, np.dtype("float64") + # error: Incompatible return value type (got "Tuple[ExtensionArray, + # dtype[floating[_64Bit]]]", expected "Tuple[ndarray, Union[dtype[Any], + # ExtensionDtype]]") + return values, np.dtype("float64") # type: ignore[return-value] except (TypeError, ValueError, OverflowError): # if we are trying to coerce to a dtype @@ -173,7 +176,9 @@ def _ensure_data(values: ArrayLike) -> Tuple[np.ndarray, DtypeObj]: elif is_timedelta64_dtype(values.dtype): from pandas import TimedeltaIndex - values = TimedeltaIndex(values)._data + # error: Incompatible types in assignment (expression has type + # "TimedeltaArray", variable has type "ndarray") + values = TimedeltaIndex(values)._data # type: ignore[assignment] else: # Datetime if values.ndim > 1 and is_datetime64_ns_dtype(values.dtype): @@ -182,27 +187,45 @@ def _ensure_data(values: ArrayLike) -> Tuple[np.ndarray, DtypeObj]: # TODO(EA2D): special case not needed with 2D EAs asi8 = values.view("i8") dtype = values.dtype - return asi8, dtype + # error: Incompatible return value type (got "Tuple[Any, + # Union[dtype, ExtensionDtype, None]]", expected + # "Tuple[ndarray, Union[dtype, ExtensionDtype]]") + return asi8, dtype # type: ignore[return-value] from pandas import DatetimeIndex - values = DatetimeIndex(values)._data + # Incompatible types in assignment (expression has type "DatetimeArray", + # variable has type "ndarray") + values = DatetimeIndex(values)._data # type: ignore[assignment] dtype = values.dtype - return values.asi8, dtype + # error: Item "ndarray" of "Union[PeriodArray, Any, ndarray]" has no attribute + # "asi8" + return values.asi8, dtype # type: ignore[union-attr] elif is_categorical_dtype(values.dtype): - values = cast("Categorical", values) - values = values.codes + # error: Incompatible types in assignment (expression has type "Categorical", + # variable has type "ndarray") + values = cast("Categorical", values) # type: ignore[assignment] + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + # error: Item "ndarray" of "Union[Any, ndarray]" has no attribute "codes" + values = values.codes # type: ignore[assignment,union-attr] dtype = pandas_dtype("category") # we are actually coercing to int64 # until our algos support int* directly (not all do) values = ensure_int64(values) - return values, dtype + # error: Incompatible return value type (got "Tuple[ExtensionArray, + # Union[dtype[Any], ExtensionDtype]]", expected "Tuple[ndarray, + # Union[dtype[Any], ExtensionDtype]]") + return values, dtype # type: ignore[return-value] # we have failed, return object - values = np.asarray(values, dtype=object) + + # error: Incompatible types in assignment (expression has type "ndarray", variable + # has type "ExtensionArray") + values = np.asarray(values, dtype=object) # type: ignore[assignment] return ensure_object(values), np.dtype("object") @@ -227,24 +250,40 @@ def _reconstruct_data( return values if is_extension_array_dtype(dtype): - cls = dtype.construct_array_type() + # error: Item "dtype[Any]" of "Union[dtype[Any], ExtensionDtype]" has no + # attribute "construct_array_type" + cls = dtype.construct_array_type() # type: ignore[union-attr] if isinstance(values, cls) and values.dtype == dtype: return values values = cls._from_sequence(values) elif is_bool_dtype(dtype): - values = values.astype(dtype, copy=False) + # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has + # incompatible type "Union[dtype, ExtensionDtype]"; expected + # "Union[dtype, None, type, _SupportsDtype, str, Tuple[Any, int], + # Tuple[Any, Union[int, Sequence[int]]], List[Any], _DtypeDict, + # Tuple[Any, Any]]" + values = values.astype(dtype, copy=False) # type: ignore[arg-type] # we only support object dtypes bool Index if isinstance(original, ABCIndex): values = values.astype(object, copy=False) elif dtype is not None: if is_datetime64_dtype(dtype): - dtype = "datetime64[ns]" + # error: Incompatible types in assignment (expression has type + # "str", variable has type "Union[dtype, ExtensionDtype]") + dtype = "datetime64[ns]" # type: ignore[assignment] elif is_timedelta64_dtype(dtype): - dtype = "timedelta64[ns]" + # error: Incompatible types in assignment (expression has type + # "str", variable has type "Union[dtype, ExtensionDtype]") + dtype = "timedelta64[ns]" # type: ignore[assignment] - values = values.astype(dtype, copy=False) + # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has + # incompatible type "Union[dtype, ExtensionDtype]"; expected + # "Union[dtype, None, type, _SupportsDtype, str, Tuple[Any, int], + # Tuple[Any, Union[int, Sequence[int]]], List[Any], _DtypeDict, + # Tuple[Any, Any]]" + values = values.astype(dtype, copy=False) # type: ignore[arg-type] return values @@ -296,14 +335,18 @@ def _get_values_for_rank(values: ArrayLike): if is_categorical_dtype(values): values = cast("Categorical", values)._values_for_rank() - values, _ = _ensure_data(values) + # error: Incompatible types in assignment (expression has type "ndarray", variable + # has type "ExtensionArray") + values, _ = _ensure_data(values) # type: ignore[assignment] return values def get_data_algo(values: ArrayLike): values = _get_values_for_rank(values) - ndtype = _check_object_for_strings(values) + # error: Argument 1 to "_check_object_for_strings" has incompatible type + # "ExtensionArray"; expected "ndarray" + ndtype = _check_object_for_strings(values) # type: ignore[arg-type] htable = _hashtables.get(ndtype, _hashtables["object"]) return htable, values @@ -460,17 +503,46 @@ def isin(comps: AnyArrayLike, values: AnyArrayLike) -> np.ndarray: ) if not isinstance(values, (ABCIndex, ABCSeries, ABCExtensionArray, np.ndarray)): - values = _ensure_arraylike(list(values)) + # error: Incompatible types in assignment (expression has type "ExtensionArray", + # variable has type "Index") + # error: Incompatible types in assignment (expression has type "ExtensionArray", + # variable has type "Series") + # error: Incompatible types in assignment (expression has type "ExtensionArray", + # variable has type "ndarray") + values = _ensure_arraylike(list(values)) # type: ignore[assignment] elif isinstance(values, ABCMultiIndex): # Avoid raising in extract_array - values = np.array(values) - else: - values = extract_array(values, extract_numpy=True) - comps = _ensure_arraylike(comps) - comps = extract_array(comps, extract_numpy=True) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "Index") + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "Series") + values = np.array(values) # type: ignore[assignment] + else: + # error: Incompatible types in assignment (expression has type "Union[Any, + # ExtensionArray]", variable has type "Index") + # error: Incompatible types in assignment (expression has type "Union[Any, + # ExtensionArray]", variable has type "Series") + values = extract_array(values, extract_numpy=True) # type: ignore[assignment] + + # error: Incompatible types in assignment (expression has type "ExtensionArray", + # variable has type "Index") + # error: Incompatible types in assignment (expression has type "ExtensionArray", + # variable has type "Series") + # error: Incompatible types in assignment (expression has type "ExtensionArray", + # variable has type "ndarray") + comps = _ensure_arraylike(comps) # type: ignore[assignment] + # error: Incompatible types in assignment (expression has type "Union[Any, + # ExtensionArray]", variable has type "Index") + # error: Incompatible types in assignment (expression has type "Union[Any, + # ExtensionArray]", variable has type "Series") + comps = extract_array(comps, extract_numpy=True) # type: ignore[assignment] if is_extension_array_dtype(comps.dtype): - return comps.isin(values) + # error: Incompatible return value type (got "Series", expected "ndarray") + # error: Item "ndarray" of "Union[Any, ndarray]" has no attribute "isin" + return comps.isin(values) # type: ignore[return-value,union-attr] elif needs_i8_conversion(comps.dtype): # Dispatch to DatetimeLikeArrayMixin.isin @@ -501,7 +573,19 @@ def f(c, v): f = np.in1d else: - common = np.find_common_type([values.dtype, comps.dtype], []) + # error: List item 0 has incompatible type "Union[Any, dtype[Any], + # ExtensionDtype]"; expected "Union[dtype[Any], None, type, _SupportsDType, str, + # Tuple[Any, Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, + # Any]]" + # error: List item 1 has incompatible type "Union[Any, ExtensionDtype]"; + # expected "Union[dtype[Any], None, type, _SupportsDType, str, Tuple[Any, + # Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]" + # error: List item 1 has incompatible type "Union[dtype[Any], ExtensionDtype]"; + # expected "Union[dtype[Any], None, type, _SupportsDType, str, Tuple[Any, + # Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]" + common = np.find_common_type( + [values.dtype, comps.dtype], [] # type: ignore[list-item] + ) values = values.astype(common, copy=False) comps = comps.astype(common, copy=False) name = common.name @@ -916,7 +1000,9 @@ def duplicated(values: ArrayLike, keep: Union[str, bool] = "first") -> np.ndarra ------- duplicated : ndarray """ - values, _ = _ensure_data(values) + # error: Incompatible types in assignment (expression has type "ndarray", variable + # has type "ExtensionArray") + values, _ = _ensure_data(values) # type: ignore[assignment] ndtype = values.dtype.name f = getattr(htable, f"duplicated_{ndtype}") return f(values, keep=keep) @@ -1188,7 +1274,9 @@ def _get_score(at): else: q = np.asarray(q, np.float64) result = [_get_score(x) for x in q] - result = np.array(result, dtype=np.float64) + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "List[Any]") + result = np.array(result, dtype=np.float64) # type: ignore[assignment] return result @@ -1776,7 +1864,11 @@ def safe_sort( if not isinstance(values, (np.ndarray, ABCExtensionArray)): # don't convert to string types dtype, _ = infer_dtype_from_array(values) - values = np.asarray(values, dtype=dtype) + # error: Argument "dtype" to "asarray" has incompatible type "Union[dtype[Any], + # ExtensionDtype]"; expected "Union[dtype[Any], None, type, _SupportsDType, str, + # Union[Tuple[Any, int], Tuple[Any, Union[int, Sequence[int]]], List[Any], + # _DTypeDict, Tuple[Any, Any]]]" + values = np.asarray(values, dtype=dtype) # type: ignore[arg-type] sorter = None diff --git a/pandas/core/apply.py b/pandas/core/apply.py index cccd88ccb7a1e..57147461284fb 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -1016,7 +1016,11 @@ def apply_standard(self) -> FrameOrSeriesUnion: with np.errstate(all="ignore"): if isinstance(f, np.ufunc): - return f(obj) + # error: Argument 1 to "__call__" of "ufunc" has incompatible type + # "Series"; expected "Union[Union[int, float, complex, str, bytes, + # generic], Sequence[Union[int, float, complex, str, bytes, generic]], + # Sequence[Sequence[Any]], _SupportsArray]" + return f(obj) # type: ignore[arg-type] # row-wise access if is_extension_array_dtype(obj.dtype) and hasattr(obj._values, "map"): diff --git a/pandas/core/array_algos/putmask.py b/pandas/core/array_algos/putmask.py index 93046f476c6ba..b552a1be4c36e 100644 --- a/pandas/core/array_algos/putmask.py +++ b/pandas/core/array_algos/putmask.py @@ -120,7 +120,11 @@ def putmask_smart(values: np.ndarray, mask: np.ndarray, new) -> np.ndarray: return _putmask_preserve(values, new, mask) dtype = find_common_type([values.dtype, new.dtype]) - values = values.astype(dtype) + # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has incompatible type + # "Union[dtype[Any], ExtensionDtype]"; expected "Union[dtype[Any], None, type, + # _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int, Sequence[int]]], + # List[Any], _DTypeDict, Tuple[Any, Any]]]" + values = values.astype(dtype) # type: ignore[arg-type] return _putmask_preserve(values, new, mask) @@ -187,10 +191,16 @@ def extract_bool_array(mask: ArrayLike) -> np.ndarray: # We could have BooleanArray, Sparse[bool], ... # Except for BooleanArray, this is equivalent to just # np.asarray(mask, dtype=bool) - mask = mask.to_numpy(dtype=bool, na_value=False) - mask = np.asarray(mask, dtype=bool) - return mask + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + mask = mask.to_numpy(dtype=bool, na_value=False) # type: ignore[assignment] + + # error: Incompatible types in assignment (expression has type "ndarray", variable + # has type "ExtensionArray") + mask = np.asarray(mask, dtype=bool) # type: ignore[assignment] + # error: Incompatible return value type (got "ExtensionArray", expected "ndarray") + return mask # type: ignore[return-value] def setitem_datetimelike_compat(values: np.ndarray, num_set: int, other): diff --git a/pandas/core/array_algos/quantile.py b/pandas/core/array_algos/quantile.py index 802fc4db0a36d..501d3308b7d8b 100644 --- a/pandas/core/array_algos/quantile.py +++ b/pandas/core/array_algos/quantile.py @@ -143,10 +143,17 @@ def quantile_ea_compat( mask = np.asarray(values.isna()) mask = np.atleast_2d(mask) - values, fill_value = values._values_for_factorize() - values = np.atleast_2d(values) - - result = quantile_with_mask(values, mask, fill_value, qs, interpolation, axis) + # error: Incompatible types in assignment (expression has type "ndarray", variable + # has type "ExtensionArray") + values, fill_value = values._values_for_factorize() # type: ignore[assignment] + # error: No overload variant of "atleast_2d" matches argument type "ExtensionArray" + values = np.atleast_2d(values) # type: ignore[call-overload] + + # error: Argument 1 to "quantile_with_mask" has incompatible type "ExtensionArray"; + # expected "ndarray" + result = quantile_with_mask( + values, mask, fill_value, qs, interpolation, axis # type: ignore[arg-type] + ) if not is_sparse(orig.dtype): # shape[0] should be 1 as long as EAs are 1D @@ -160,4 +167,5 @@ def quantile_ea_compat( assert result.shape == (1, len(qs)), result.shape result = type(orig)._from_factorized(result[0], orig) - return result + # error: Incompatible return value type (got "ndarray", expected "ExtensionArray") + return result # type: ignore[return-value] diff --git a/pandas/core/array_algos/replace.py b/pandas/core/array_algos/replace.py index 201b9fdcc51cc..b0c0799750859 100644 --- a/pandas/core/array_algos/replace.py +++ b/pandas/core/array_algos/replace.py @@ -95,7 +95,9 @@ def _check_comparison_types( if is_numeric_v_string_like(a, b): # GH#29553 avoid deprecation warnings from numpy - return np.zeros(a.shape, dtype=bool) + # error: Incompatible return value type (got "ndarray", expected + # "Union[ExtensionArray, bool]") + return np.zeros(a.shape, dtype=bool) # type: ignore[return-value] elif is_datetimelike_v_numeric(a, b): # GH#29553 avoid deprecation warnings from numpy @@ -152,6 +154,8 @@ def re_replacer(s): f = np.vectorize(re_replacer, otypes=[values.dtype]) if mask is None: - values[:] = f(values) + # error: Invalid index type "slice" for "ExtensionArray"; expected type + # "Union[int, ndarray]" + values[:] = f(values) # type: ignore[index] else: values[mask] = f(values[mask]) diff --git a/pandas/core/array_algos/take.py b/pandas/core/array_algos/take.py index 054497089c5ab..7eed31663f1cb 100644 --- a/pandas/core/array_algos/take.py +++ b/pandas/core/array_algos/take.py @@ -140,7 +140,14 @@ def take_1d( """ if not isinstance(arr, np.ndarray): # ExtensionArray -> dispatch to their method - return arr.take(indexer, fill_value=fill_value, allow_fill=allow_fill) + + # error: Argument 1 to "take" of "ExtensionArray" has incompatible type + # "ndarray"; expected "Sequence[int]" + return arr.take( + indexer, # type: ignore[arg-type] + fill_value=fill_value, + allow_fill=allow_fill, + ) indexer, dtype, fill_value, mask_info = _take_preprocess_indexer_and_fill_value( arr, indexer, 0, None, fill_value, allow_fill @@ -174,7 +181,9 @@ def take_2d_multi( row_idx = ensure_int64(row_idx) col_idx = ensure_int64(col_idx) - indexer = row_idx, col_idx + # error: Incompatible types in assignment (expression has type "Tuple[Any, Any]", + # variable has type "ndarray") + indexer = row_idx, col_idx # type: ignore[assignment] mask_info = None # check for promotion based on types only (do this first because @@ -485,8 +494,13 @@ def _take_preprocess_indexer_and_fill_value( if dtype != arr.dtype and (out is None or out.dtype != dtype): # check if promotion is actually required based on indexer mask = indexer == -1 - needs_masking = mask.any() - mask_info = mask, needs_masking + # error: Item "bool" of "Union[Any, bool]" has no attribute "any" + # [union-attr] + needs_masking = mask.any() # type: ignore[union-attr] + # error: Incompatible types in assignment (expression has type + # "Tuple[Union[Any, bool], Any]", variable has type + # "Optional[Tuple[None, bool]]") + mask_info = mask, needs_masking # type: ignore[assignment] if needs_masking: if out is not None and out.dtype != dtype: raise TypeError("Incompatible type for fill_value") diff --git a/pandas/core/arraylike.py b/pandas/core/arraylike.py index 3f45f503d0f62..588fe8adc7241 100644 --- a/pandas/core/arraylike.py +++ b/pandas/core/arraylike.py @@ -258,7 +258,12 @@ def array_ufunc(self, ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any) return result # Determine if we should defer. - no_defer = (np.ndarray.__array_ufunc__, cls.__array_ufunc__) + + # error: "Type[ndarray]" has no attribute "__array_ufunc__" + no_defer = ( + np.ndarray.__array_ufunc__, # type: ignore[attr-defined] + cls.__array_ufunc__, + ) for item in inputs: higher_priority = ( diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index d54d1855ac2f8..8beafe3fe4578 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -104,7 +104,9 @@ def take( new_data = take( self._ndarray, - indices, + # error: Argument 2 to "take" has incompatible type "Sequence[int]"; + # expected "ndarray" + indices, # type: ignore[arg-type] allow_fill=allow_fill, fill_value=fill_value, axis=axis, @@ -147,7 +149,8 @@ def ndim(self) -> int: @cache_readonly def size(self) -> int: - return np.prod(self.shape) + # error: Incompatible return value type (got "number", expected "int") + return np.prod(self.shape) # type: ignore[return-value] @cache_readonly def nbytes(self) -> int: @@ -217,7 +220,9 @@ def _concat_same_type( new_values = [x._ndarray for x in to_concat] new_values = np.concatenate(new_values, axis=axis) - return to_concat[0]._from_backing_data(new_values) + # error: Argument 1 to "_from_backing_data" of "NDArrayBackedExtensionArray" has + # incompatible type "List[ndarray]"; expected "ndarray" + return to_concat[0]._from_backing_data(new_values) # type: ignore[arg-type] @doc(ExtensionArray.searchsorted) def searchsorted(self, value, side="left", sorter=None): @@ -258,7 +263,13 @@ def __getitem__( return self._box_func(result) return self._from_backing_data(result) - key = extract_array(key, extract_numpy=True) + # error: Value of type variable "AnyArrayLike" of "extract_array" cannot be + # "Union[int, slice, ndarray]" + # error: Incompatible types in assignment (expression has type "ExtensionArray", + # variable has type "Union[int, slice, ndarray]") + key = extract_array( # type: ignore[type-var,assignment] + key, extract_numpy=True + ) key = check_array_indexer(self, key) result = self._ndarray[key] if lib.is_scalar(result): @@ -274,9 +285,14 @@ def fillna( value, method = validate_fillna_kwargs(value, method) mask = self.isna() - value = missing.check_value_size(value, mask, len(self)) + # error: Argument 2 to "check_value_size" has incompatible type + # "ExtensionArray"; expected "ndarray" + value = missing.check_value_size( + value, mask, len(self) # type: ignore[arg-type] + ) - if mask.any(): + # error: "ExtensionArray" has no attribute "any" + if mask.any(): # type: ignore[attr-defined] if method is not None: # TODO: check value is None # (for now) when self.ndim == 2, we assume axis=0 @@ -412,7 +428,8 @@ def value_counts(self, dropna: bool = True): ) if dropna: - values = self[~self.isna()]._ndarray + # error: Unsupported operand type for ~ ("ExtensionArray") + values = self[~self.isna()]._ndarray # type: ignore[operator] else: values = self._ndarray diff --git a/pandas/core/arrays/_ranges.py b/pandas/core/arrays/_ranges.py index c001c57ffe757..34d5ea6cfb20d 100644 --- a/pandas/core/arrays/_ranges.py +++ b/pandas/core/arrays/_ranges.py @@ -161,7 +161,9 @@ def _generate_range_overflow_safe_signed( # Putting this into a DatetimeArray/TimedeltaArray # would incorrectly be interpreted as NaT raise OverflowError - return result + # error: Incompatible return value type (got "signedinteger[_64Bit]", + # expected "int") + return result # type: ignore[return-value] except (FloatingPointError, OverflowError): # with endpoint negative and addend positive we risk # FloatingPointError; with reversed signed we risk OverflowError @@ -175,11 +177,16 @@ def _generate_range_overflow_safe_signed( # watch out for very special case in which we just slightly # exceed implementation bounds, but when passing the result to # np.arange will get a result slightly within the bounds - result = np.uint64(endpoint) + np.uint64(addend) + + # error: Incompatible types in assignment (expression has type + # "unsignedinteger[_64Bit]", variable has type "signedinteger[_64Bit]") + result = np.uint64(endpoint) + np.uint64(addend) # type: ignore[assignment] i64max = np.uint64(np.iinfo(np.int64).max) assert result > i64max if result <= i64max + np.uint64(stride): - return result + # error: Incompatible return value type (got "unsignedinteger", expected + # "int") + return result # type: ignore[return-value] raise OutOfBoundsDatetime( f"Cannot generate range with {side}={endpoint} and periods={periods}" diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 86a1bcf24167c..99838602eeb63 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -391,13 +391,15 @@ def __contains__(self, item) -> bool: if not self._can_hold_na: return False elif item is self.dtype.na_value or isinstance(item, self.dtype.type): - return self.isna().any() + # error: "ExtensionArray" has no attribute "any" + return self.isna().any() # type: ignore[attr-defined] else: return False else: return (item == self).any() - def __eq__(self, other: Any) -> ArrayLike: + # error: Signature of "__eq__" incompatible with supertype "object" + def __eq__(self, other: Any) -> ArrayLike: # type: ignore[override] """ Return for `self == other` (element-wise equality). """ @@ -409,7 +411,8 @@ def __eq__(self, other: Any) -> ArrayLike: # underlying arrays) raise AbstractMethodError(self) - def __ne__(self, other: Any) -> ArrayLike: + # error: Signature of "__ne__" incompatible with supertype "object" + def __ne__(self, other: Any) -> ArrayLike: # type: ignore[override] """ Return for `self != other` (element-wise in-equality). """ @@ -446,7 +449,12 @@ def to_numpy( ------- numpy.ndarray """ - result = np.asarray(self, dtype=dtype) + # error: Argument "dtype" to "asarray" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[str], Type[float], Type[int], + # Type[complex], Type[bool], Type[object], None]"; expected "Union[dtype[Any], + # None, type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int, + # Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]" + result = np.asarray(self, dtype=dtype) # type: ignore[arg-type] if copy or na_value is not lib.no_default: result = result.copy() if na_value is not lib.no_default: @@ -476,7 +484,8 @@ def size(self) -> int: """ The number of elements in the array. """ - return np.prod(self.shape) + # error: Incompatible return value type (got "number", expected "int") + return np.prod(self.shape) # type: ignore[return-value] @property def ndim(self) -> int: @@ -639,7 +648,8 @@ def argmin(self, skipna: bool = True) -> int: ExtensionArray.argmax """ validate_bool_kwarg(skipna, "skipna") - if not skipna and self.isna().any(): + # error: "ExtensionArray" has no attribute "any" + if not skipna and self.isna().any(): # type: ignore[attr-defined] raise NotImplementedError return nargminmax(self, "argmin") @@ -663,7 +673,8 @@ def argmax(self, skipna: bool = True) -> int: ExtensionArray.argmin """ validate_bool_kwarg(skipna, "skipna") - if not skipna and self.isna().any(): + # error: "ExtensionArray" has no attribute "any" + if not skipna and self.isna().any(): # type: ignore[attr-defined] raise NotImplementedError return nargminmax(self, "argmax") @@ -697,9 +708,14 @@ def fillna(self, value=None, method=None, limit=None): value, method = validate_fillna_kwargs(value, method) mask = self.isna() - value = missing.check_value_size(value, mask, len(self)) + # error: Argument 2 to "check_value_size" has incompatible type + # "ExtensionArray"; expected "ndarray" + value = missing.check_value_size( + value, mask, len(self) # type: ignore[arg-type] + ) - if mask.any(): + # error: "ExtensionArray" has no attribute "any" + if mask.any(): # type: ignore[attr-defined] if method is not None: func = missing.get_fill_func(method) new_values, _ = func(self.astype(object), limit=limit, mask=mask) @@ -720,7 +736,8 @@ def dropna(self): ------- valid : ExtensionArray """ - return self[~self.isna()] + # error: Unsupported operand type for ~ ("ExtensionArray") + return self[~self.isna()] # type: ignore[operator] def shift(self, periods: int = 1, fill_value: object = None) -> ExtensionArray: """ @@ -865,7 +882,8 @@ def equals(self, other: object) -> bool: if isinstance(equal_values, ExtensionArray): # boolean array with NA -> fill with False equal_values = equal_values.fillna(False) - equal_na = self.isna() & other.isna() + # error: Unsupported left operand type for & ("ExtensionArray") + equal_na = self.isna() & other.isna() # type: ignore[operator] return bool((equal_values | equal_na).all()) def isin(self, values) -> np.ndarray: @@ -954,7 +972,9 @@ def factorize(self, na_sentinel: int = -1) -> Tuple[np.ndarray, ExtensionArray]: ) uniques = self._from_factorized(uniques, self) - return codes, uniques + # error: Incompatible return value type (got "Tuple[ndarray, ndarray]", + # expected "Tuple[ndarray, ExtensionArray]") + return codes, uniques # type: ignore[return-value] _extension_array_shared_docs[ "repeat" @@ -1136,7 +1156,9 @@ def view(self, dtype: Optional[Dtype] = None) -> ArrayLike: # giving a view with the same dtype as self. if dtype is not None: raise NotImplementedError(dtype) - return self[:] + # error: Incompatible return value type (got "Union[ExtensionArray, Any]", + # expected "ndarray") + return self[:] # type: ignore[return-value] # ------------------------------------------------------------------------ # Printing diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index b37cf0a0ec579..a84b33d3da9af 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -406,14 +406,18 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike: dtype = pandas_dtype(dtype) if isinstance(dtype, ExtensionDtype): - return super().astype(dtype, copy) + # error: Incompatible return value type (got "ExtensionArray", expected + # "ndarray") + return super().astype(dtype, copy) # type: ignore[return-value] if is_bool_dtype(dtype): # astype_nansafe converts np.nan to True if self._hasna: raise ValueError("cannot convert float NaN to bool") else: - return self._data.astype(dtype, copy=copy) + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return self._data.astype(dtype, copy=copy) # type: ignore[return-value] # for integer, error if there are missing values if is_integer_dtype(dtype) and self._hasna: @@ -425,7 +429,12 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike: if is_float_dtype(dtype): na_value = np.nan # coerce - return self.to_numpy(dtype=dtype, na_value=na_value, copy=False) + + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return self.to_numpy( # type: ignore[return-value] + dtype=dtype, na_value=na_value, copy=False + ) def _values_for_argsort(self) -> np.ndarray: """ @@ -613,7 +622,9 @@ def _logical_method(self, other, op): elif op.__name__ in {"xor", "rxor"}: result, mask = ops.kleene_xor(self._data, other, self._mask, mask) - return BooleanArray(result, mask) + # error: Argument 2 to "BooleanArray" has incompatible type "Optional[Any]"; + # expected "ndarray" + return BooleanArray(result, mask) # type: ignore[arg-type] def _cmp_method(self, other, op): from pandas.arrays import ( diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 8c242e3800e48..8588bc9aa94ec 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -412,7 +412,12 @@ def __init__( if null_mask.any(): # We remove null values here, then below will re-insert # them, grep "full_codes" - arr = [values[idx] for idx in np.where(~null_mask)[0]] + + # error: Incompatible types in assignment (expression has type + # "List[Any]", variable has type "ExtensionArray") + arr = [ # type: ignore[assignment] + values[idx] for idx in np.where(~null_mask)[0] + ] arr = sanitize_array(arr, None) values = arr @@ -440,7 +445,9 @@ def __init__( dtype = CategoricalDtype(categories, dtype.ordered) elif is_categorical_dtype(values.dtype): - old_codes = extract_array(values)._codes + # error: Item "ExtensionArray" of "Union[Any, ExtensionArray]" has no + # attribute "_codes" + old_codes = extract_array(values)._codes # type: ignore[union-attr] codes = recode_for_categories( old_codes, values.dtype.categories, dtype.categories, copy=copy ) @@ -504,13 +511,32 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike: raise ValueError("Cannot convert float NaN to integer") elif len(self.codes) == 0 or len(self.categories) == 0: - result = np.array(self, dtype=dtype, copy=copy) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "Categorical") + result = np.array( # type: ignore[assignment] + self, + # error: Argument "dtype" to "array" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[str], Type[float], + # Type[int], Type[complex], Type[bool], Type[object]]"; expected + # "Union[dtype[Any], None, type, _SupportsDType, str, Union[Tuple[Any, + # int], Tuple[Any, Union[int, Sequence[int]]], List[Any], _DTypeDict, + # Tuple[Any, Any]]]" + dtype=dtype, # type: ignore[arg-type] + copy=copy, + ) else: # GH8628 (PERF): astype category codes instead of astyping array try: new_cats = np.asarray(self.categories) - new_cats = new_cats.astype(dtype=dtype, copy=copy) + # error: Argument "dtype" to "astype" of "_ArrayOrScalarCommon" has + # incompatible type "Union[ExtensionDtype, dtype[Any]]"; expected + # "Union[dtype[Any], None, type, _SupportsDType, str, Union[Tuple[Any, + # int], Tuple[Any, Union[int, Sequence[int]]], List[Any], _DTypeDict, + # Tuple[Any, Any]]]" + new_cats = new_cats.astype( + dtype=dtype, copy=copy # type: ignore[arg-type] + ) except ( TypeError, # downstream error msg for CategoricalIndex is misleading ValueError, @@ -518,9 +544,14 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike: msg = f"Cannot cast {self.categories.dtype} dtype to {dtype}" raise ValueError(msg) - result = take_nd(new_cats, libalgos.ensure_platform_int(self._codes)) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "Categorical") + result = take_nd( # type: ignore[assignment] + new_cats, libalgos.ensure_platform_int(self._codes) + ) - return result + # error: Incompatible return value type (got "Categorical", expected "ndarray") + return result # type: ignore[return-value] @cache_readonly def itemsize(self) -> int: @@ -1311,7 +1342,9 @@ def _validate_searchsorted_value(self, value): codes = self._unbox_scalar(value) else: locs = [self.categories.get_loc(x) for x in value] - codes = np.array(locs, dtype=self.codes.dtype) + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "int") + codes = np.array(locs, dtype=self.codes.dtype) # type: ignore[assignment] return codes def _validate_fill_value(self, fill_value): @@ -2126,7 +2159,11 @@ def mode(self, dropna=True): if dropna: good = self._codes != -1 codes = self._codes[good] - codes = sorted(htable.mode_int64(ensure_int64(codes), dropna)) + # error: Incompatible types in assignment (expression has type "List[Any]", + # variable has type "ndarray") + codes = sorted( # type: ignore[assignment] + htable.mode_int64(ensure_int64(codes), dropna) + ) codes = coerce_indexer_dtype(codes, self.dtype.categories) return self._from_backing_data(codes) @@ -2418,7 +2455,11 @@ def _str_get_dummies(self, sep="|"): # sep may not be in categories. Just bail on this. from pandas.core.arrays import PandasArray - return PandasArray(self.astype(str))._str_get_dummies(sep) + # error: Argument 1 to "PandasArray" has incompatible type + # "ExtensionArray"; expected "Union[ndarray, PandasArray]" + return PandasArray(self.astype(str))._str_get_dummies( # type: ignore[arg-type] + sep + ) # The Series.cat accessor @@ -2618,7 +2659,8 @@ def _get_codes_for_values(values, categories: Index) -> np.ndarray: # Only hit here when we've already coerced to object dtypee. hash_klass, vals = get_data_algo(values) - _, cats = get_data_algo(categories) + # error: Value of type variable "ArrayLike" of "get_data_algo" cannot be "Index" + _, cats = get_data_algo(categories) # type: ignore[type-var] t = hash_klass(len(cats)) t.map_locations(cats) return coerce_indexer_dtype(t.lookup(vals), cats) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 633a20d6bed37..c2ac7517ecba3 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -378,7 +378,10 @@ def _get_getitem_freq(self, key): return self._get_getitem_freq(new_key) return freq - def __setitem__( + # error: Argument 1 of "__setitem__" is incompatible with supertype + # "ExtensionArray"; supertype defines the argument type as "Union[int, + # ndarray]" + def __setitem__( # type: ignore[override] self, key: Union[int, Sequence[int], Sequence[bool], slice], value: Union[NaTType, Any, Sequence[Any]], @@ -455,26 +458,45 @@ def view(self, dtype: Optional[Dtype] = None) -> ArrayLike: # dtypes here. Everything else we pass through to the underlying # ndarray. if dtype is None or dtype is self.dtype: - return type(self)(self._ndarray, dtype=self.dtype) + # error: Incompatible return value type (got "DatetimeLikeArrayMixin", + # expected "ndarray") + return type(self)( # type: ignore[return-value] + self._ndarray, dtype=self.dtype + ) if isinstance(dtype, type): # we sometimes pass non-dtype objects, e.g np.ndarray; # pass those through to the underlying ndarray - return self._ndarray.view(dtype) + + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return self._ndarray.view(dtype) # type: ignore[return-value] dtype = pandas_dtype(dtype) if isinstance(dtype, (PeriodDtype, DatetimeTZDtype)): cls = dtype.construct_array_type() - return cls(self.asi8, dtype=dtype) + # error: Incompatible return value type (got "Union[PeriodArray, + # DatetimeArray]", expected "ndarray") + return cls(self.asi8, dtype=dtype) # type: ignore[return-value] elif dtype == "M8[ns]": from pandas.core.arrays import DatetimeArray - return DatetimeArray(self.asi8, dtype=dtype) + # error: Incompatible return value type (got "DatetimeArray", expected + # "ndarray") + return DatetimeArray(self.asi8, dtype=dtype) # type: ignore[return-value] elif dtype == "m8[ns]": from pandas.core.arrays import TimedeltaArray - return TimedeltaArray(self.asi8, dtype=dtype) - return self._ndarray.view(dtype=dtype) + # error: Incompatible return value type (got "TimedeltaArray", expected + # "ndarray") + return TimedeltaArray(self.asi8, dtype=dtype) # type: ignore[return-value] + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + # error: Argument "dtype" to "view" of "_ArrayOrScalarCommon" has incompatible + # type "Union[ExtensionDtype, dtype[Any]]"; expected "Union[dtype[Any], None, + # type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int, + # Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]" + return self._ndarray.view(dtype=dtype) # type: ignore[return-value,arg-type] # ------------------------------------------------------------------ # ExtensionArray Interface @@ -849,7 +871,9 @@ def isin(self, values) -> np.ndarray: # ------------------------------------------------------------------ # Null Handling - def isna(self) -> np.ndarray: + # error: Return type "ndarray" of "isna" incompatible with return type "ArrayLike" + # in supertype "ExtensionArray" + def isna(self) -> np.ndarray: # type: ignore[override] return self._isnan @property # NB: override with cache_readonly in immutable subclasses @@ -864,7 +888,8 @@ def _hasnans(self) -> np.ndarray: """ return if I have any nans; enables various perf speedups """ - return bool(self._isnan.any()) + # error: Incompatible return value type (got "bool", expected "ndarray") + return bool(self._isnan.any()) # type: ignore[return-value] def _maybe_mask_results( self, result: np.ndarray, fill_value=iNaT, convert=None @@ -1208,7 +1233,13 @@ def _addsub_object_array(self, other: np.ndarray, op): res_values = op(self.astype("O"), np.asarray(other)) result = pd_array(res_values.ravel()) - result = extract_array(result, extract_numpy=True).reshape(self.shape) + # error: Item "ExtensionArray" of "Union[Any, ExtensionArray]" has no attribute + # "reshape" + result = extract_array( + result, extract_numpy=True + ).reshape( # type: ignore[union-attr] + self.shape + ) return result def _time_shift(self, periods, freq=None): @@ -1758,7 +1789,8 @@ def _with_freq(self, freq): freq = to_offset(self.inferred_freq) arr = self.view() - arr._freq = freq + # error: "ExtensionArray" has no attribute "_freq" + arr._freq = freq # type: ignore[attr-defined] return arr # -------------------------------------------------------------- diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index ce0ea7bca55cd..7e200097d7e82 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -504,7 +504,10 @@ def _box_func(self, x) -> Union[Timestamp, NaTType]: return Timestamp(x, freq=self.freq, tz=self.tz) @property - def dtype(self) -> Union[np.dtype, DatetimeTZDtype]: + # error: Return type "Union[dtype, DatetimeTZDtype]" of "dtype" + # incompatible with return type "ExtensionDtype" in supertype + # "ExtensionArray" + def dtype(self) -> Union[np.dtype, DatetimeTZDtype]: # type: ignore[override] """ The dtype for the DatetimeArray. diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py index aace5583ff47a..bbe2f23421fcf 100644 --- a/pandas/core/arrays/floating.py +++ b/pandas/core/arrays/floating.py @@ -305,19 +305,27 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike: dtype = pandas_dtype(dtype) if isinstance(dtype, ExtensionDtype): - return super().astype(dtype, copy=copy) + # error: Incompatible return value type (got "ExtensionArray", expected + # "ndarray") + return super().astype(dtype, copy=copy) # type: ignore[return-value] # coerce if is_float_dtype(dtype): # In astype, we consider dtype=float to also mean na_value=np.nan kwargs = {"na_value": np.nan} elif is_datetime64_dtype(dtype): - kwargs = {"na_value": np.datetime64("NaT")} + # error: Dict entry 0 has incompatible type "str": "datetime64"; expected + # "str": "float" + kwargs = {"na_value": np.datetime64("NaT")} # type: ignore[dict-item] else: kwargs = {} - data = self.to_numpy(dtype=dtype, **kwargs) - return astype_nansafe(data, dtype, copy=False) + # error: Argument 2 to "to_numpy" of "BaseMaskedArray" has incompatible + # type "**Dict[str, float]"; expected "bool" + data = self.to_numpy(dtype=dtype, **kwargs) # type: ignore[arg-type] + # error: Incompatible return value type (got "ExtensionArray", expected + # "ndarray") + return astype_nansafe(data, dtype, copy=False) # type: ignore[return-value] def _values_for_argsort(self) -> np.ndarray: return self._data diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index 61d63d2eed6e9..b2308233a6272 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -101,7 +101,17 @@ def _get_common_dtype(self, dtypes: List[DtypeObj]) -> Optional[DtypeObj]: ): return None np_dtype = np.find_common_type( - [t.numpy_dtype if isinstance(t, BaseMaskedDtype) else t for t in dtypes], [] + # error: List comprehension has incompatible type List[Union[Any, + # dtype, ExtensionDtype]]; expected List[Union[dtype, None, type, + # _SupportsDtype, str, Tuple[Any, Union[int, Sequence[int]]], + # List[Any], _DtypeDict, Tuple[Any, Any]]] + [ + t.numpy_dtype # type: ignore[misc] + if isinstance(t, BaseMaskedDtype) + else t + for t in dtypes + ], + [], ) if np.issubdtype(np_dtype, np.integer): return INT_STR_TO_DTYPE[str(np_dtype)] @@ -359,18 +369,26 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike: dtype = pandas_dtype(dtype) if isinstance(dtype, ExtensionDtype): - return super().astype(dtype, copy=copy) + # error: Incompatible return value type (got "ExtensionArray", expected + # "ndarray") + return super().astype(dtype, copy=copy) # type: ignore[return-value] # coerce if is_float_dtype(dtype): # In astype, we consider dtype=float to also mean na_value=np.nan na_value = np.nan elif is_datetime64_dtype(dtype): - na_value = np.datetime64("NaT") + # error: Incompatible types in assignment (expression has type + # "datetime64", variable has type "float") + na_value = np.datetime64("NaT") # type: ignore[assignment] else: na_value = lib.no_default - return self.to_numpy(dtype=dtype, na_value=na_value, copy=False) + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return self.to_numpy( # type: ignore[return-value] + dtype=dtype, na_value=na_value, copy=False + ) def _values_for_argsort(self) -> np.ndarray: """ diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index f192a34514390..7ccdad11761ab 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -641,7 +641,11 @@ def __getitem__(self, key): if is_scalar(left) and isna(left): return self._fill_value return Interval(left, right, self.closed) - if np.ndim(left) > 1: + # error: Argument 1 to "ndim" has incompatible type "Union[ndarray, + # ExtensionArray]"; expected "Union[Union[int, float, complex, str, bytes, + # generic], Sequence[Union[int, float, complex, str, bytes, generic]], + # Sequence[Sequence[Any]], _SupportsArray]" + if np.ndim(left) > 1: # type: ignore[arg-type] # GH#30588 multi-dimensional indexer disallowed raise ValueError("multi-dimensional indexing not allowed") return self._shallow_copy(left, right) @@ -907,7 +911,9 @@ def copy(self: IntervalArrayT) -> IntervalArrayT: # TODO: Could skip verify_integrity here. return type(self).from_arrays(left, right, closed=closed) - def isna(self) -> np.ndarray: + # error: Return type "ndarray" of "isna" incompatible with return type + # "ArrayLike" in supertype "ExtensionArray" + def isna(self) -> np.ndarray: # type: ignore[override] return isna(self._left) def shift( @@ -1612,7 +1618,10 @@ def _maybe_convert_platform_interval(values) -> ArrayLike: # GH 19016 # empty lists/tuples get object dtype by default, but this is # prohibited for IntervalArray, so coerce to integer instead - return np.array([], dtype=np.int64) + + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return np.array([], dtype=np.int64) # type: ignore[return-value] elif not is_list_like(values) or isinstance(values, ABCDataFrame): # This will raise later, but we avoid passing to maybe_convert_platform return values @@ -1624,4 +1633,5 @@ def _maybe_convert_platform_interval(values) -> ArrayLike: else: values = extract_array(values, extract_numpy=True) - return maybe_convert_platform(values) + # error: Incompatible return value type (got "ExtensionArray", expected "ndarray") + return maybe_convert_platform(values) # type: ignore[return-value] diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index eff06a5c62894..ac0ac2bb21d62 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -212,7 +212,10 @@ def __len__(self) -> int: def __invert__(self: BaseMaskedArrayT) -> BaseMaskedArrayT: return type(self)(~self._data, self._mask.copy()) - def to_numpy( + # error: Argument 1 of "to_numpy" is incompatible with supertype "ExtensionArray"; + # supertype defines the argument type as "Union[ExtensionDtype, str, dtype[Any], + # Type[str], Type[float], Type[int], Type[complex], Type[bool], Type[object], None]" + def to_numpy( # type: ignore[override] self, dtype: Optional[NpDtype] = None, copy: bool = False, @@ -281,7 +284,9 @@ def to_numpy( if na_value is lib.no_default: na_value = libmissing.NA if dtype is None: - dtype = object + # error: Incompatible types in assignment (expression has type + # "Type[object]", variable has type "Union[str, dtype[Any], None]") + dtype = object # type: ignore[assignment] if self._hasna: if ( not is_object_dtype(dtype) @@ -305,8 +310,12 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike: if is_dtype_equal(dtype, self.dtype): if copy: - return self.copy() - return self + # error: Incompatible return value type (got "BaseMaskedArray", expected + # "ndarray") + return self.copy() # type: ignore[return-value] + # error: Incompatible return value type (got "BaseMaskedArray", expected + # "ndarray") + return self # type: ignore[return-value] # if we are astyping to another nullable masked dtype, we can fastpath if isinstance(dtype, BaseMaskedDtype): @@ -316,7 +325,9 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike: # not directly depending on the `copy` keyword mask = self._mask if data is self._data else self._mask.copy() cls = dtype.construct_array_type() - return cls(data, mask, copy=False) + # error: Incompatible return value type (got "BaseMaskedArray", expected + # "ndarray") + return cls(data, mask, copy=False) # type: ignore[return-value] if isinstance(dtype, ExtensionDtype): eacls = dtype.construct_array_type() @@ -346,9 +357,13 @@ def _hasna(self) -> bool: # Note: this is expensive right now! The hope is that we can # make this faster by having an optional mask, but not have to change # source code using it.. - return self._mask.any() - def isna(self) -> np.ndarray: + # error: Incompatible return value type (got "bool_", expected "bool") + return self._mask.any() # type: ignore[return-value] + + # error: Return type "ndarray" of "isna" incompatible with return type + # "ArrayLike" in supertype "ExtensionArray" + def isna(self) -> np.ndarray: # type: ignore[override] return self._mask @property @@ -394,7 +409,9 @@ def take( return type(self)(result, mask, copy=False) - def isin(self, values) -> BooleanArray: + # error: Return type "BooleanArray" of "isin" incompatible with return type + # "ndarray" in supertype "ExtensionArray" + def isin(self, values) -> BooleanArray: # type: ignore[override] from pandas.core.arrays import BooleanArray @@ -404,7 +421,9 @@ def isin(self, values) -> BooleanArray: result += self._mask else: result *= np.invert(self._mask) - mask = np.zeros_like(self, dtype=bool) + # error: No overload variant of "zeros_like" matches argument types + # "BaseMaskedArray", "Type[bool]" + mask = np.zeros_like(self, dtype=bool) # type: ignore[call-overload] return BooleanArray(result, mask, copy=False) def copy(self: BaseMaskedArrayT) -> BaseMaskedArrayT: @@ -422,8 +441,14 @@ def factorize(self, na_sentinel: int = -1) -> Tuple[np.ndarray, ExtensionArray]: # the hashtables don't handle all different types of bits uniques = uniques.astype(self.dtype.numpy_dtype, copy=False) - uniques = type(self)(uniques, np.zeros(len(uniques), dtype=bool)) - return codes, uniques + # error: Incompatible types in assignment (expression has type + # "BaseMaskedArray", variable has type "ndarray") + uniques = type(self)( # type: ignore[assignment] + uniques, np.zeros(len(uniques), dtype=bool) + ) + # error: Incompatible return value type (got "Tuple[ndarray, ndarray]", + # expected "Tuple[ndarray, ExtensionArray]") + return codes, uniques # type: ignore[return-value] def value_counts(self, dropna: bool = True) -> Series: """ diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index fd95ab987b18a..bef047c29413b 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -97,7 +97,12 @@ def _from_sequence( if isinstance(dtype, PandasDtype): dtype = dtype._dtype - result = np.asarray(scalars, dtype=dtype) + # error: Argument "dtype" to "asarray" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], dtype[floating[_64Bit]], Type[object], + # None]"; expected "Union[dtype[Any], None, type, _SupportsDType, str, + # Union[Tuple[Any, int], Tuple[Any, Union[int, Sequence[int]]], List[Any], + # _DTypeDict, Tuple[Any, Any]]]" + result = np.asarray(scalars, dtype=dtype) # type: ignore[arg-type] if ( result.ndim > 1 and not hasattr(scalars, "dtype") @@ -185,7 +190,9 @@ def __array_ufunc__(self, ufunc, method: str, *inputs, **kwargs): # ------------------------------------------------------------------------ # Pandas ExtensionArray Interface - def isna(self) -> np.ndarray: + # error: Return type "ndarray" of "isna" incompatible with return type + # "ArrayLike" in supertype "ExtensionArray" + def isna(self) -> np.ndarray: # type: ignore[override] return isna(self._ndarray) def _validate_fill_value(self, fill_value): @@ -341,7 +348,10 @@ def skew( # ------------------------------------------------------------------------ # Additional Methods - def to_numpy( + # error: Argument 1 of "to_numpy" is incompatible with supertype "ExtensionArray"; + # supertype defines the argument type as "Union[ExtensionDtype, str, dtype[Any], + # Type[str], Type[float], Type[int], Type[complex], Type[bool], Type[object], None]" + def to_numpy( # type: ignore[override] self, dtype: Optional[NpDtype] = None, copy: bool = False, diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index 7e9e13400e11f..d91522a9e1bb6 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -1125,9 +1125,12 @@ def _make_field_arrays(*fields): elif length is None: length = len(x) + # error: Argument 2 to "repeat" has incompatible type "Optional[int]"; expected + # "Union[Union[int, integer[Any]], Union[bool, bool_], ndarray, Sequence[Union[int, + # integer[Any]]], Sequence[Union[bool, bool_]], Sequence[Sequence[Any]]]" return [ np.asarray(x) if isinstance(x, (np.ndarray, list, ABCSeries)) - else np.repeat(x, length) + else np.repeat(x, length) # type: ignore[arg-type] for x in fields ] diff --git a/pandas/core/arrays/sparse/accessor.py b/pandas/core/arrays/sparse/accessor.py index c3d11793dbd8c..d4faea4fbc42c 100644 --- a/pandas/core/arrays/sparse/accessor.py +++ b/pandas/core/arrays/sparse/accessor.py @@ -354,7 +354,9 @@ def density(self) -> float: """ Ratio of non-sparse points to total (dense) data points. """ - return np.mean([column.array.density for _, column in self._parent.items()]) + # error: Incompatible return value type (got "number", expected "float") + tmp = np.mean([column.array.density for _, column in self._parent.items()]) + return tmp # type: ignore[return-value] @staticmethod def _prep_index(data, index, columns): diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index a209037f9a9a6..088a1165e4df0 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -365,7 +365,12 @@ def __init__( # dtype inference if data is None: # TODO: What should the empty dtype be? Object or float? - data = np.array([], dtype=dtype) + + # error: Argument "dtype" to "array" has incompatible type + # "Union[ExtensionDtype, dtype[Any], None]"; expected "Union[dtype[Any], + # None, type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, + # Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]" + data = np.array([], dtype=dtype) # type: ignore[arg-type] if not is_array_like(data): try: @@ -394,7 +399,14 @@ def __init__( if isinstance(data, type(self)) and sparse_index is None: sparse_index = data._sparse_index - sparse_values = np.asarray(data.sp_values, dtype=dtype) + # error: Argument "dtype" to "asarray" has incompatible type + # "Union[ExtensionDtype, dtype[Any], Type[object], None]"; expected + # "Union[dtype[Any], None, type, _SupportsDType, str, Union[Tuple[Any, int], + # Tuple[Any, Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, + # Any]]]" + sparse_values = np.asarray( + data.sp_values, dtype=dtype # type: ignore[arg-type] + ) elif sparse_index is None: data = extract_array(data, extract_numpy=True) if not isinstance(data, np.ndarray): @@ -412,10 +424,21 @@ def __init__( fill_value = np.datetime64("NaT", "ns") data = np.asarray(data) sparse_values, sparse_index, fill_value = make_sparse( - data, kind=kind, fill_value=fill_value, dtype=dtype + # error: Argument "dtype" to "make_sparse" has incompatible type + # "Union[ExtensionDtype, dtype[Any], Type[object], None]"; expected + # "Union[str, dtype[Any], None]" + data, + kind=kind, + fill_value=fill_value, + dtype=dtype, # type: ignore[arg-type] ) else: - sparse_values = np.asarray(data, dtype=dtype) + # error: Argument "dtype" to "asarray" has incompatible type + # "Union[ExtensionDtype, dtype[Any], Type[object], None]"; expected + # "Union[dtype[Any], None, type, _SupportsDType, str, Union[Tuple[Any, int], + # Tuple[Any, Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, + # Any]]]" + sparse_values = np.asarray(data, dtype=dtype) # type: ignore[arg-type] if len(sparse_values) != sparse_index.npoints: raise AssertionError( f"Non array-like type {type(sparse_values)} must " @@ -503,7 +526,9 @@ def __array__(self, dtype: Optional[NpDtype] = None) -> np.ndarray: try: dtype = np.result_type(self.sp_values.dtype, type(fill_value)) except TypeError: - dtype = object + # error: Incompatible types in assignment (expression has type + # "Type[object]", variable has type "Union[str, dtype[Any], None]") + dtype = object # type: ignore[assignment] out = np.full(self.shape, fill_value, dtype=dtype) out[self.sp_index.to_int_index().indices] = self.sp_values @@ -748,7 +773,9 @@ def factorize(self, na_sentinel=-1): # Given that we have to return a dense array of codes, why bother # implementing an efficient factorize? codes, uniques = algos.factorize(np.asarray(self), na_sentinel=na_sentinel) - uniques = SparseArray(uniques, dtype=self.dtype) + # error: Incompatible types in assignment (expression has type "SparseArray", + # variable has type "Union[ndarray, Index]") + uniques = SparseArray(uniques, dtype=self.dtype) # type: ignore[assignment] return codes, uniques def value_counts(self, dropna: bool = True): @@ -857,7 +884,9 @@ def take(self, indices, *, allow_fill=False, fill_value=None) -> SparseArray: result = self._take_with_fill(indices, fill_value=fill_value) kwargs = {} else: - result = self._take_without_fill(indices) + # error: Incompatible types in assignment (expression has type + # "Union[ndarray, SparseArray]", variable has type "ndarray") + result = self._take_without_fill(indices) # type: ignore[assignment] kwargs = {"dtype": self.dtype} return type(self)(result, fill_value=self.fill_value, kind=self.kind, **kwargs) @@ -1094,14 +1123,38 @@ def astype(self, dtype: Optional[Dtype] = None, copy=True): else: return self.copy() dtype = self.dtype.update_dtype(dtype) - subtype = pandas_dtype(dtype._subtype_with_str) + # error: Item "ExtensionDtype" of "Union[ExtensionDtype, str, dtype[Any], + # Type[str], Type[float], Type[int], Type[complex], Type[bool], Type[object], + # None]" has no attribute "_subtype_with_str" + # error: Item "str" of "Union[ExtensionDtype, str, dtype[Any], Type[str], + # Type[float], Type[int], Type[complex], Type[bool], Type[object], None]" has no + # attribute "_subtype_with_str" + # error: Item "dtype[Any]" of "Union[ExtensionDtype, str, dtype[Any], Type[str], + # Type[float], Type[int], Type[complex], Type[bool], Type[object], None]" has no + # attribute "_subtype_with_str" + # error: Item "ABCMeta" of "Union[ExtensionDtype, str, dtype[Any], Type[str], + # Type[float], Type[int], Type[complex], Type[bool], Type[object], None]" has no + # attribute "_subtype_with_str" + # error: Item "type" of "Union[ExtensionDtype, str, dtype[Any], Type[str], + # Type[float], Type[int], Type[complex], Type[bool], Type[object], None]" has no + # attribute "_subtype_with_str" + # error: Item "None" of "Union[ExtensionDtype, str, dtype[Any], Type[str], + # Type[float], Type[int], Type[complex], Type[bool], Type[object], None]" has no + # attribute "_subtype_with_str" + subtype = pandas_dtype(dtype._subtype_with_str) # type: ignore[union-attr] # TODO copy=False is broken for astype_nansafe with int -> float, so cannot # passthrough copy keyword: https://github.com/pandas-dev/pandas/issues/34456 sp_values = astype_nansafe(self.sp_values, subtype, copy=True) - if sp_values is self.sp_values and copy: + # error: Non-overlapping identity check (left operand type: "ExtensionArray", + # right operand t...ype: "ndarray") + if sp_values is self.sp_values and copy: # type: ignore[comparison-overlap] sp_values = sp_values.copy() - return self._simple_new(sp_values, self.sp_index, dtype) + # error: Argument 1 to "_simple_new" of "SparseArray" has incompatible type + # "ExtensionArray"; expected "ndarray" + return self._simple_new( + sp_values, self.sp_index, dtype # type: ignore[arg-type] + ) def map(self, mapper): """ @@ -1396,7 +1449,11 @@ def __array_ufunc__(self, ufunc, method, *inputs, **kwargs): return type(self)(result) def __abs__(self): - return np.abs(self) + # error: Argument 1 to "__call__" of "ufunc" has incompatible type + # "SparseArray"; expected "Union[Union[int, float, complex, str, bytes, + # generic], Sequence[Union[int, float, complex, str, bytes, generic]], + # Sequence[Sequence[Any]], _SupportsArray]" + return np.abs(self) # type: ignore[arg-type] # ------------------------------------------------------------------------ # Ops @@ -1545,7 +1602,11 @@ def make_sparse( index = make_sparse_index(length, indices, kind) sparsified_values = arr[mask] if dtype is not None: - sparsified_values = astype_nansafe(sparsified_values, dtype=dtype) + # error: Argument "dtype" to "astype_nansafe" has incompatible type "Union[str, + # dtype[Any]]"; expected "Union[dtype[Any], ExtensionDtype]" + sparsified_values = astype_nansafe( + sparsified_values, dtype=dtype # type: ignore[arg-type] + ) # TODO: copy return sparsified_values, index, fill_value diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py index 948edcbd99e64..9e61675002e64 100644 --- a/pandas/core/arrays/sparse/dtype.py +++ b/pandas/core/arrays/sparse/dtype.py @@ -342,7 +342,10 @@ def update_dtype(self, dtype): if is_extension_array_dtype(dtype): raise TypeError("sparse arrays of extension dtypes not supported") - fill_value = astype_nansafe(np.array(self.fill_value), dtype).item() + # error: "ExtensionArray" has no attribute "item" + fill_value = astype_nansafe( + np.array(self.fill_value), dtype + ).item() # type: ignore[attr-defined] dtype = cls(dtype, fill_value=fill_value) return dtype diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index 6fd68050bc8dc..67cd6c63c1faa 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -320,7 +320,9 @@ def astype(self, dtype, copy=True): values = arr.astype(dtype.numpy_dtype) return IntegerArray(values, mask, copy=False) elif isinstance(dtype, FloatingDtype): - arr = self.copy() + # error: Incompatible types in assignment (expression has type + # "StringArray", variable has type "ndarray") + arr = self.copy() # type: ignore[assignment] mask = self.isna() arr[mask] = "0" values = arr.astype(dtype.numpy_dtype) @@ -434,7 +436,12 @@ def _str_map(self, f, na_value=None, dtype: Optional[Dtype] = None): mask.view("uint8"), convert=False, na_value=na_value, - dtype=np.dtype(dtype), + # error: Value of type variable "_DTypeScalar" of "dtype" cannot be + # "object" + # error: Argument 1 to "dtype" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[object]]"; expected + # "Type[object]" + dtype=np.dtype(dtype), # type: ignore[type-var,arg-type] ) if not na_value_is_na: diff --git a/pandas/core/arrays/string_arrow.py b/pandas/core/arrays/string_arrow.py index e003efeabcb66..efdc18cd071b5 100644 --- a/pandas/core/arrays/string_arrow.py +++ b/pandas/core/arrays/string_arrow.py @@ -248,7 +248,10 @@ def __arrow_array__(self, type=None): """Convert myself to a pyarrow Array or ChunkedArray.""" return self._data - def to_numpy( + # error: Argument 1 of "to_numpy" is incompatible with supertype "ExtensionArray"; + # supertype defines the argument type as "Union[ExtensionDtype, str, dtype[Any], + # Type[str], Type[float], Type[int], Type[complex], Type[bool], Type[object], None]" + def to_numpy( # type: ignore[override] self, dtype: Optional[NpDtype] = None, copy: bool = False, @@ -341,7 +344,9 @@ def __getitem__(self, item: Any) -> Any: if not len(item): return type(self)(pa.chunked_array([], type=pa.string())) elif is_integer_dtype(item.dtype): - return self.take(item) + # error: Argument 1 to "take" of "ArrowStringArray" has incompatible + # type "ndarray"; expected "Sequence[int]" + return self.take(item) # type: ignore[arg-type] elif is_bool_dtype(item.dtype): return type(self)(self._data.filter(item)) else: @@ -400,7 +405,13 @@ def fillna(self, value=None, method=None, limit=None): if mask.any(): if method is not None: func = missing.get_fill_func(method) - new_values, _ = func(self.to_numpy(object), limit=limit, mask=mask) + # error: Argument 1 to "to_numpy" of "ArrowStringArray" has incompatible + # type "Type[object]"; expected "Union[str, dtype[Any], None]" + new_values, _ = func( + self.to_numpy(object), # type: ignore[arg-type] + limit=limit, + mask=mask, + ) new_values = self._from_sequence(new_values) else: # fill with value @@ -423,7 +434,9 @@ def nbytes(self) -> int: """ return self._data.nbytes - def isna(self) -> np.ndarray: + # error: Return type "ndarray" of "isna" incompatible with return type "ArrayLike" + # in supertype "ExtensionArray" + def isna(self) -> np.ndarray: # type: ignore[override] """ Boolean NumPy array indicating if each value is missing. @@ -498,7 +511,8 @@ def __setitem__(self, key: Union[int, np.ndarray], value: Any) -> None: # Slice data and insert in-between new_data = [ - *self._data[0:key].chunks, + # error: Slice index must be an integer or None + *self._data[0:key].chunks, # type: ignore[misc] pa.array([value], type=pa.string()), *self._data[(key + 1) :].chunks, ] @@ -589,7 +603,9 @@ def take( if not is_array_like(indices): indices_array = np.asanyarray(indices) else: - indices_array = indices + # error: Incompatible types in assignment (expression has type + # "Sequence[int]", variable has type "ndarray") + indices_array = indices # type: ignore[assignment] if len(self._data) == 0 and (indices_array >= 0).any(): raise IndexError("cannot do a non-empty take") diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index c371e27eeceac..5a45a8d105f6e 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -148,7 +148,9 @@ def _box_func(self, x) -> Union[Timedelta, NaTType]: return Timedelta(x, unit="ns") @property - def dtype(self) -> np.dtype: + # error: Return type "dtype" of "dtype" incompatible with return type + # "ExtensionDtype" in supertype "ExtensionArray" + def dtype(self) -> np.dtype: # type: ignore[override] """ The dtype for the TimedeltaArray. @@ -666,7 +668,11 @@ def __floordiv__(self, other): return result elif is_object_dtype(other.dtype): - result = [self[n] // other[n] for n in range(len(self))] + # error: Incompatible types in assignment (expression has type + # "List[Any]", variable has type "ndarray") + result = [ # type: ignore[assignment] + self[n] // other[n] for n in range(len(self)) + ] result = np.array(result) if lib.infer_dtype(result, skipna=False) == "timedelta": result, _ = sequence_to_td64ns(result) @@ -720,7 +726,11 @@ def __rfloordiv__(self, other): return result elif is_object_dtype(other.dtype): - result = [other[n] // self[n] for n in range(len(self))] + # error: Incompatible types in assignment (expression has type + # "List[Any]", variable has type "ndarray") + result = [ # type: ignore[assignment] + other[n] // self[n] for n in range(len(self)) + ] result = np.array(result) return result diff --git a/pandas/core/base.py b/pandas/core/base.py index c02f7bb2edf58..1943aafc7c760 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -617,7 +617,12 @@ def to_numpy( f"to_numpy() got an unexpected keyword argument '{bad_keys}'" ) - result = np.asarray(self._values, dtype=dtype) + # error: Argument "dtype" to "asarray" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[str], Type[float], Type[int], + # Type[complex], Type[bool], Type[object], None]"; expected "Union[dtype[Any], + # None, type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int, + # Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]" + result = np.asarray(self._values, dtype=dtype) # type: ignore[arg-type] # TODO(GH-24345): Avoid potential double copy if copy or na_value is not lib.no_default: result = result.copy() @@ -730,12 +735,17 @@ def argmax(self, axis=None, skipna: bool = True, *args, **kwargs) -> int: skipna = nv.validate_argmax_with_skipna(skipna, args, kwargs) if isinstance(delegate, ExtensionArray): - if not skipna and delegate.isna().any(): + # error: "ExtensionArray" has no attribute "any" + if not skipna and delegate.isna().any(): # type: ignore[attr-defined] return -1 else: return delegate.argmax() else: - return nanops.nanargmax(delegate, skipna=skipna) + # error: Incompatible return value type (got "Union[int, ndarray]", expected + # "int") + return nanops.nanargmax( # type: ignore[return-value] + delegate, skipna=skipna + ) def min(self, axis=None, skipna: bool = True, *args, **kwargs): """ @@ -788,12 +798,17 @@ def argmin(self, axis=None, skipna=True, *args, **kwargs) -> int: skipna = nv.validate_argmin_with_skipna(skipna, args, kwargs) if isinstance(delegate, ExtensionArray): - if not skipna and delegate.isna().any(): + # error: "ExtensionArray" has no attribute "any" + if not skipna and delegate.isna().any(): # type: ignore[attr-defined] return -1 else: return delegate.argmin() else: - return nanops.nanargmin(delegate, skipna=skipna) + # error: Incompatible return value type (got "Union[int, ndarray]", expected + # "int") + return nanops.nanargmin( # type: ignore[return-value] + delegate, skipna=skipna + ) def tolist(self): """ @@ -1318,4 +1333,6 @@ def drop_duplicates(self, keep="first"): return self[~duplicated] # type: ignore[index] def duplicated(self, keep: Union[str, bool] = "first") -> np.ndarray: - return duplicated(self._values, keep=keep) + # error: Value of type variable "ArrayLike" of "duplicated" cannot be + # "Union[ExtensionArray, ndarray]" + return duplicated(self._values, keep=keep) # type: ignore[type-var] diff --git a/pandas/core/common.py b/pandas/core/common.py index 0b2dec371bf02..83848e0532253 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -228,9 +228,16 @@ def asarray_tuplesafe(values, dtype: Optional[NpDtype] = None) -> np.ndarray: if not (isinstance(values, (list, tuple)) or hasattr(values, "__array__")): values = list(values) elif isinstance(values, ABCIndex): - return values._values - - if isinstance(values, list) and dtype in [np.object_, object]: + # error: Incompatible return value type (got "Union[ExtensionArray, ndarray]", + # expected "ndarray") + return values._values # type: ignore[return-value] + + # error: Non-overlapping container check (element type: "Union[str, dtype[Any], + # None]", container item type: "type") + if isinstance(values, list) and dtype in [ # type: ignore[comparison-overlap] + np.object_, + object, + ]: return construct_1d_object_array_from_listlike(values) result = np.asarray(values, dtype=dtype) diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 43900709ad11f..46f32ee401603 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -306,7 +306,17 @@ def array( # Note: we exclude np.ndarray here, will do type inference on it dtype = data.dtype - data = extract_array(data, extract_numpy=True) + # error: Value of type variable "AnyArrayLike" of "extract_array" cannot be + # "Union[Sequence[object], ExtensionArray]" + # error: Value of type variable "AnyArrayLike" of "extract_array" cannot be + # "Union[Sequence[object], Index]" + # error: Incompatible types in assignment (expression has type "ExtensionArray", + # variable has type "Union[Sequence[object], Index]") + # error: Incompatible types in assignment (expression has type "ExtensionArray", + # variable has type "Union[Sequence[object], Series]") + # error: Incompatible types in assignment (expression has type "ExtensionArray", + # variable has type "Union[Sequence[object], ndarray]") + data = extract_array(data, extract_numpy=True) # type: ignore[type-var,assignment] # this returns None for not-found dtypes. if isinstance(dtype, str): @@ -500,7 +510,9 @@ def sanitize_array( try: subarr = _try_cast(data, dtype, copy, True) except ValueError: - subarr = np.array(data, copy=copy) + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "ExtensionArray") + subarr = np.array(data, copy=copy) # type: ignore[assignment] else: # we will try to copy by-definition here subarr = _try_cast(data, dtype, copy, raise_cast_failure) @@ -513,7 +525,9 @@ def sanitize_array( subarr = subarr.astype(dtype, copy=copy) elif copy: subarr = subarr.copy() - return subarr + # error: Incompatible return value type (got "ExtensionArray", expected + # "ndarray") + return subarr # type: ignore[return-value] elif isinstance(data, (list, tuple, abc.Set, abc.ValuesView)) and len(data) > 0: # TODO: deque, array.array @@ -526,7 +540,10 @@ def sanitize_array( subarr = _try_cast(data, dtype, copy, raise_cast_failure) else: subarr = maybe_convert_platform(data) - subarr = maybe_cast_to_datetime(subarr, dtype) + # error: Incompatible types in assignment (expression has type + # "Union[ExtensionArray, ndarray, List[Any]]", variable has type + # "ExtensionArray") + subarr = maybe_cast_to_datetime(subarr, dtype) # type: ignore[assignment] elif isinstance(data, range): # GH#16804 @@ -547,7 +564,13 @@ def sanitize_array( subarr = _sanitize_ndim(subarr, data, dtype, index) if not (is_extension_array_dtype(subarr.dtype) or is_extension_array_dtype(dtype)): - subarr = _sanitize_str_dtypes(subarr, data, dtype, copy) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + # error: Argument 1 to "_sanitize_str_dtypes" has incompatible type + # "ExtensionArray"; expected "ndarray" + subarr = _sanitize_str_dtypes( # type: ignore[assignment] + subarr, data, dtype, copy # type: ignore[arg-type] + ) is_object_or_str_dtype = is_object_dtype(dtype) or is_string_dtype(dtype) if is_object_dtype(subarr.dtype) and not is_object_or_str_dtype: @@ -556,7 +579,8 @@ def sanitize_array( subarr = array(subarr) subarr = extract_array(subarr, extract_numpy=True) - return subarr + # error: Incompatible return value type (got "ExtensionArray", expected "ndarray") + return subarr # type: ignore[return-value] def _sanitize_ndim( @@ -577,11 +601,25 @@ def _sanitize_ndim( raise ValueError("Data must be 1-dimensional") if is_object_dtype(dtype) and isinstance(dtype, ExtensionDtype): # i.e. PandasDtype("O") - result = com.asarray_tuplesafe(data, dtype=object) + + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + # error: Argument "dtype" to "asarray_tuplesafe" has incompatible type + # "Type[object]"; expected "Union[str, dtype[Any], None]" + result = com.asarray_tuplesafe( # type: ignore[assignment] + data, dtype=object # type: ignore[arg-type] + ) cls = dtype.construct_array_type() result = cls._from_sequence(result, dtype=dtype) else: - result = com.asarray_tuplesafe(data, dtype=dtype) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + # error: Argument "dtype" to "asarray_tuplesafe" has incompatible type + # "Union[dtype[Any], ExtensionDtype, None]"; expected "Union[str, + # dtype[Any], None]" + result = com.asarray_tuplesafe( # type: ignore[assignment] + data, dtype=dtype # type: ignore[arg-type] + ) return result @@ -600,7 +638,11 @@ def _sanitize_str_dtypes( # GH#19853: If data is a scalar, result has already the result if not lib.is_scalar(data): if not np.all(isna(data)): - data = np.array(data, dtype=dtype, copy=False) + # error: Argument "dtype" to "array" has incompatible type + # "Union[dtype[Any], ExtensionDtype, None]"; expected "Union[dtype[Any], + # None, type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, + # Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]" + data = np.array(data, dtype=dtype, copy=False) # type: ignore[arg-type] result = np.array(data, dtype=object, copy=copy) return result @@ -647,7 +689,9 @@ def _try_cast( and not copy and dtype is None ): - return arr + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return arr # type: ignore[return-value] if isinstance(dtype, ExtensionDtype) and (dtype.kind != "M" or is_sparse(dtype)): # create an extension array from its dtype @@ -666,7 +710,12 @@ def _try_cast( # that we can convert the data to the requested dtype. if is_integer_dtype(dtype): # this will raise if we have e.g. floats - maybe_cast_to_integer_array(arr, dtype) + + # error: Argument 2 to "maybe_cast_to_integer_array" has incompatible type + # "Union[dtype, ExtensionDtype, None]"; expected "Union[ExtensionDtype, str, + # dtype, Type[str], Type[float], Type[int], Type[complex], Type[bool], + # Type[object]]" + maybe_cast_to_integer_array(arr, dtype) # type: ignore[arg-type] subarr = arr else: subarr = maybe_cast_to_datetime(arr, dtype) diff --git a/pandas/core/describe.py b/pandas/core/describe.py index 3a872c6202e04..57a33e7f90e51 100644 --- a/pandas/core/describe.py +++ b/pandas/core/describe.py @@ -192,7 +192,9 @@ def _select_data(self): # when some numerics are found, keep only numerics default_include = [np.number] if self.datetime_is_numeric: - default_include.append("datetime") + # error: Argument 1 to "append" of "list" has incompatible type "str"; + # expected "Type[number[Any]]" + default_include.append("datetime") # type: ignore[arg-type] data = self.obj.select_dtypes(include=default_include) if len(data.columns) == 0: data = self.obj @@ -232,7 +234,10 @@ def describe_numeric_1d(series: Series, percentiles: Sequence[float]) -> Series: """ from pandas import Series - formatted_percentiles = format_percentiles(percentiles) + # error: Argument 1 to "format_percentiles" has incompatible type "Sequence[float]"; + # expected "Union[ndarray, List[Union[int, float]], List[float], List[Union[str, + # float]]]" + formatted_percentiles = format_percentiles(percentiles) # type: ignore[arg-type] stat_index = ["count", "mean", "std", "min"] + formatted_percentiles + ["max"] d = ( @@ -336,7 +341,10 @@ def describe_timestamp_1d(data: Series, percentiles: Sequence[float]) -> Series: # GH-30164 from pandas import Series - formatted_percentiles = format_percentiles(percentiles) + # error: Argument 1 to "format_percentiles" has incompatible type "Sequence[float]"; + # expected "Union[ndarray, List[Union[int, float]], List[float], List[Union[str, + # float]]]" + formatted_percentiles = format_percentiles(percentiles) # type: ignore[arg-type] stat_index = ["count", "mean", "min"] + formatted_percentiles + ["max"] d = ( @@ -392,7 +400,9 @@ def refine_percentiles(percentiles: Optional[Sequence[float]]) -> Sequence[float The percentiles to include in the output. """ if percentiles is None: - return np.array([0.25, 0.5, 0.75]) + # error: Incompatible return value type (got "ndarray", expected + # "Sequence[float]") + return np.array([0.25, 0.5, 0.75]) # type: ignore[return-value] # explicit conversion of `percentiles` to list percentiles = list(percentiles) @@ -404,7 +414,9 @@ def refine_percentiles(percentiles: Optional[Sequence[float]]) -> Sequence[float if 0.5 not in percentiles: percentiles.append(0.5) - percentiles = np.asarray(percentiles) + # error: Incompatible types in assignment (expression has type "ndarray", variable + # has type "Optional[Sequence[float]]") + percentiles = np.asarray(percentiles) # type: ignore[assignment] # sort and check for duplicates unique_pcts = np.unique(percentiles) diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 6eca89e1a8744..c5d672b207369 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -128,12 +128,16 @@ def maybe_convert_platform( else: # The caller is responsible for ensuring that we have np.ndarray # or ExtensionArray here. - arr = values + + # error: Incompatible types in assignment (expression has type "Union[ndarray, + # ExtensionArray]", variable has type "ndarray") + arr = values # type: ignore[assignment] if arr.dtype == object: arr = lib.maybe_convert_objects(arr) - return arr + # error: Incompatible return value type (got "ndarray", expected "ExtensionArray") + return arr # type: ignore[return-value] def is_nested_object(obj) -> bool: @@ -279,7 +283,9 @@ def maybe_downcast_to_dtype( with suppress(TypeError): # e.g. TypeError: int() argument must be a string, a # bytes-like object or a number, not 'Period - return PeriodArray(result, freq=dtype.freq) + + # error: "dtype[Any]" has no attribute "freq" + return PeriodArray(result, freq=dtype.freq) # type: ignore[attr-defined] converted = maybe_downcast_numeric(result, dtype, do_round) if converted is not result: @@ -406,11 +412,20 @@ def maybe_cast_result( ): # We have to special case categorical so as not to upcast # things like counts back to categorical - cls = dtype.construct_array_type() - result = maybe_cast_to_extension_array(cls, result, dtype=dtype) + + # error: Item "dtype[Any]" of "Union[dtype[Any], ExtensionDtype]" has no + # attribute "construct_array_type" + cls = dtype.construct_array_type() # type: ignore[union-attr] + # error: Argument "dtype" to "maybe_cast_to_extension_array" has incompatible + # type "Union[dtype[Any], ExtensionDtype]"; expected "Optional[ExtensionDtype]" + result = maybe_cast_to_extension_array( + cls, result, dtype=dtype # type: ignore[arg-type] + ) elif numeric_only and is_numeric_dtype(dtype) or not numeric_only: - result = maybe_downcast_to_dtype(result, dtype) + # error: Argument 2 to "maybe_downcast_to_dtype" has incompatible type + # "Union[dtype[Any], ExtensionDtype]"; expected "Union[str, dtype[Any]]" + result = maybe_downcast_to_dtype(result, dtype) # type: ignore[arg-type] return result @@ -532,7 +547,11 @@ def maybe_upcast_putmask(result: np.ndarray, mask: np.ndarray) -> np.ndarray: new_dtype = ensure_dtype_can_hold_na(result.dtype) if new_dtype != result.dtype: - result = result.astype(new_dtype, copy=True) + # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has incompatible + # type "Union[dtype[Any], ExtensionDtype]"; expected "Union[dtype[Any], + # None, type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, + # Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]" + result = result.astype(new_dtype, copy=True) # type: ignore[arg-type] np.place(result, mask, np.nan) @@ -615,7 +634,9 @@ def _maybe_promote(dtype: np.dtype, fill_value=np.nan): kinds = ["i", "u", "f", "c", "m", "M"] if is_valid_na_for_dtype(fill_value, dtype) and dtype.kind in kinds: - dtype = ensure_dtype_can_hold_na(dtype) + # error: Incompatible types in assignment (expression has type + # "Union[dtype[Any], ExtensionDtype]", variable has type "dtype[Any]") + dtype = ensure_dtype_can_hold_na(dtype) # type: ignore[assignment] fv = na_value_for_dtype(dtype) return dtype, fv @@ -666,13 +687,15 @@ def _maybe_promote(dtype: np.dtype, fill_value=np.nan): if fv.tz is None: return dtype, fv.asm8 - return np.dtype(object), fill_value + # error: Value of type variable "_DTypeScalar" of "dtype" cannot be "object" + return np.dtype(object), fill_value # type: ignore[type-var] elif issubclass(dtype.type, np.timedelta64): inferred, fv = infer_dtype_from_scalar(fill_value, pandas_dtype=True) if inferred == dtype: return dtype, fv - return np.dtype(object), fill_value + # error: Value of type variable "_DTypeScalar" of "dtype" cannot be "object" + return np.dtype(object), fill_value # type: ignore[type-var] elif is_float(fill_value): if issubclass(dtype.type, np.bool_): @@ -916,7 +939,9 @@ def infer_dtype_from_array( (dtype('O'), [1, '1']) """ if isinstance(arr, np.ndarray): - return arr.dtype, arr + # error: Incompatible return value type (got "Tuple[dtype, ndarray]", expected + # "Tuple[Union[dtype, ExtensionDtype], ExtensionArray]") + return arr.dtype, arr # type: ignore[return-value] if not is_list_like(arr): raise TypeError("'arr' must be list-like") @@ -925,7 +950,9 @@ def infer_dtype_from_array( return arr.dtype, arr elif isinstance(arr, ABCSeries): - return arr.dtype, np.asarray(arr) + # error: Incompatible return value type (got "Tuple[Any, ndarray]", expected + # "Tuple[Union[dtype, ExtensionDtype], ExtensionArray]") + return arr.dtype, np.asarray(arr) # type: ignore[return-value] # don't force numpy coerce with nan's inferred = lib.infer_dtype(arr, skipna=False) @@ -1005,7 +1032,14 @@ def invalidate_string_dtypes(dtype_set: Set[DtypeObj]): Change string like dtypes to object for ``DataFrame.select_dtypes()``. """ - non_string_dtypes = dtype_set - {np.dtype("S").type, np.dtype("<U").type} + # error: Argument 1 to <set> has incompatible type "Type[generic]"; expected + # "Union[dtype[Any], ExtensionDtype, None]" + # error: Argument 2 to <set> has incompatible type "Type[generic]"; expected + # "Union[dtype[Any], ExtensionDtype, None]" + non_string_dtypes = dtype_set - { + np.dtype("S").type, # type: ignore[arg-type] + np.dtype("<U").type, # type: ignore[arg-type] + } if non_string_dtypes != dtype_set: raise TypeError("string dtypes are not allowed, use 'object' instead") @@ -1033,12 +1067,18 @@ def astype_dt64_to_dt64tz( from pandas.core.construction import ensure_wrapped_if_datetimelike values = ensure_wrapped_if_datetimelike(values) - values = cast("DatetimeArray", values) + # error: Incompatible types in assignment (expression has type "DatetimeArray", + # variable has type "ndarray") + values = cast("DatetimeArray", values) # type: ignore[assignment] aware = isinstance(dtype, DatetimeTZDtype) if via_utc: # Series.astype behavior - assert values.tz is None and aware # caller is responsible for checking this + + # caller is responsible for checking this + + # error: "ndarray" has no attribute "tz" + assert values.tz is None and aware # type: ignore[attr-defined] dtype = cast(DatetimeTZDtype, dtype) if copy: @@ -1056,12 +1096,17 @@ def astype_dt64_to_dt64tz( # FIXME: GH#33401 this doesn't match DatetimeArray.astype, which # goes through the `not via_utc` path - return values.tz_localize("UTC").tz_convert(dtype.tz) + + # error: "ndarray" has no attribute "tz_localize" + return values.tz_localize("UTC").tz_convert( # type: ignore[attr-defined] + dtype.tz + ) else: # DatetimeArray/DatetimeIndex.astype behavior - if values.tz is None and aware: + # error: "ndarray" has no attribute "tz" + if values.tz is None and aware: # type: ignore[attr-defined] dtype = cast(DatetimeTZDtype, dtype) level = find_stack_level() warnings.warn( @@ -1072,17 +1117,20 @@ def astype_dt64_to_dt64tz( stacklevel=level, ) - return values.tz_localize(dtype.tz) + # error: "ndarray" has no attribute "tz_localize" + return values.tz_localize(dtype.tz) # type: ignore[attr-defined] elif aware: # GH#18951: datetime64_tz dtype but not equal means different tz dtype = cast(DatetimeTZDtype, dtype) - result = values.tz_convert(dtype.tz) + # error: "ndarray" has no attribute "tz_convert" + result = values.tz_convert(dtype.tz) # type: ignore[attr-defined] if copy: result = result.copy() return result - elif values.tz is not None: + # error: "ndarray" has no attribute "tz" + elif values.tz is not None: # type: ignore[attr-defined] level = find_stack_level() warnings.warn( "Using .astype to convert from timezone-aware dtype to " @@ -1093,7 +1141,10 @@ def astype_dt64_to_dt64tz( stacklevel=level, ) - result = values.tz_convert("UTC").tz_localize(None) + # error: "ndarray" has no attribute "tz_convert" + result = values.tz_convert("UTC").tz_localize( # type: ignore[attr-defined] + None + ) if copy: result = result.copy() return result @@ -1161,7 +1212,8 @@ def astype_nansafe( flat = arr.ravel("K") result = astype_nansafe(flat, dtype, copy=copy, skipna=skipna) order = "F" if flags.f_contiguous else "C" - return result.reshape(arr.shape, order=order) + # error: "ExtensionArray" has no attribute "reshape"; maybe "shape"? + return result.reshape(arr.shape, order=order) # type: ignore[attr-defined] # We get here with 0-dim from sparse arr = np.atleast_1d(arr) @@ -1179,7 +1231,9 @@ def astype_nansafe( from pandas.core.construction import ensure_wrapped_if_datetimelike arr = ensure_wrapped_if_datetimelike(arr) - return arr.astype(dtype, copy=copy) + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return arr.astype(dtype, copy=copy) # type: ignore[return-value] if issubclass(dtype.type, str): return lib.ensure_string_array(arr, skipna=skipna, convert_na_value=False) @@ -1196,11 +1250,15 @@ def astype_nansafe( ) if isna(arr).any(): raise ValueError("Cannot convert NaT values to integer") - return arr.view(dtype) + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return arr.view(dtype) # type: ignore[return-value] # allow frequency conversions if dtype.kind == "M": - return arr.astype(dtype) + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return arr.astype(dtype) # type: ignore[return-value] raise TypeError(f"cannot astype a datetimelike from [{arr.dtype}] to [{dtype}]") @@ -1216,10 +1274,16 @@ def astype_nansafe( ) if isna(arr).any(): raise ValueError("Cannot convert NaT values to integer") - return arr.view(dtype) + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return arr.view(dtype) # type: ignore[return-value] elif dtype.kind == "m": - return astype_td64_unit_conversion(arr, dtype, copy=copy) + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return astype_td64_unit_conversion( # type: ignore[return-value] + arr, dtype, copy=copy + ) raise TypeError(f"cannot astype a timedelta from [{arr.dtype}] to [{dtype}]") @@ -1240,11 +1304,23 @@ def astype_nansafe( elif is_datetime64_dtype(dtype): from pandas import to_datetime - return astype_nansafe(to_datetime(arr).values, dtype, copy=copy) + # error: Incompatible return value type (got "ExtensionArray", expected + # "ndarray") + return astype_nansafe( # type: ignore[return-value] + # error: No overload variant of "to_datetime" matches argument type + # "ndarray" + to_datetime(arr).values, # type: ignore[call-overload] + dtype, + copy=copy, + ) elif is_timedelta64_dtype(dtype): from pandas import to_timedelta - return astype_nansafe(to_timedelta(arr)._values, dtype, copy=copy) + # error: Incompatible return value type (got "ExtensionArray", expected + # "ndarray") + return astype_nansafe( # type: ignore[return-value] + to_timedelta(arr)._values, dtype, copy=copy + ) if dtype.name in ("datetime64", "timedelta64"): msg = ( @@ -1255,9 +1331,13 @@ def astype_nansafe( if copy or is_object_dtype(arr.dtype) or is_object_dtype(dtype): # Explicit copy, or required since NumPy can't view from / to object. - return arr.astype(dtype, copy=True) - return arr.astype(dtype, copy=copy) + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return arr.astype(dtype, copy=True) # type: ignore[return-value] + + # error: Incompatible return value type (got "ndarray", expected "ExtensionArray") + return arr.astype(dtype, copy=copy) # type: ignore[return-value] def astype_array(values: ArrayLike, dtype: DtypeObj, copy: bool = False) -> ArrayLike: @@ -1286,7 +1366,11 @@ def astype_array(values: ArrayLike, dtype: DtypeObj, copy: bool = False) -> Arra raise TypeError(msg) if is_datetime64tz_dtype(dtype) and is_datetime64_dtype(values.dtype): - return astype_dt64_to_dt64tz(values, dtype, copy, via_utc=True) + # error: Incompatible return value type (got "DatetimeArray", expected + # "ndarray") + return astype_dt64_to_dt64tz( # type: ignore[return-value] + values, dtype, copy, via_utc=True + ) if is_dtype_equal(values.dtype, dtype): if copy: @@ -1297,11 +1381,19 @@ def astype_array(values: ArrayLike, dtype: DtypeObj, copy: bool = False) -> Arra values = values.astype(dtype, copy=copy) else: - values = astype_nansafe(values, dtype, copy=copy) + # error: Incompatible types in assignment (expression has type "ExtensionArray", + # variable has type "ndarray") + # error: Argument 1 to "astype_nansafe" has incompatible type "ExtensionArray"; + # expected "ndarray" + values = astype_nansafe( # type: ignore[assignment] + values, dtype, copy=copy # type: ignore[arg-type] + ) # in pandas we don't store numpy str dtypes, so convert to object if isinstance(dtype, np.dtype) and issubclass(values.dtype.type, str): - values = np.array(values, dtype=object) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + values = np.array(values, dtype=object) # type: ignore[assignment] return values @@ -1402,7 +1494,9 @@ def soft_convert_objects( values, convert_datetime=datetime, convert_timedelta=timedelta ) except (OutOfBoundsDatetime, ValueError): - return values + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return values # type: ignore[return-value] if numeric and is_object_dtype(values.dtype): converted = lib.maybe_convert_numeric(values, set(), coerce_numeric=True) @@ -1411,7 +1505,8 @@ def soft_convert_objects( values = converted if not isna(converted).all() else values values = values.copy() if copy else values - return values + # error: Incompatible return value type (got "ndarray", expected "ExtensionArray") + return values # type: ignore[return-value] def convert_dtypes( @@ -1562,12 +1657,20 @@ def try_datetime(v: np.ndarray) -> ArrayLike: dta = sequence_to_datetimes(v, require_iso8601=True, allow_object=True) except (ValueError, TypeError): # e.g. <class 'numpy.timedelta64'> is not convertible to datetime - return v.reshape(shape) + + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return v.reshape(shape) # type: ignore[return-value] else: # GH#19761 we may have mixed timezones, in which cast 'dta' is # an ndarray[object]. Only 1 test # relies on this behavior, see GH#40111 - return dta.reshape(shape) + + # error: Incompatible return value type (got "Union[ndarray, + # DatetimeArray]", expected "ExtensionArray") + # error: Incompatible return value type (got "Union[ndarray, + # DatetimeArray]", expected "ndarray") + return dta.reshape(shape) # type: ignore[return-value] def try_timedelta(v: np.ndarray) -> np.ndarray: # safe coerce to timedelta64 @@ -1586,14 +1689,18 @@ def try_timedelta(v: np.ndarray) -> np.ndarray: inferred_type = lib.infer_datetimelike_array(ensure_object(v)) if inferred_type == "datetime": - value = try_datetime(v) + # error: Incompatible types in assignment (expression has type "ExtensionArray", + # variable has type "Union[ndarray, List[Any]]") + value = try_datetime(v) # type: ignore[assignment] elif inferred_type == "timedelta": value = try_timedelta(v) elif inferred_type == "nat": # if all NaT, return as datetime if isna(v).all(): - value = try_datetime(v) + # error: Incompatible types in assignment (expression has type + # "ExtensionArray", variable has type "Union[ndarray, List[Any]]") + value = try_datetime(v) # type: ignore[assignment] else: # We have at least a NaT and a string @@ -1603,7 +1710,10 @@ def try_timedelta(v: np.ndarray) -> np.ndarray: if lib.infer_dtype(value, skipna=False) in ["mixed"]: # cannot skip missing values, as NaT implies that the string # is actually a datetime - value = try_datetime(v) + + # error: Incompatible types in assignment (expression has type + # "ExtensionArray", variable has type "Union[ndarray, List[Any]]") + value = try_datetime(v) # type: ignore[assignment] return value @@ -1643,10 +1753,16 @@ def maybe_cast_to_datetime( dta = sequence_to_datetimes(value, allow_object=False) # GH 25843: Remove tz information since the dtype # didn't specify one - if dta.tz is not None: + + # error: Item "ndarray" of "Union[ndarray, DatetimeArray]" + # has no attribute "tz" + if dta.tz is not None: # type: ignore[union-attr] # equiv: dta.view(dtype) # Note: NOT equivalent to dta.astype(dtype) - dta = dta.tz_localize(None) + + # error: Item "ndarray" of "Union[ndarray, + # DatetimeArray]" has no attribute "tz_localize" + dta = dta.tz_localize(None) # type: ignore[union-attr] value = dta elif is_datetime64tz: dtype = cast(DatetimeTZDtype, dtype) @@ -1656,17 +1772,38 @@ def maybe_cast_to_datetime( # be localized to the timezone. is_dt_string = is_string_dtype(value.dtype) dta = sequence_to_datetimes(value, allow_object=False) - if dta.tz is not None: - value = dta.astype(dtype, copy=False) + # error: Item "ndarray" of "Union[ndarray, DatetimeArray]" + # has no attribute "tz" + if dta.tz is not None: # type: ignore[union-attr] + # error: Argument 1 to "astype" of + # "_ArrayOrScalarCommon" has incompatible type + # "Union[dtype[Any], ExtensionDtype, None]"; expected + # "Union[dtype[Any], None, type, _SupportsDType, str, + # Union[Tuple[Any, int], Tuple[Any, Union[int, + # Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, + # Any]]]" + value = dta.astype( + dtype, copy=False # type: ignore[arg-type] + ) elif is_dt_string: # Strings here are naive, so directly localize # equiv: dta.astype(dtype) # though deprecated - value = dta.tz_localize(dtype.tz) + + # error: Item "ndarray" of "Union[ndarray, + # DatetimeArray]" has no attribute "tz_localize" + value = dta.tz_localize( # type: ignore[union-attr] + dtype.tz + ) else: # Numeric values are UTC at this point, # so localize and convert # equiv: Series(dta).astype(dtype) # though deprecated - value = dta.tz_localize("UTC").tz_convert(dtype.tz) + + # error: Item "ndarray" of "Union[ndarray, + # DatetimeArray]" has no attribute "tz_localize" + value = dta.tz_localize( # type: ignore[union-attr] + "UTC" + ).tz_convert(dtype.tz) elif is_timedelta64: # if successful, we get a ndarray[td64ns] value, _ = sequence_to_td64ns(value) @@ -1703,7 +1840,10 @@ def maybe_cast_to_datetime( # only do this if we have an array and the dtype of the array is not # setup already we are not an integer/object, so don't bother with this # conversion - value = maybe_infer_to_datetimelike(value) + + # error: Argument 1 to "maybe_infer_to_datetimelike" has incompatible type + # "Union[ExtensionArray, List[Any]]"; expected "Union[ndarray, List[Any]]" + value = maybe_infer_to_datetimelike(value) # type: ignore[arg-type] return value @@ -1820,7 +1960,11 @@ def find_common_type(types: List[DtypeObj]) -> DtypeObj: if is_integer_dtype(t) or is_float_dtype(t) or is_complex_dtype(t): return np.dtype("object") - return np.find_common_type(types, []) + # error: Argument 1 to "find_common_type" has incompatible type + # "List[Union[dtype, ExtensionDtype]]"; expected "Sequence[Union[dtype, + # None, type, _SupportsDtype, str, Tuple[Any, int], Tuple[Any, Union[int, + # Sequence[int]]], List[Any], _DtypeDict, Tuple[Any, Any]]]" + return np.find_common_type(types, []) # type: ignore[arg-type] def construct_2d_arraylike_from_scalar( @@ -1878,7 +2022,9 @@ def construct_1d_arraylike_from_scalar( dtype = np.dtype(object) if is_extension_array_dtype(dtype): - cls = dtype.construct_array_type() + # error: Item "dtype" of "Union[dtype, ExtensionDtype]" has no + # attribute "construct_array_type" + cls = dtype.construct_array_type() # type: ignore[union-attr] subarr = cls._from_sequence([value] * length, dtype=dtype) else: @@ -1895,7 +2041,11 @@ def construct_1d_arraylike_from_scalar( elif dtype.kind in ["M", "m"]: value = maybe_unbox_datetimelike(value, dtype) - subarr = np.empty(length, dtype=dtype) + # error: Argument "dtype" to "empty" has incompatible type + # "Union[dtype, ExtensionDtype]"; expected "Union[dtype, None, type, + # _SupportsDtype, str, Tuple[Any, int], Tuple[Any, Union[int, + # Sequence[int]]], List[Any], _DtypeDict, Tuple[Any, Any]]" + subarr = np.empty(length, dtype=dtype) # type: ignore[arg-type] subarr.fill(value) return subarr @@ -1967,7 +2117,11 @@ def construct_1d_ndarray_preserving_na( # TODO(numpy#12550): special-case can be removed subarr = construct_1d_object_array_from_listlike(list(values)) else: - subarr = np.array(values, dtype=dtype, copy=copy) + # error: Argument "dtype" to "array" has incompatible type + # "Union[dtype[Any], ExtensionDtype, None]"; expected "Union[dtype[Any], + # None, type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, + # Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]" + subarr = np.array(values, dtype=dtype, copy=copy) # type: ignore[arg-type] return subarr diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 0966d0b93cc25..68c8d35810b7e 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -165,7 +165,10 @@ def ensure_int_or_float(arr: ArrayLike, copy: bool = False) -> np.ndarray: return arr.astype("uint64", copy=copy, casting="safe") # type: ignore[call-arg] except TypeError: if is_extension_array_dtype(arr.dtype): - return arr.to_numpy(dtype="float64", na_value=np.nan) + # error: "ndarray" has no attribute "to_numpy" + return arr.to_numpy( # type: ignore[attr-defined] + dtype="float64", na_value=np.nan + ) return arr.astype("float64", copy=copy) @@ -1718,7 +1721,10 @@ def infer_dtype_from_object(dtype) -> DtypeObj: """ if isinstance(dtype, type) and issubclass(dtype, np.generic): # Type object from a dtype - return dtype + + # error: Incompatible return value type (got "Type[generic]", expected + # "Union[dtype[Any], ExtensionDtype]") + return dtype # type: ignore[return-value] elif isinstance(dtype, (np.dtype, ExtensionDtype)): # dtype object try: @@ -1726,7 +1732,9 @@ def infer_dtype_from_object(dtype) -> DtypeObj: except TypeError: # Should still pass if we don't have a date-like pass - return dtype.type + # error: Incompatible return value type (got "Union[Type[generic], Type[Any]]", + # expected "Union[dtype[Any], ExtensionDtype]") + return dtype.type # type: ignore[return-value] try: dtype = pandas_dtype(dtype) @@ -1740,7 +1748,9 @@ def infer_dtype_from_object(dtype) -> DtypeObj: # TODO(jreback) # should deprecate these if dtype in ["datetimetz", "datetime64tz"]: - return DatetimeTZDtype.type + # error: Incompatible return value type (got "Type[Any]", expected + # "Union[dtype[Any], ExtensionDtype]") + return DatetimeTZDtype.type # type: ignore[return-value] elif dtype in ["period"]: raise NotImplementedError @@ -1837,7 +1847,9 @@ def pandas_dtype(dtype) -> DtypeObj: # registered extension types result = registry.find(dtype) if result is not None: - return result + # error: Incompatible return value type (got "Type[ExtensionDtype]", + # expected "Union[dtype, ExtensionDtype]") + return result # type: ignore[return-value] # try a numpy dtype # raise a consistent TypeError if failed diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 1545b5b106803..06fc1918b5ecf 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -51,8 +51,12 @@ def _cast_to_common_type(arr: ArrayLike, dtype: DtypeObj) -> ArrayLike: # problem case: SparseArray.astype(dtype) doesn't follow the specified # dtype exactly, but converts this to Sparse[dtype] -> first manually # convert to dense array - arr = cast(SparseArray, arr) - return arr.to_dense().astype(dtype, copy=False) + + # error: Incompatible types in assignment (expression has type + # "SparseArray", variable has type "ndarray") + arr = cast(SparseArray, arr) # type: ignore[assignment] + # error: "ndarray" has no attribute "to_dense" + return arr.to_dense().astype(dtype, copy=False) # type: ignore[attr-defined] if ( isinstance(arr, np.ndarray) @@ -67,7 +71,11 @@ def _cast_to_common_type(arr: ArrayLike, dtype: DtypeObj) -> ArrayLike: if is_extension_array_dtype(dtype) and isinstance(arr, np.ndarray): # numpy's astype cannot handle ExtensionDtypes return pd_array(arr, dtype=dtype, copy=False) - return arr.astype(dtype, copy=False) + # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has incompatible type + # "Union[dtype[Any], ExtensionDtype]"; expected "Union[dtype[Any], None, type, + # _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int, Sequence[int]]], + # List[Any], _DTypeDict, Tuple[Any, Any]]]" + return arr.astype(dtype, copy=False) # type: ignore[arg-type] def concat_compat(to_concat, axis: int = 0, ea_compat_axis: bool = False): diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index da3a9269cf2c4..d44d2a564fb78 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -180,7 +180,9 @@ class CategoricalDtype(PandasExtensionDtype, ExtensionDtype): type: Type[CategoricalDtypeType] = CategoricalDtypeType kind: str_type = "O" str = "|O08" - base = np.dtype("O") + # error: Incompatible types in assignment (expression has type "dtype", + # base class "PandasExtensionDtype" defined the type as "None") + base = np.dtype("O") # type: ignore[assignment] _metadata = ("categories", "ordered") _cache: Dict[str_type, PandasExtensionDtype] = {} @@ -467,8 +469,14 @@ def _hash_categories(categories, ordered: Ordered = True) -> int: [cat_array, np.arange(len(cat_array), dtype=cat_array.dtype)] ) else: - cat_array = [cat_array] - hashed = combine_hash_arrays(iter(cat_array), num_items=len(cat_array)) + # error: Incompatible types in assignment (expression has type + # "List[ndarray]", variable has type "ndarray") + cat_array = [cat_array] # type: ignore[assignment] + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "int") + hashed = combine_hash_arrays( # type: ignore[assignment] + iter(cat_array), num_items=len(cat_array) + ) return np.bitwise_xor.reduce(hashed) @classmethod @@ -668,7 +676,9 @@ class DatetimeTZDtype(PandasExtensionDtype): kind: str_type = "M" str = "|M8[ns]" num = 101 - base = np.dtype("M8[ns]") + # error: Incompatible types in assignment (expression has type "dtype", + # base class "PandasExtensionDtype" defined the type as "None") + base = np.dtype("M8[ns]") # type: ignore[assignment] na_value = NaT _metadata = ("unit", "tz") _match = re.compile(r"(datetime64|M8)\[(?P<unit>.+), (?P<tz>.+)\]") @@ -834,7 +844,9 @@ class PeriodDtype(dtypes.PeriodDtypeBase, PandasExtensionDtype): type: Type[Period] = Period kind: str_type = "O" str = "|O08" - base = np.dtype("O") + # error: Incompatible types in assignment (expression has type "dtype", + # base class "PandasExtensionDtype" defined the type as "None") + base = np.dtype("O") # type: ignore[assignment] num = 102 _metadata = ("freq",) _match = re.compile(r"(P|p)eriod\[(?P<freq>.+)\]") @@ -1034,7 +1046,9 @@ class IntervalDtype(PandasExtensionDtype): name = "interval" kind: str_type = "O" str = "|O08" - base = np.dtype("O") + # error: Incompatible types in assignment (expression has type "dtype", + # base class "PandasExtensionDtype" defined the type as "None") + base = np.dtype("O") # type: ignore[assignment] num = 103 _metadata = ( "subtype", diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index b4a77337ce9f2..286272b165fb9 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -164,9 +164,13 @@ def _isna(obj, inf_as_na: bool = False): elif isinstance(obj, type): return False elif isinstance(obj, (np.ndarray, ABCExtensionArray)): - return _isna_array(obj, inf_as_na=inf_as_na) + # error: Value of type variable "ArrayLike" of "_isna_array" cannot be + # "Union[ndarray, ExtensionArray]" + return _isna_array(obj, inf_as_na=inf_as_na) # type: ignore[type-var] elif isinstance(obj, (ABCSeries, ABCIndex)): - result = _isna_array(obj._values, inf_as_na=inf_as_na) + # error: Value of type variable "ArrayLike" of "_isna_array" cannot be + # "Union[Any, ExtensionArray, ndarray]" + result = _isna_array(obj._values, inf_as_na=inf_as_na) # type: ignore[type-var] # box if isinstance(obj, ABCSeries): result = obj._constructor( @@ -234,19 +238,37 @@ def _isna_array(values: ArrayLike, inf_as_na: bool = False): if is_extension_array_dtype(dtype): if inf_as_na and is_categorical_dtype(dtype): - result = libmissing.isnaobj_old(values.to_numpy()) + # error: "ndarray" has no attribute "to_numpy" + result = libmissing.isnaobj_old( + values.to_numpy() # type: ignore[attr-defined] + ) else: - result = values.isna() + # error: "ndarray" has no attribute "isna" + result = values.isna() # type: ignore[attr-defined] elif is_string_dtype(dtype): - result = _isna_string_dtype(values, dtype, inf_as_na=inf_as_na) + # error: Argument 1 to "_isna_string_dtype" has incompatible type + # "ExtensionArray"; expected "ndarray" + # error: Argument 2 to "_isna_string_dtype" has incompatible type + # "ExtensionDtype"; expected "dtype[Any]" + result = _isna_string_dtype( + values, dtype, inf_as_na=inf_as_na # type: ignore[arg-type] + ) elif needs_i8_conversion(dtype): # this is the NaT pattern result = values.view("i8") == iNaT else: if inf_as_na: - result = ~np.isfinite(values) + # error: Argument 1 to "__call__" of "ufunc" has incompatible type + # "ExtensionArray"; expected "Union[Union[int, float, complex, str, bytes, + # generic], Sequence[Union[int, float, complex, str, bytes, generic]], + # Sequence[Sequence[Any]], _SupportsArray]" + result = ~np.isfinite(values) # type: ignore[arg-type] else: - result = np.isnan(values) + # error: Argument 1 to "__call__" of "ufunc" has incompatible type + # "ExtensionArray"; expected "Union[Union[int, float, complex, str, bytes, + # generic], Sequence[Union[int, float, complex, str, bytes, generic]], + # Sequence[Sequence[Any]], _SupportsArray]" + result = np.isnan(values) # type: ignore[arg-type] return result @@ -573,7 +595,9 @@ def na_value_for_dtype(dtype: DtypeObj, compat: bool = True): """ if is_extension_array_dtype(dtype): - return dtype.na_value + # error: Item "dtype[Any]" of "Union[dtype[Any], ExtensionDtype]" has no + # attribute "na_value" + return dtype.na_value # type: ignore[union-attr] elif needs_i8_conversion(dtype): return dtype.type("NaT", "ns") elif is_float_dtype(dtype): @@ -626,7 +650,8 @@ def is_valid_na_for_dtype(obj, dtype: DtypeObj) -> bool: # Numeric return obj is not NaT and not isinstance(obj, (np.datetime64, np.timedelta64)) - elif dtype == np.dtype(object): + # error: Value of type variable "_DTypeScalar" of "dtype" cannot be "object" + elif dtype == np.dtype(object): # type: ignore[type-var] # This is needed for Categorical, but is kind of weird return True @@ -650,11 +675,22 @@ def isna_all(arr: ArrayLike) -> bool: checker = nan_checker elif dtype.kind in ["m", "M"] or dtype.type is Period: - checker = lambda x: np.asarray(x.view("i8")) == iNaT + # error: Incompatible types in assignment (expression has type + # "Callable[[Any], Any]", variable has type "ufunc") + checker = lambda x: np.asarray(x.view("i8")) == iNaT # type: ignore[assignment] else: - checker = lambda x: _isna_array(x, inf_as_na=INF_AS_NA) + # error: Incompatible types in assignment (expression has type "Callable[[Any], + # Any]", variable has type "ufunc") + checker = lambda x: _isna_array( # type: ignore[assignment] + x, inf_as_na=INF_AS_NA + ) return all( - checker(arr[i : i + chunk_len]).all() for i in range(0, total_len, chunk_len) + # error: Argument 1 to "__call__" of "ufunc" has incompatible type + # "Union[ExtensionArray, Any]"; expected "Union[Union[int, float, complex, str, + # bytes, generic], Sequence[Union[int, float, complex, str, bytes, generic]], + # Sequence[Sequence[Any]], _SupportsArray]" + checker(arr[i : i + chunk_len]).all() # type: ignore[arg-type] + for i in range(0, total_len, chunk_len) ) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index a0c97b0cdd268..de28c04ca0793 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -584,33 +584,84 @@ def __init__( ) elif isinstance(data, dict): - mgr = dict_to_mgr(data, index, columns, dtype=dtype, typ=manager) + # error: Argument "dtype" to "dict_to_mgr" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected + # "Union[dtype[Any], ExtensionDtype, None]" + mgr = dict_to_mgr( + data, index, columns, dtype=dtype, typ=manager # type: ignore[arg-type] + ) elif isinstance(data, ma.MaskedArray): import numpy.ma.mrecords as mrecords # masked recarray if isinstance(data, mrecords.MaskedRecords): - mgr = rec_array_to_mgr(data, index, columns, dtype, copy, typ=manager) + # error: Argument 4 to "rec_array_to_mgr" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected + # "Union[dtype[Any], ExtensionDtype, None]" + mgr = rec_array_to_mgr( + data, + index, + columns, + dtype, # type: ignore[arg-type] + copy, + typ=manager, + ) # a masked array else: data = sanitize_masked_array(data) mgr = ndarray_to_mgr( - data, index, columns, dtype=dtype, copy=copy, typ=manager + # error: Argument "dtype" to "ndarray_to_mgr" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; + # expected "Union[dtype[Any], ExtensionDtype, None]" + data, + index, + columns, + dtype=dtype, # type: ignore[arg-type] + copy=copy, + typ=manager, ) elif isinstance(data, (np.ndarray, Series, Index)): if data.dtype.names: # i.e. numpy structured array - mgr = rec_array_to_mgr(data, index, columns, dtype, copy, typ=manager) + + # error: Argument 4 to "rec_array_to_mgr" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected + # "Union[dtype[Any], ExtensionDtype, None]" + mgr = rec_array_to_mgr( + data, + index, + columns, + dtype, # type: ignore[arg-type] + copy, + typ=manager, + ) elif getattr(data, "name", None) is not None: # i.e. Series/Index with non-None name mgr = dict_to_mgr( - {data.name: data}, index, columns, dtype=dtype, typ=manager + # error: Item "ndarray" of "Union[ndarray, Series, Index]" has no + # attribute "name" + # error: Argument "dtype" to "dict_to_mgr" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; + # expected "Union[dtype[Any], ExtensionDtype, None]" + {data.name: data}, # type: ignore[union-attr] + index, + columns, + dtype=dtype, # type: ignore[arg-type] + typ=manager, ) else: mgr = ndarray_to_mgr( - data, index, columns, dtype=dtype, copy=copy, typ=manager + # error: Argument "dtype" to "ndarray_to_mgr" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; + # expected "Union[dtype[Any], ExtensionDtype, None]" + data, + index, + columns, + dtype=dtype, # type: ignore[arg-type] + copy=copy, + typ=manager, ) # For data is list-like, or Iterable (will consume into list) @@ -622,19 +673,54 @@ def __init__( data = dataclasses_to_dicts(data) if treat_as_nested(data): if columns is not None: - columns = ensure_index(columns) + # error: Value of type variable "AnyArrayLike" of "ensure_index" + # cannot be "Collection[Any]" + columns = ensure_index(columns) # type: ignore[type-var] arrays, columns, index = nested_data_to_arrays( - data, columns, index, dtype + # error: Argument 3 to "nested_data_to_arrays" has incompatible + # type "Optional[Collection[Any]]"; expected "Optional[Index]" + # error: Argument 4 to "nested_data_to_arrays" has incompatible + # type "Union[ExtensionDtype, str, dtype[Any], Type[object], + # None]"; expected "Union[dtype[Any], ExtensionDtype, None]" + data, + columns, + index, # type: ignore[arg-type] + dtype, # type: ignore[arg-type] ) mgr = arrays_to_mgr( - arrays, columns, index, columns, dtype=dtype, typ=manager + # error: Argument "dtype" to "arrays_to_mgr" has incompatible + # type "Union[ExtensionDtype, str, dtype[Any], Type[object], + # None]"; expected "Union[dtype[Any], ExtensionDtype, None]" + arrays, + columns, + index, + columns, + dtype=dtype, # type: ignore[arg-type] + typ=manager, ) else: mgr = ndarray_to_mgr( - data, index, columns, dtype=dtype, copy=copy, typ=manager + # error: Argument "dtype" to "ndarray_to_mgr" has incompatible + # type "Union[ExtensionDtype, str, dtype[Any], Type[object], + # None]"; expected "Union[dtype[Any], ExtensionDtype, None]" + data, + index, + columns, + dtype=dtype, # type: ignore[arg-type] + copy=copy, + typ=manager, ) else: - mgr = dict_to_mgr({}, index, columns, dtype=dtype, typ=manager) + # error: Argument "dtype" to "dict_to_mgr" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected + # "Union[dtype[Any], ExtensionDtype, None]" + mgr = dict_to_mgr( + {}, + index, + columns, + dtype=dtype, # type: ignore[arg-type] + typ=manager, + ) # For data is scalar else: if index is None or columns is None: @@ -648,19 +734,39 @@ def __init__( # TODO(EA2D): special case not needed with 2D EAs values = [ - construct_1d_arraylike_from_scalar(data, len(index), dtype) + # error: Argument 3 to "construct_1d_arraylike_from_scalar" + # has incompatible type "Union[ExtensionDtype, str, dtype, + # Type[object]]"; expected "Union[dtype, ExtensionDtype]" + construct_1d_arraylike_from_scalar( + data, len(index), dtype # type: ignore[arg-type] + ) for _ in range(len(columns)) ] mgr = arrays_to_mgr( values, columns, index, columns, dtype=None, typ=manager ) else: - values = construct_2d_arraylike_from_scalar( - data, len(index), len(columns), dtype, copy + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "List[ExtensionArray]") + values = construct_2d_arraylike_from_scalar( # type: ignore[assignment] + # error: Argument 4 to "construct_2d_arraylike_from_scalar" has + # incompatible type "Union[ExtensionDtype, str, dtype[Any], + # Type[object]]"; expected "dtype[Any]" + data, + len(index), + len(columns), + dtype, # type: ignore[arg-type] + copy, ) mgr = ndarray_to_mgr( - values, index, columns, dtype=values.dtype, copy=False, typ=manager + # error: "List[ExtensionArray]" has no attribute "dtype" + values, + index, + columns, + dtype=values.dtype, # type: ignore[attr-defined] + copy=False, + typ=manager, ) # ensure correct Manager type according to settings @@ -1230,17 +1336,19 @@ def __len__(self) -> int: """ return len(self.index) - # error: Overloaded function signatures 1 and 2 overlap with incompatible return - # types @overload - def dot(self, other: Series) -> Series: # type: ignore[misc] + def dot(self, other: Series) -> Series: ... @overload def dot(self, other: Union[DataFrame, Index, ArrayLike]) -> DataFrame: ... - def dot(self, other: Union[AnyArrayLike, FrameOrSeriesUnion]) -> FrameOrSeriesUnion: + # error: Overloaded function implementation cannot satisfy signature 2 due to + # inconsistencies in how they use type variables + def dot( # type: ignore[misc] + self, other: Union[AnyArrayLike, FrameOrSeriesUnion] + ) -> FrameOrSeriesUnion: """ Compute the matrix multiplication between the DataFrame and other. @@ -2085,7 +2193,9 @@ def to_records( # array of tuples to numpy cols. copy copy copy ix_vals = list(map(np.array, zip(*self.index._values))) else: - ix_vals = [self.index.values] + # error: List item 0 has incompatible type "ArrayLike"; expected + # "ndarray" + ix_vals = [self.index.values] # type: ignore[list-item] arrays = ix_vals + [ np.asarray(self.iloc[:, i]) for i in range(len(self.columns)) @@ -2152,7 +2262,9 @@ def to_records( if dtype_mapping is None: formats.append(v.dtype) elif isinstance(dtype_mapping, (type, np.dtype, str)): - formats.append(dtype_mapping) + # error: Argument 1 to "append" of "list" has incompatible type + # "Union[type, dtype, str]"; expected "dtype" + formats.append(dtype_mapping) # type: ignore[arg-type] else: element = "row" if i < index_len else "column" msg = f"Invalid dtype {dtype_mapping} specified for {element} {name}" @@ -3217,7 +3329,9 @@ def transpose(self, *args, copy: bool = False) -> DataFrame: ) else: - new_values = self.values.T + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "List[Any]") + new_values = self.values.T # type: ignore[assignment] if copy: new_values = new_values.copy() result = self._constructor( @@ -3276,7 +3390,9 @@ def _get_column_array(self, i: int) -> ArrayLike: Get the values of the i'th column (ndarray or ExtensionArray, as stored in the Block) """ - return self._mgr.iget_values(i) + # error: Incompatible return value type (got "ExtensionArray", expected + # "ndarray") + return self._mgr.iget_values(i) # type: ignore[return-value] def _iter_column_arrays(self) -> Iterator[ArrayLike]: """ @@ -3284,7 +3400,9 @@ def _iter_column_arrays(self) -> Iterator[ArrayLike]: This returns the values as stored in the Block (ndarray or ExtensionArray). """ for i in range(len(self.columns)): - yield self._get_column_array(i) + # error: Incompatible types in "yield" (actual type + # "ExtensionArray", expected type "ndarray") + yield self._get_column_array(i) # type: ignore[misc] def __getitem__(self, key): key = lib.item_from_zerodim(key) @@ -3543,7 +3661,10 @@ def _set_item_frame_value(self, key, value: DataFrame) -> None: value = value.reindex(cols, axis=1) # now align rows - value = _reindex_for_setitem(value, self.index) + + # error: Incompatible types in assignment (expression has type "ExtensionArray", + # variable has type "DataFrame") + value = _reindex_for_setitem(value, self.index) # type: ignore[assignment] self._set_item_mgr(key, value) def _iset_item_mgr(self, loc: int, value) -> None: @@ -4052,9 +4173,16 @@ def check_int_infer_dtype(dtypes): # see https://github.com/numpy/numpy/issues/9464 if (isinstance(dtype, str) and dtype == "int") or (dtype is int): converted_dtypes.append(np.int32) - converted_dtypes.append(np.int64) + # error: Argument 1 to "append" of "list" has incompatible type + # "Type[signedinteger[Any]]"; expected "Type[signedinteger[Any]]" + converted_dtypes.append(np.int64) # type: ignore[arg-type] else: - converted_dtypes.append(infer_dtype_from_object(dtype)) + # error: Argument 1 to "append" of "list" has incompatible type + # "Union[dtype[Any], ExtensionDtype]"; expected + # "Type[signedinteger[Any]]" + converted_dtypes.append( + infer_dtype_from_object(dtype) # type: ignore[arg-type] + ) return frozenset(converted_dtypes) include = check_int_infer_dtype(include) @@ -4109,7 +4237,8 @@ def extract_unique_dtypes_from_dtypes_set( ) keep_these &= ~self.dtypes.isin(excluded_dtypes) - return self.iloc[:, keep_these.values] + # error: "ndarray" has no attribute "values" + return self.iloc[:, keep_these.values] # type: ignore[attr-defined] def insert(self, loc, column, value, allow_duplicates: bool = False) -> None: """ @@ -4418,7 +4547,11 @@ def _reindex_multi(self, axes, copy: bool, fill_value) -> DataFrame: if row_indexer is not None and col_indexer is not None: indexer = row_indexer, col_indexer - new_values = take_2d_multi(self.values, indexer, fill_value=fill_value) + # error: Argument 2 to "take_2d_multi" has incompatible type "Tuple[Any, + # Any]"; expected "ndarray" + new_values = take_2d_multi( + self.values, indexer, fill_value=fill_value # type: ignore[arg-type] + ) return self._constructor(new_values, index=new_index, columns=new_columns) else: return self._reindex_with_indexers( @@ -5106,10 +5239,14 @@ def set_index( arrays.append(col) # type:ignore[arg-type] names.append(col.name) elif isinstance(col, (list, np.ndarray)): - arrays.append(col) + # error: Argument 1 to "append" of "list" has incompatible type + # "Union[List[Any], ndarray]"; expected "Index" + arrays.append(col) # type: ignore[arg-type] names.append(None) elif isinstance(col, abc.Iterator): - arrays.append(list(col)) + # error: Argument 1 to "append" of "list" has incompatible type + # "List[Any]"; expected "Index" + arrays.append(list(col)) # type: ignore[arg-type] names.append(None) # from here, col can only be a column label else: @@ -5853,7 +5990,12 @@ def sort_values( # type: ignore[override] # need to rewrap columns in Series to apply key function if key is not None: - keys = [Series(k, name=name) for (k, name) in zip(keys, by)] + # error: List comprehension has incompatible type List[Series]; + # expected List[ndarray] + keys = [ + Series(k, name=name) # type: ignore[misc] + for (k, name) in zip(keys, by) + ] indexer = lexsort_indexer( keys, orders=ascending, na_position=na_position, key=key @@ -5866,7 +6008,9 @@ def sort_values( # type: ignore[override] # need to rewrap column in Series to apply key function if key is not None: - k = Series(k, name=by) + # error: Incompatible types in assignment (expression has type + # "Series", variable has type "ndarray") + k = Series(k, name=by) # type: ignore[assignment] if isinstance(ascending, (tuple, list)): ascending = ascending[0] @@ -10024,7 +10168,9 @@ def _reindex_for_setitem(value: FrameOrSeriesUnion, index: Index) -> ArrayLike: # reindex if necessary if value.index.equals(index) or not len(index): - return value._values.copy() + # error: Incompatible return value type (got "Union[ndarray, Any]", expected + # "ExtensionArray") + return value._values.copy() # type: ignore[return-value] # GH#4107 try: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index cd5c0159e93cb..d2b63c42d777b 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -666,7 +666,8 @@ def size(self) -> int: >>> df.size 4 """ - return np.prod(self.shape) + # error: Incompatible return value type (got "number", expected "int") + return np.prod(self.shape) # type: ignore[return-value] @final @property @@ -752,11 +753,13 @@ def swapaxes(self: FrameOrSeries, axis1, axis2, copy=True) -> FrameOrSeries: # ignore needed because of NDFrame constructor is different than # DataFrame/Series constructors. return self._constructor( + # error: Argument 1 to "NDFrame" has incompatible type "ndarray"; expected + # "Union[ArrayManager, BlockManager]" # error: Argument 2 to "NDFrame" has incompatible type "*Generator[Index, # None, None]"; expected "bool" [arg-type] # error: Argument 2 to "NDFrame" has incompatible type "*Generator[Index, # None, None]"; expected "Optional[Mapping[Optional[Hashable], Any]]" - new_values, + new_values, # type: ignore[arg-type] *new_axes, # type: ignore[arg-type] ).__finalize__(self, method="swapaxes") @@ -1985,14 +1988,20 @@ def __array_wrap__( # ptp also requires the item_from_zerodim return result d = self._construct_axes_dict(self._AXIS_ORDERS, copy=False) - return self._constructor(result, **d).__finalize__( + # error: Argument 1 to "NDFrame" has incompatible type "ndarray"; + # expected "BlockManager" + return self._constructor(result, **d).__finalize__( # type: ignore[arg-type] self, method="__array_wrap__" ) def __array_ufunc__( self, ufunc: Callable, method: str, *inputs: Any, **kwargs: Any ): - return arraylike.array_ufunc(self, ufunc, method, *inputs, **kwargs) + # error: Argument 2 to "array_ufunc" has incompatible type "Callable[..., Any]"; + # expected "ufunc" + return arraylike.array_ufunc( + self, ufunc, method, *inputs, **kwargs # type: ignore[arg-type] + ) # ideally we would define this to avoid the getattr checks, but # is slower @@ -6989,7 +6998,10 @@ def interpolate( f"`limit_direction` must be 'backward' for method `{method}`" ) - if obj.ndim == 2 and np.all(obj.dtypes == np.dtype(object)): + # error: Value of type variable "_DTypeScalar" of "dtype" cannot be "object" + if obj.ndim == 2 and np.all( + obj.dtypes == np.dtype(object) # type: ignore[type-var] + ): raise TypeError( "Cannot interpolate with all object-dtype columns " "in the DataFrame. Try setting at least one " @@ -8367,7 +8379,8 @@ def last(self: FrameOrSeries, offset) -> FrameOrSeries: start_date = self.index[-1] - offset start = self.index.searchsorted(start_date, side="right") - return self.iloc[start:] + # error: Slice index must be an integer or None + return self.iloc[start:] # type: ignore[misc] @final def rank( @@ -8475,8 +8488,15 @@ def ranker(data): na_option=na_option, pct=pct, ) - ranks = self._constructor(ranks, **data._construct_axes_dict()) - return ranks.__finalize__(self, method="rank") + # error: Incompatible types in assignment (expression has type + # "FrameOrSeries", variable has type "ndarray") + # error: Argument 1 to "NDFrame" has incompatible type "ndarray"; expected + # "Union[ArrayManager, BlockManager]" + ranks = self._constructor( # type: ignore[assignment] + ranks, **data._construct_axes_dict() # type: ignore[arg-type] + ) + # error: "ndarray" has no attribute "__finalize__" + return ranks.__finalize__(self, method="rank") # type: ignore[attr-defined] # if numeric_only is None, and we can't get anything, we try with # numeric_only=True @@ -8958,7 +8978,11 @@ def _where( # we are the same shape, so create an actual object for alignment else: - other = self._constructor(other, **self._construct_axes_dict()) + # error: Argument 1 to "NDFrame" has incompatible type "ndarray"; + # expected "BlockManager" + other = self._constructor( + other, **self._construct_axes_dict() # type: ignore[arg-type] + ) if axis is None: axis = 0 @@ -9885,7 +9909,11 @@ def abs(self: FrameOrSeries) -> FrameOrSeries: 2 6 30 -30 3 7 40 -50 """ - return np.abs(self) + # error: Argument 1 to "__call__" of "ufunc" has incompatible type + # "FrameOrSeries"; expected "Union[Union[int, float, complex, str, bytes, + # generic], Sequence[Union[int, float, complex, str, bytes, generic]], + # Sequence[Sequence[Any]], _SupportsArray]" + return np.abs(self) # type: ignore[arg-type] @final def describe( diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index af5c92ce82a66..50d04135c9300 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -344,7 +344,13 @@ def _aggregate_multiple_funcs(self, arg): # let higher level handle return results - output = self._wrap_aggregated_output(results, index=None) + # Argument 1 to "_wrap_aggregated_output" of "SeriesGroupBy" has + # incompatible type "Dict[OutputKey, Union[DataFrame, + # Series]]"; + # expected "Mapping[OutputKey, Union[Series, ndarray]]" + output = self._wrap_aggregated_output( + results, index=None # type: ignore[arg-type] + ) return self.obj._constructor_expanddim(output, columns=columns) # TODO: index should not be Optional - see GH 35490 @@ -759,13 +765,28 @@ def apply_series_value_counts(): # lab is a Categorical with categories an IntervalIndex lab = cut(Series(val), bins, include_lowest=True) - lev = lab.cat.categories - lab = lev.take(lab.cat.codes, allow_fill=True, fill_value=lev._na_value) + # error: "ndarray" has no attribute "cat" + lev = lab.cat.categories # type: ignore[attr-defined] + # error: No overload variant of "take" of "_ArrayOrScalarCommon" matches + # argument types "Any", "bool", "Union[Any, float]" + lab = lev.take( # type: ignore[call-overload] + # error: "ndarray" has no attribute "cat" + lab.cat.codes, # type: ignore[attr-defined] + allow_fill=True, + # error: Item "ndarray" of "Union[ndarray, Index]" has no attribute + # "_na_value" + fill_value=lev._na_value, # type: ignore[union-attr] + ) llab = lambda lab, inc: lab[inc]._multiindex.codes[-1] if is_interval_dtype(lab.dtype): # TODO: should we do this inside II? - sorter = np.lexsort((lab.left, lab.right, ids)) + + # error: "ndarray" has no attribute "left" + # error: "ndarray" has no attribute "right" + sorter = np.lexsort( + (lab.left, lab.right, ids) # type: ignore[attr-defined] + ) else: sorter = np.lexsort((lab, ids)) @@ -791,7 +812,11 @@ def apply_series_value_counts(): # multi-index components codes = self.grouper.reconstructed_codes codes = [rep(level_codes) for level_codes in codes] + [llab(lab, inc)] - levels = [ping.group_index for ping in self.grouper.groupings] + [lev] + # error: List item 0 has incompatible type "Union[ndarray, Any]"; + # expected "Index" + levels = [ping.group_index for ping in self.grouper.groupings] + [ + lev # type: ignore[list-item] + ] names = self.grouper.names + [self._selection_name] if dropna: @@ -1149,11 +1174,20 @@ def py_fallback(values: ArrayLike) -> ArrayLike: # We've split an object block! Everything we've assumed # about a single block input returning a single block output # is a lie. See eg GH-39329 - return mgr.as_array() + + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return mgr.as_array() # type: ignore[return-value] else: # We are a single block from a BlockManager # or one array from SingleArrayManager - return arrays[0] + + # error: Incompatible return value type (got "Union[ndarray, + # ExtensionArray, ArrayLike]", expected "ExtensionArray") + # error: Incompatible return value type (got "Union[ndarray, + # ExtensionArray, ArrayLike]", expected + # "ndarray") + return arrays[0] # type: ignore[return-value] def array_func(values: ArrayLike) -> ArrayLike: @@ -1172,7 +1206,9 @@ def array_func(values: ArrayLike) -> ArrayLike: assert how == "ohlc" raise - result = py_fallback(values) + # error: Incompatible types in assignment (expression has type + # "ExtensionArray", variable has type "ndarray") + result = py_fallback(values) # type: ignore[assignment] return cast_agg_result(result, values, how) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index e11c296783476..e5010da5ccac6 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1131,7 +1131,12 @@ def _cython_agg_general( if not output: raise DataError("No numeric types to aggregate") - return self._wrap_aggregated_output(output, index=self.grouper.result_index) + # error: Argument 1 to "_wrap_aggregated_output" of "BaseGroupBy" has + # incompatible type "Dict[OutputKey, Union[ndarray, DatetimeArray]]"; + # expected "Mapping[OutputKey, ndarray]" + return self._wrap_aggregated_output( + output, index=self.grouper.result_index # type: ignore[arg-type] + ) @final def _transform_with_numba(self, data, func, *args, engine_kwargs=None, **kwargs): @@ -2269,15 +2274,25 @@ def pre_processor(vals: np.ndarray) -> Tuple[np.ndarray, Optional[Type]]: inference = None if is_integer_dtype(vals.dtype): if is_extension_array_dtype(vals.dtype): - vals = vals.to_numpy(dtype=float, na_value=np.nan) + # error: "ndarray" has no attribute "to_numpy" + vals = vals.to_numpy( # type: ignore[attr-defined] + dtype=float, na_value=np.nan + ) inference = np.int64 elif is_bool_dtype(vals.dtype) and is_extension_array_dtype(vals.dtype): - vals = vals.to_numpy(dtype=float, na_value=np.nan) + # error: "ndarray" has no attribute "to_numpy" + vals = vals.to_numpy( # type: ignore[attr-defined] + dtype=float, na_value=np.nan + ) elif is_datetime64_dtype(vals.dtype): - inference = "datetime64[ns]" + # error: Incompatible types in assignment (expression has type + # "str", variable has type "Optional[Type[int64]]") + inference = "datetime64[ns]" # type: ignore[assignment] vals = np.asarray(vals).astype(float) elif is_timedelta64_dtype(vals.dtype): - inference = "timedelta64[ns]" + # error: Incompatible types in assignment (expression has type "str", + # variable has type "Optional[Type[signedinteger[Any]]]") + inference = "timedelta64[ns]" # type: ignore[assignment] vals = np.asarray(vals).astype(float) return vals, inference diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 89becb880c519..51f7b44f6d69d 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -583,7 +583,9 @@ def indices(self): def codes(self) -> np.ndarray: if self._codes is None: self._make_codes() - return self._codes + # error: Incompatible return value type (got "Optional[ndarray]", + # expected "ndarray") + return self._codes # type: ignore[return-value] @cache_readonly def result_index(self) -> Index: diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 008ee4dff4f7b..2d7547ff75ca4 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -539,7 +539,10 @@ def _ea_wrap_cython_operation( ) if how in ["rank"]: # preserve float64 dtype - return res_values + + # error: Incompatible return value type (got "ndarray", expected + # "Tuple[ndarray, Optional[List[str]]]") + return res_values # type: ignore[return-value] res_values = res_values.astype("i8", copy=False) result = type(orig_values)(res_values, dtype=orig_values.dtype) @@ -553,9 +556,13 @@ def _ea_wrap_cython_operation( ) dtype = maybe_cast_result_dtype(orig_values.dtype, how) if is_extension_array_dtype(dtype): - cls = dtype.construct_array_type() + # error: Item "dtype[Any]" of "Union[dtype[Any], ExtensionDtype]" has no + # attribute "construct_array_type" + cls = dtype.construct_array_type() # type: ignore[union-attr] return cls._from_sequence(res_values, dtype=dtype) - return res_values + # error: Incompatible return value type (got "ndarray", expected + # "Tuple[ndarray, Optional[List[str]]]") + return res_values # type: ignore[return-value] elif is_float_dtype(values.dtype): # FloatingArray @@ -592,7 +599,9 @@ def _cython_operation( self._disallow_invalid_ops(values, how) if is_extension_array_dtype(values.dtype): - return self._ea_wrap_cython_operation( + # error: Incompatible return value type (got "Tuple[ndarray, + # Optional[List[str]]]", expected "ndarray") + return self._ea_wrap_cython_operation( # type: ignore[return-value] kind, values, how, axis, min_count, **kwargs ) @@ -680,7 +689,9 @@ def _cython_operation( # e.g. if we are int64 and need to restore to datetime64/timedelta64 # "rank" is the only member of cython_cast_blocklist we get here dtype = maybe_cast_result_dtype(orig_values.dtype, how) - result = maybe_downcast_to_dtype(result, dtype) + # error: Argument 2 to "maybe_downcast_to_dtype" has incompatible type + # "Union[dtype[Any], ExtensionDtype]"; expected "Union[str, dtype[Any]]" + result = maybe_downcast_to_dtype(result, dtype) # type: ignore[arg-type] return result diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index e3f9f6dbb0025..9543b11ad4de1 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -191,7 +191,8 @@ str_t = str -_o_dtype = np.dtype(object) +# error: Value of type variable "_DTypeScalar" of "dtype" cannot be "object" +_o_dtype = np.dtype(object) # type: ignore[type-var] _Identity = NewType("_Identity", object) @@ -404,14 +405,23 @@ def __new__( # they are actually ints, e.g. '0' and 0.0 # should not be coerced # GH 11836 - data = _maybe_cast_with_dtype(data, dtype, copy) + + # error: Argument 1 to "_maybe_cast_with_dtype" has incompatible type + # "Union[ndarray, Index, Series]"; expected "ndarray" + data = _maybe_cast_with_dtype( + data, dtype, copy # type: ignore[arg-type] + ) dtype = data.dtype if data.dtype.kind in ["i", "u", "f"]: # maybe coerce to a sub-class arr = data else: - arr = com.asarray_tuplesafe(data, dtype=object) + # error: Argument "dtype" to "asarray_tuplesafe" has incompatible type + # "Type[object]"; expected "Union[str, dtype[Any], None]" + arr = com.asarray_tuplesafe( + data, dtype=object # type: ignore[arg-type] + ) if dtype is None: arr = _maybe_cast_data_without_dtype(arr) @@ -445,7 +455,10 @@ def __new__( data, names=name or kwargs.get("names") ) # other iterable of some kind - subarr = com.asarray_tuplesafe(data, dtype=object) + + # error: Argument "dtype" to "asarray_tuplesafe" has incompatible type + # "Type[object]"; expected "Union[str, dtype[Any], None]" + subarr = com.asarray_tuplesafe(data, dtype=object) # type: ignore[arg-type] return Index(subarr, dtype=dtype, copy=copy, name=name, **kwargs) @classmethod @@ -2889,10 +2902,16 @@ def union(self, other, sort=None): # <T> | <T> -> T # <T> | <U> -> object if not (is_integer_dtype(self.dtype) and is_integer_dtype(other.dtype)): - dtype = "float64" + # error: Incompatible types in assignment (expression has type + # "str", variable has type "Union[dtype[Any], ExtensionDtype]") + dtype = "float64" # type: ignore[assignment] else: # one is int64 other is uint64 - dtype = object + + # error: Incompatible types in assignment (expression has type + # "Type[object]", variable has type "Union[dtype[Any], + # ExtensionDtype]") + dtype = object # type: ignore[assignment] left = self.astype(dtype, copy=False) right = other.astype(dtype, copy=False) @@ -2941,7 +2960,11 @@ def _union(self, other: Index, sort): ): # Both are unique and monotonic, so can use outer join try: - return self._outer_indexer(lvals, rvals)[0] + # error: Argument 1 to "_outer_indexer" of "Index" has incompatible type + # "Union[ExtensionArray, ndarray]"; expected "ndarray" + # error: Argument 2 to "_outer_indexer" of "Index" has incompatible type + # "Union[ExtensionArray, ndarray]"; expected "ndarray" + return self._outer_indexer(lvals, rvals)[0] # type: ignore[arg-type] except (TypeError, IncompatibleFrequency): # incomparable objects value_list = list(lvals) @@ -2953,7 +2976,12 @@ def _union(self, other: Index, sort): elif not other.is_unique and not self.is_unique: # self and other both have duplicates - result = algos.union_with_duplicates(lvals, rvals) + + # error: Argument 1 to "union_with_duplicates" has incompatible type + # "Union[ExtensionArray, ndarray]"; expected "ndarray" + # error: Argument 2 to "union_with_duplicates" has incompatible type + # "Union[ExtensionArray, ndarray]"; expected "ndarray" + result = algos.union_with_duplicates(lvals, rvals) # type: ignore[arg-type] return _maybe_try_sort(result, sort) # Either other or self is not unique @@ -2965,10 +2993,16 @@ def _union(self, other: Index, sort): missing = algos.unique1d(self.get_indexer_non_unique(other)[1]) if len(missing) > 0: - other_diff = algos.take_nd(rvals, missing, allow_fill=False) + # error: Value of type variable "ArrayLike" of "take_nd" cannot be + # "Union[ExtensionArray, ndarray]" + other_diff = algos.take_nd( + rvals, missing, allow_fill=False # type: ignore[type-var] + ) result = concat_compat((lvals, other_diff)) else: - result = lvals + # error: Incompatible types in assignment (expression has type + # "Union[ExtensionArray, ndarray]", variable has type "ndarray") + result = lvals # type: ignore[assignment] if not self.is_monotonic or not other.is_monotonic: result = _maybe_try_sort(result, sort) @@ -3058,7 +3092,9 @@ def _intersection(self, other: Index, sort=False): if self.is_monotonic and other.is_monotonic: try: - result = self._inner_indexer(lvals, rvals)[0] + # error: Argument 1 to "_inner_indexer" of "Index" has incompatible type + # "Union[ExtensionArray, ndarray]"; expected "ndarray" + result = self._inner_indexer(lvals, rvals)[0] # type: ignore[arg-type] except TypeError: pass else: @@ -3964,11 +4000,15 @@ def join(self, other, how="left", level=None, return_indexers=False, sort=False) if return_indexers: if join_index is self: - lindexer = None + # error: Incompatible types in assignment (expression has type "None", + # variable has type "ndarray") + lindexer = None # type: ignore[assignment] else: lindexer = self.get_indexer(join_index) if join_index is other: - rindexer = None + # error: Incompatible types in assignment (expression has type "None", + # variable has type "ndarray") + rindexer = None # type: ignore[assignment] else: rindexer = other.get_indexer(join_index) return join_index, lindexer, rindexer @@ -4075,7 +4115,11 @@ def _join_non_unique(self, other, how="left", return_indexers=False): mask = left_idx == -1 np.putmask(join_index, mask, rvalues.take(right_idx)) - join_index = self._wrap_joined_index(join_index, other) + # error: Incompatible types in assignment (expression has type "Index", variable + # has type "ndarray") + join_index = self._wrap_joined_index( + join_index, other # type: ignore[assignment] + ) if return_indexers: return join_index, left_idx, right_idx @@ -4248,23 +4292,61 @@ def _join_monotonic(self, other, how="left", return_indexers=False): elif how == "right": join_index = other lidx = self._left_indexer_unique(ov, sv) - ridx = None + # error: Incompatible types in assignment (expression has type "None", + # variable has type "ndarray") + ridx = None # type: ignore[assignment] elif how == "inner": - join_index, lidx, ridx = self._inner_indexer(sv, ov) - join_index = self._wrap_joined_index(join_index, other) + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "Index") + join_index, lidx, ridx = self._inner_indexer( # type:ignore[assignment] + sv, ov + ) + # error: Argument 1 to "_wrap_joined_index" of "Index" has incompatible + # type "Index"; expected "ndarray" + join_index = self._wrap_joined_index( + join_index, other # type: ignore[arg-type] + ) elif how == "outer": - join_index, lidx, ridx = self._outer_indexer(sv, ov) - join_index = self._wrap_joined_index(join_index, other) + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "Index") + join_index, lidx, ridx = self._outer_indexer( # type:ignore[assignment] + sv, ov + ) + # error: Argument 1 to "_wrap_joined_index" of "Index" has incompatible + # type "Index"; expected "ndarray" + join_index = self._wrap_joined_index( + join_index, other # type: ignore[arg-type] + ) else: if how == "left": - join_index, lidx, ridx = self._left_indexer(sv, ov) + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "Index") + join_index, lidx, ridx = self._left_indexer( # type: ignore[assignment] + sv, ov + ) elif how == "right": - join_index, ridx, lidx = self._left_indexer(ov, sv) + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "Index") + join_index, ridx, lidx = self._left_indexer( # type: ignore[assignment] + ov, sv + ) elif how == "inner": - join_index, lidx, ridx = self._inner_indexer(sv, ov) + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "Index") + join_index, lidx, ridx = self._inner_indexer( # type:ignore[assignment] + sv, ov + ) elif how == "outer": - join_index, lidx, ridx = self._outer_indexer(sv, ov) - join_index = self._wrap_joined_index(join_index, other) + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "Index") + join_index, lidx, ridx = self._outer_indexer( # type:ignore[assignment] + sv, ov + ) + # error: Argument 1 to "_wrap_joined_index" of "Index" has incompatible type + # "Index"; expected "ndarray" + join_index = self._wrap_joined_index( + join_index, other # type: ignore[arg-type] + ) if return_indexers: lidx = None if lidx is None else ensure_platform_int(lidx) @@ -4307,7 +4389,11 @@ def values(self) -> ArrayLike: Index.array : Reference to the underlying data. Index.to_numpy : A NumPy array representing the underlying data. """ - return self._data + # error: Incompatible return value type (got "Union[ExtensionArray, ndarray]", + # expected "ExtensionArray") + # error: Incompatible return value type (got "Union[ExtensionArray, ndarray]", + # expected "ndarray") + return self._data # type: ignore[return-value] @cache_readonly @doc(IndexOpsMixin.array) @@ -4349,7 +4435,9 @@ def _get_engine_target(self) -> np.ndarray: """ Get the ndarray that we can pass to the IndexEngine constructor. """ - return self._values + # error: Incompatible return value type (got "Union[ExtensionArray, + # ndarray]", expected "ndarray") + return self._values # type: ignore[return-value] @doc(IndexOpsMixin.memory_usage) def memory_usage(self, deep: bool = False) -> int: @@ -4542,7 +4630,11 @@ def __getitem__(self, key): result = getitem(key) if not is_scalar(result): - if np.ndim(result) > 1: + # error: Argument 1 to "ndim" has incompatible type "Union[ExtensionArray, + # Any]"; expected "Union[Union[int, float, complex, str, bytes, generic], + # Sequence[Union[int, float, complex, str, bytes, generic]], + # Sequence[Sequence[Any]], _SupportsArray]" + if np.ndim(result) > 1: # type: ignore[arg-type] deprecate_ndim_indexing(result) return result # NB: Using _constructor._simple_new would break if MultiIndex @@ -4622,7 +4714,9 @@ def putmask(self, mask, value): numpy.ndarray.putmask : Changes elements of an array based on conditional and input values. """ - mask, noop = validate_putmask(self._values, mask) + # error: Value of type variable "ArrayLike" of "validate_putmask" cannot be + # "Union[ExtensionArray, ndarray]" + mask, noop = validate_putmask(self._values, mask) # type: ignore[type-var] if noop: return self.copy() @@ -4638,7 +4732,11 @@ def putmask(self, mask, value): return self.astype(dtype).putmask(mask, value) values = self._values.copy() - converted = setitem_datetimelike_compat(values, mask.sum(), converted) + # error: Argument 1 to "setitem_datetimelike_compat" has incompatible type + # "Union[ExtensionArray, ndarray]"; expected "ndarray" + converted = setitem_datetimelike_compat( + values, mask.sum(), converted # type: ignore[arg-type] + ) np.putmask(values, mask, converted) return type(self)._simple_new(values, name=self.name) @@ -5502,7 +5600,9 @@ def isin(self, values, level=None): """ if level is not None: self._validate_index_level(level) - return algos.isin(self._values, values) + # error: Value of type variable "AnyArrayLike" of "isin" cannot be + # "Union[ExtensionArray, ndarray]" + return algos.isin(self._values, values) # type: ignore[type-var] def _get_string_slice(self, key: str_t): # this is for partial string indexing, @@ -5923,7 +6023,11 @@ def _cmp_method(self, other, op): else: with np.errstate(all="ignore"): - result = ops.comparison_op(self._values, other, op) + # error: Value of type variable "ArrayLike" of "comparison_op" cannot be + # "Union[ExtensionArray, ndarray]" + result = ops.comparison_op( + self._values, other, op # type: ignore[type-var] + ) return result @@ -5996,7 +6100,11 @@ def any(self, *args, **kwargs): """ nv.validate_any(args, kwargs) self._maybe_disable_logical_methods("any") - return np.any(self.values) + # error: Argument 1 to "any" has incompatible type "ArrayLike"; expected + # "Union[Union[int, float, complex, str, bytes, generic], Sequence[Union[int, + # float, complex, str, bytes, generic]], Sequence[Sequence[Any]], + # _SupportsArray]" + return np.any(self.values) # type: ignore[arg-type] def all(self, *args, **kwargs): """ @@ -6053,7 +6161,11 @@ def all(self, *args, **kwargs): """ nv.validate_all(args, kwargs) self._maybe_disable_logical_methods("all") - return np.all(self.values) + # error: Argument 1 to "all" has incompatible type "ArrayLike"; expected + # "Union[Union[int, float, complex, str, bytes, generic], Sequence[Union[int, + # float, complex, str, bytes, generic]], Sequence[Sequence[Any]], + # _SupportsArray]" + return np.all(self.values) # type: ignore[arg-type] @final def _maybe_disable_logical_methods(self, opname: str_t): @@ -6340,7 +6452,11 @@ def _maybe_cast_data_without_dtype(subarr): if inferred == "integer": try: - data = _try_convert_to_int_array(subarr, False, None) + # error: Argument 3 to "_try_convert_to_int_array" has incompatible type + # "None"; expected "dtype[Any]" + data = _try_convert_to_int_array( + subarr, False, None # type: ignore[arg-type] + ) return data except ValueError: pass @@ -6374,7 +6490,11 @@ def _maybe_cast_data_without_dtype(subarr): pass elif inferred.startswith("timedelta"): - data = TimedeltaArray._from_sequence(subarr, copy=False) + # error: Incompatible types in assignment (expression has type + # "TimedeltaArray", variable has type "ndarray") + data = TimedeltaArray._from_sequence( # type: ignore[assignment] + subarr, copy=False + ) return data elif inferred == "period": try: diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 869836a3da70c..a38ef55614638 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -193,12 +193,17 @@ def _can_hold_strings(self): def _engine_type(self): # self.codes can have dtype int8, int16, int32 or int64, so we need # to return the corresponding engine type (libindex.Int8Engine, etc.). + + # error: Invalid index type "Type[generic]" for "Dict[Type[signedinteger[Any]], + # Any]"; expected type "Type[signedinteger[Any]]" return { np.int8: libindex.Int8Engine, np.int16: libindex.Int16Engine, np.int32: libindex.Int32Engine, np.int64: libindex.Int64Engine, - }[self.codes.dtype.type] + }[ + self.codes.dtype.type # type: ignore[index] + ] _attributes = ["name"] @@ -484,7 +489,9 @@ def _get_indexer( if self.equals(target): return np.arange(len(self), dtype="intp") - return self._get_indexer_non_unique(target._values)[0] + # error: Value of type variable "ArrayLike" of "_get_indexer_non_unique" of + # "CategoricalIndex" cannot be "Union[ExtensionArray, ndarray]" + return self._get_indexer_non_unique(target._values)[0] # type: ignore[type-var] @Appender(_index_shared_docs["get_indexer_non_unique"] % _index_doc_kwargs) def get_indexer_non_unique(self, target): diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 1dd5b40f7102f..793dd041fbf6f 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -136,7 +136,9 @@ def _is_all_dates(self) -> bool: # Abstract data attributes @property - def values(self) -> np.ndarray: + # error: Return type "ndarray" of "values" incompatible with return type "ArrayLike" + # in supertype "Index" + def values(self) -> np.ndarray: # type: ignore[override] # Note: PeriodArray overrides this to return an ndarray of objects. return self._data._ndarray @@ -528,8 +530,10 @@ def shift(self: _T, periods: int = 1, freq=None) -> _T: PeriodIndex.shift : Shift values of PeriodIndex. """ arr = self._data.view() - arr._freq = self.freq - result = arr._time_shift(periods, freq=freq) + # error: "ExtensionArray" has no attribute "_freq" + arr._freq = self.freq # type: ignore[attr-defined] + # error: "ExtensionArray" has no attribute "_time_shift" + result = arr._time_shift(periods, freq=freq) # type: ignore[attr-defined] return type(self)(result, name=self.name) # -------------------------------------------------------------------- @@ -772,7 +776,8 @@ def _fast_union(self: _T, other: _T, sort=None) -> _T: left, right = self, other left_start = left[0] loc = right.searchsorted(left_start, side="left") - right_chunk = right._values[:loc] + # error: Slice index must be an integer or None + right_chunk = right._values[:loc] # type: ignore[misc] dates = concat_compat((left._values, right_chunk)) # With sort being False, we can't infer that result.freq == self.freq # TODO: no tests rely on the _with_freq("infer"); needed? @@ -788,7 +793,8 @@ def _fast_union(self: _T, other: _T, sort=None) -> _T: # concatenate if left_end < right_end: loc = right.searchsorted(left_end, side="right") - right_chunk = right._values[loc:] + # error: Slice index must be an integer or None + right_chunk = right._values[loc:] # type: ignore[misc] dates = concat_compat([left._values, right_chunk]) # The can_fast_union check ensures that the result.freq # should match self.freq diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 9ea43d083f5b3..ed0856f3d30a3 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -365,7 +365,10 @@ def _is_dates_only(self) -> bool: """ from pandas.io.formats.format import is_dates_only - return self.tz is None and is_dates_only(self._values) + # error: Argument 1 to "is_dates_only" has incompatible type + # "Union[ExtensionArray, ndarray]"; expected "Union[ndarray, + # DatetimeArray, Index, DatetimeIndex]" + return self.tz is None and is_dates_only(self._values) # type: ignore[arg-type] def __reduce__(self): @@ -533,7 +536,9 @@ def to_series(self, keep_tz=lib.no_default, index=None, name=None): # preserve the tz & copy values = self.copy(deep=True) else: - values = self._values.view("M8[ns]").copy() + # error: Incompatible types in assignment (expression has type + # "Union[ExtensionArray, ndarray]", variable has type "DatetimeIndex") + values = self._values.view("M8[ns]").copy() # type: ignore[assignment] return Series(values, index=index, name=name) diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index a5899f83dd238..4c15e9df534ba 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -339,7 +339,9 @@ def astype(self, dtype, copy=True): @cache_readonly def _isnan(self) -> np.ndarray: - return self._data.isna() + # error: Incompatible return value type (got "ExtensionArray", expected + # "ndarray") + return self._data.isna() # type: ignore[return-value] @doc(Index.equals) def equals(self, other) -> bool: diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index ad512b8393166..58c5b23d12a35 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1227,8 +1227,16 @@ def interval_range( else: # delegate to the appropriate range function if isinstance(endpoint, Timestamp): - breaks = date_range(start=start, end=end, periods=periods, freq=freq) + # error: Incompatible types in assignment (expression has type + # "DatetimeIndex", variable has type "ndarray") + breaks = date_range( # type: ignore[assignment] + start=start, end=end, periods=periods, freq=freq + ) else: - breaks = timedelta_range(start=start, end=end, periods=periods, freq=freq) + # error: Incompatible types in assignment (expression has type + # "TimedeltaIndex", variable has type "ndarray") + breaks = timedelta_range( # type: ignore[assignment] + start=start, end=end, periods=periods, freq=freq + ) return IntervalIndex.from_breaks(breaks, name=name, closed=closed) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index fc3e404998b43..3b538b948ae81 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -711,14 +711,18 @@ def _values(self) -> np.ndarray: vals, (ABCDatetimeIndex, ABCTimedeltaIndex) ): vals = vals.astype(object) - vals = np.array(vals, copy=False) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "Index") + vals = np.array(vals, copy=False) # type: ignore[assignment] values.append(vals) arr = lib.fast_zip(values) return arr @property - def values(self) -> np.ndarray: + # error: Return type "ndarray" of "values" incompatible with return type "ArrayLike" + # in supertype "Index" + def values(self) -> np.ndarray: # type: ignore[override] return self._values @property @@ -2218,7 +2222,11 @@ def drop(self, codes, level=None, errors="raise"): if not isinstance(codes, (np.ndarray, Index)): try: - codes = com.index_labels_to_array(codes, dtype=object) + # error: Argument "dtype" to "index_labels_to_array" has incompatible + # type "Type[object]"; expected "Union[str, dtype[Any], None]" + codes = com.index_labels_to_array( + codes, dtype=object # type: ignore[arg-type] + ) except ValueError: pass @@ -3162,10 +3170,14 @@ def convert_indexer(start, stop, step, indexer=indexer, codes=level_codes): indexer = codes.take(ensure_platform_int(indexer)) result = Series(Index(indexer).isin(r).nonzero()[0]) m = result.map(mapper) - m = np.asarray(m) + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "Series") + m = np.asarray(m) # type: ignore[assignment] else: - m = np.zeros(len(codes), dtype=bool) + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "Series") + m = np.zeros(len(codes), dtype=bool) # type: ignore[assignment] m[np.in1d(codes, r, assume_unique=Index(codes).is_unique)] = True return m diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index a581516f23feb..b6f476d864011 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -253,7 +253,9 @@ def asi8(self) -> np.ndarray: FutureWarning, stacklevel=2, ) - return self._values.view(self._default_dtype) + # error: Incompatible return value type (got "Union[ExtensionArray, ndarray]", + # expected "ndarray") + return self._values.view(self._default_dtype) # type: ignore[return-value] class Int64Index(IntegerIndex): @@ -292,7 +294,10 @@ def _convert_arr_indexer(self, keyarr): ): dtype = np.uint64 - return com.asarray_tuplesafe(keyarr, dtype=dtype) + # error: Argument "dtype" to "asarray_tuplesafe" has incompatible type + # "Optional[Type[unsignedinteger[Any]]]"; expected "Union[str, dtype[Any], + # None]" + return com.asarray_tuplesafe(keyarr, dtype=dtype) # type: ignore[arg-type] _float64_descr_args = { @@ -328,7 +333,10 @@ def astype(self, dtype, copy=True): elif is_integer_dtype(dtype) and not is_extension_array_dtype(dtype): # TODO(jreback); this can change once we have an EA Index type # GH 13149 - arr = astype_nansafe(self._values, dtype=dtype) + + # error: Argument 1 to "astype_nansafe" has incompatible type + # "Union[ExtensionArray, ndarray]"; expected "ndarray" + arr = astype_nansafe(self._values, dtype=dtype) # type: ignore[arg-type] return Int64Index(arr, name=self.name) return super().astype(dtype, copy=copy) diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 0c5dbec2094e5..b15912e4c477b 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -275,7 +275,9 @@ def __new__( # Data @property - def values(self) -> np.ndarray: + # error: Return type "ndarray" of "values" incompatible with return type "ArrayLike" + # in supertype "Index" + def values(self) -> np.ndarray: # type: ignore[override] return np.asarray(self, dtype=object) def _maybe_convert_timedelta(self, other): diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 56093c2a399c2..05bb32dad6cab 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -111,7 +111,12 @@ def __new__( name=None, ): - cls._validate_dtype(dtype) + # error: Argument 1 to "_validate_dtype" of "NumericIndex" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[str], Type[float], Type[int], + # Type[complex], Type[bool], Type[object], None]"; expected + # "Union[ExtensionDtype, Union[str, dtype[Any]], Type[str], Type[float], + # Type[int], Type[complex], Type[bool], Type[object]]" + cls._validate_dtype(dtype) # type: ignore[arg-type] name = maybe_extract_name(name, start, cls) # RangeIndex @@ -155,7 +160,12 @@ def from_range( f"range, {repr(data)} was passed" ) - cls._validate_dtype(dtype) + # error: Argument 1 to "_validate_dtype" of "NumericIndex" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[str], Type[float], Type[int], + # Type[complex], Type[bool], Type[object], None]"; expected + # "Union[ExtensionDtype, Union[str, dtype[Any]], Type[str], Type[float], + # Type[int], Type[complex], Type[bool], Type[object]]" + cls._validate_dtype(dtype) # type: ignore[arg-type] return cls._simple_new(data, name=name) @classmethod @@ -901,7 +911,8 @@ def _arith_method(self, other, op): # apply if we have an override if step: with np.errstate(all="ignore"): - rstep = step(left.step, right) + # error: "bool" not callable + rstep = step(left.step, right) # type: ignore[operator] # we don't have a representable op # so return a base index diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index bbe71c4977e77..0ab4bc991f468 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -267,7 +267,11 @@ def reduce( if res is NaT and is_timedelta64_ns_dtype(arr.dtype): result_arrays.append(np.array(["NaT"], dtype="timedelta64[ns]")) else: - result_arrays.append(sanitize_array([res], None)) + # error: Argument 1 to "append" of "list" has incompatible type + # "ExtensionArray"; expected "ndarray" + result_arrays.append( + sanitize_array([res], None) # type: ignore[arg-type] + ) result_indices.append(i) index = Index._simple_new(np.array([None], dtype=object)) # placeholder @@ -278,7 +282,9 @@ def reduce( indexer = np.arange(self.shape[0]) columns = self.items - new_mgr = type(self)(result_arrays, [index, columns]) + # error: Argument 1 to "ArrayManager" has incompatible type "List[ndarray]"; + # expected "List[Union[ndarray, ExtensionArray]]" + new_mgr = type(self)(result_arrays, [index, columns]) # type: ignore[arg-type] return new_mgr, indexer def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T: @@ -318,7 +324,9 @@ def grouped_reduce(self: T, func: Callable, ignore_failures: bool = False) -> T: else: columns = self.items - return type(self)(result_arrays, [index, columns]) + # error: Argument 1 to "ArrayManager" has incompatible type "List[ndarray]"; + # expected "List[Union[ndarray, ExtensionArray]]" + return type(self)(result_arrays, [index, columns]) # type: ignore[arg-type] def operate_blockwise(self, other: ArrayManager, array_op) -> ArrayManager: """ @@ -408,7 +416,9 @@ def apply( if len(result_arrays) == 0: return self.make_empty(new_axes) - return type(self)(result_arrays, new_axes) + # error: Argument 1 to "ArrayManager" has incompatible type "List[ndarray]"; + # expected "List[Union[ndarray, ExtensionArray]]" + return type(self)(result_arrays, new_axes) # type: ignore[arg-type] def apply_2d(self: T, f, ignore_failures: bool = False, **kwargs) -> T: """ @@ -469,9 +479,8 @@ def apply_with_block(self: T, f, align_keys=None, swap_axis=True, **kwargs) -> T elif arr.dtype.kind == "m" and not isinstance(arr, np.ndarray): # TimedeltaArray needs to be converted to ndarray for TimedeltaBlock - # error: Item "ExtensionArray" of "Union[Any, ExtensionArray]" has no - # attribute "_data" - arr = arr._data # type: ignore[union-attr] + # error: "ExtensionArray" has no attribute "_data" + arr = arr._data # type: ignore[attr-defined] if self.ndim == 2: if isinstance(arr, np.ndarray): @@ -500,9 +509,16 @@ def quantile( interpolation="linear", ) -> ArrayManager: - arrs = [ensure_block_shape(x, 2) for x in self.arrays] + # error: Value of type variable "ArrayLike" of "ensure_block_shape" cannot be + # "Union[ndarray, ExtensionArray]" + arrs = [ensure_block_shape(x, 2) for x in self.arrays] # type: ignore[type-var] assert axis == 1 - new_arrs = [quantile_compat(x, qs, interpolation, axis=axis) for x in arrs] + # error: Value of type variable "ArrayLike" of "quantile_compat" cannot be + # "object" + new_arrs = [ + quantile_compat(x, qs, interpolation, axis=axis) # type: ignore[type-var] + for x in arrs + ] for i, arr in enumerate(new_arrs): if arr.ndim == 2: assert arr.shape[0] == 1, arr.shape @@ -765,7 +781,9 @@ def as_array( result = np.empty(self.shape_proper, dtype=dtype) - for i, arr in enumerate(self.arrays): + # error: Incompatible types in assignment (expression has type "Union[ndarray, + # ExtensionArray]", variable has type "ndarray") + for i, arr in enumerate(self.arrays): # type: ignore[assignment] arr = arr.astype(dtype, copy=copy) result[:, i] = arr @@ -827,7 +845,11 @@ def iget_values(self, i: int) -> ArrayLike: """ Return the data for column i as the values (ndarray or ExtensionArray). """ - return self.arrays[i] + # error: Incompatible return value type (got "Union[ndarray, ExtensionArray]", + # expected "ExtensionArray") + # error: Incompatible return value type (got "Union[ndarray, ExtensionArray]", + # expected "ndarray") + return self.arrays[i] # type: ignore[return-value] def idelete(self, indexer): """ @@ -870,7 +892,9 @@ def iset(self, loc: Union[int, slice, np.ndarray], value): assert isinstance(value, (np.ndarray, ExtensionArray)) assert value.ndim == 1 assert len(value) == len(self._axes[0]) - self.arrays[loc] = value + # error: Invalid index type "Union[int, slice, ndarray]" for + # "List[Union[ndarray, ExtensionArray]]"; expected type "int" + self.arrays[loc] = value # type: ignore[index] return # multiple columns -> convert slice or array to integer indices @@ -883,7 +907,9 @@ def iset(self, loc: Union[int, slice, np.ndarray], value): else: assert isinstance(loc, np.ndarray) assert loc.dtype == "bool" - indices = np.nonzero(loc)[0] + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "range") + indices = np.nonzero(loc)[0] # type: ignore[assignment] assert value.ndim == 2 assert value.shape[0] == len(self._axes[0]) @@ -1002,7 +1028,9 @@ def _reindex_indexer( else: validate_indices(indexer, len(self._axes[0])) new_arrays = [ - take_1d( + # error: Value of type variable "ArrayLike" of "take_1d" cannot be + # "Union[ndarray, ExtensionArray]" [type-var] + take_1d( # type: ignore[type-var] arr, indexer, allow_fill=True, @@ -1047,7 +1075,11 @@ def _make_na_array(self, fill_value=None): fill_value = np.nan dtype, fill_value = infer_dtype_from_scalar(fill_value) - values = np.empty(self.shape_proper[0], dtype=dtype) + # error: Argument "dtype" to "empty" has incompatible type "Union[dtype[Any], + # ExtensionDtype]"; expected "Union[dtype[Any], None, type, _SupportsDType, str, + # Union[Tuple[Any, int], Tuple[Any, Union[int, Sequence[int]]], List[Any], + # _DTypeDict, Tuple[Any, Any]]]" + values = np.empty(self.shape_proper[0], dtype=dtype) # type: ignore[arg-type] values.fill(fill_value) return values @@ -1057,7 +1089,9 @@ def _equal_values(self, other) -> bool: assuming shape and indexes have already been checked. """ for left, right in zip(self.arrays, other.arrays): - if not array_equals(left, right): + # error: Value of type variable "ArrayLike" of "array_equals" cannot be + # "Union[Any, ndarray, ExtensionArray]" + if not array_equals(left, right): # type: ignore[type-var] return False else: return True @@ -1084,7 +1118,9 @@ def unstack(self, unstacker, fill_value) -> ArrayManager: new_arrays = [] for arr in self.arrays: for i in range(unstacker.full_shape[1]): - new_arr = take_1d( + # error: Value of type variable "ArrayLike" of "take_1d" cannot be + # "Union[ndarray, ExtensionArray]" [type-var] + new_arr = take_1d( # type: ignore[type-var] arr, new_indexer2D[:, i], allow_fill=True, fill_value=fill_value ) new_arrays.append(new_arr) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index f0d7d7e441527..1767b56962db1 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -117,8 +117,10 @@ ) from pandas.core.arrays._mixins import NDArrayBackedExtensionArray +# comparison is faster than is_object_dtype -_dtype_obj = np.dtype(object) # comparison is faster than is_object_dtype +# error: Value of type variable "_DTypeScalar" of "dtype" cannot be "object" +_dtype_obj = np.dtype(object) # type: ignore[type-var] class Block(PandasObject): @@ -277,7 +279,9 @@ def array_values(self) -> ExtensionArray: """ The array that Series.array returns. Always an ExtensionArray. """ - return PandasArray(self.values) + # error: Argument 1 to "PandasArray" has incompatible type "Union[ndarray, + # ExtensionArray]"; expected "Union[ndarray, PandasArray]" + return PandasArray(self.values) # type: ignore[arg-type] def get_values(self, dtype: Optional[DtypeObj] = None) -> np.ndarray: """ @@ -286,7 +290,9 @@ def get_values(self, dtype: Optional[DtypeObj] = None) -> np.ndarray: """ if dtype == _dtype_obj: return self.values.astype(_dtype_obj) - return self.values + # error: Incompatible return value type (got "Union[ndarray, ExtensionArray]", + # expected "ndarray") + return self.values # type: ignore[return-value] @final def get_block_values_for_json(self) -> np.ndarray: @@ -474,7 +480,9 @@ def fillna( inplace = validate_bool_kwarg(inplace, "inplace") mask = isna(self.values) - mask, noop = validate_putmask(self.values, mask) + # error: Value of type variable "ArrayLike" of "validate_putmask" cannot be + # "Union[ndarray, ExtensionArray]" + mask, noop = validate_putmask(self.values, mask) # type: ignore[type-var] if limit is not None: limit = libalgos.validate_limit(None, limit=limit) @@ -617,7 +625,9 @@ def downcast(self, dtypes=None) -> List[Block]: if dtypes is None: dtypes = "infer" - nv = maybe_downcast_to_dtype(values, dtypes) + # error: Value of type variable "ArrayLike" of "maybe_downcast_to_dtype" + # cannot be "Union[ndarray, ExtensionArray]" + nv = maybe_downcast_to_dtype(values, dtypes) # type: ignore[type-var] return [self.make_block(nv)] # ndim > 1 @@ -661,7 +671,11 @@ def astype(self, dtype, copy: bool = False, errors: str = "raise"): if values.dtype.kind in ["m", "M"]: values = self.array_values() - new_values = astype_array_safe(values, dtype, copy=copy, errors=errors) + # error: Value of type variable "ArrayLike" of "astype_array_safe" cannot be + # "Union[ndarray, ExtensionArray]" + new_values = astype_array_safe( + values, dtype, copy=copy, errors=errors # type: ignore[type-var] + ) newb = self.make_block(new_values) if newb.shape != self.shape: @@ -758,7 +772,9 @@ def replace( values = self.values - mask = missing.mask_missing(values, to_replace) + # error: Value of type variable "ArrayLike" of "mask_missing" cannot be + # "Union[ndarray, ExtensionArray]" + mask = missing.mask_missing(values, to_replace) # type: ignore[type-var] if not mask.any(): # Note: we get here with test_replace_extension_other incorrectly # bc _can_hold_element is incorrect. @@ -785,7 +801,9 @@ def replace( ) blk = self if inplace else self.copy() - putmask_inplace(blk.values, mask, value) + # error: Value of type variable "ArrayLike" of "putmask_inplace" cannot be + # "Union[ndarray, ExtensionArray]" + putmask_inplace(blk.values, mask, value) # type: ignore[type-var] blocks = blk.convert(numeric=False, copy=False) return blocks @@ -826,7 +844,9 @@ def _replace_regex( rx = re.compile(to_replace) new_values = self.values if inplace else self.values.copy() - replace_regex(new_values, rx, value, mask) + # error: Value of type variable "ArrayLike" of "replace_regex" cannot be + # "Union[ndarray, ExtensionArray]" + replace_regex(new_values, rx, value, mask) # type: ignore[type-var] block = self.make_block(new_values) return [block] @@ -863,14 +883,26 @@ def _replace_list( # in order to avoid repeating the same computations mask = ~isna(self.values) masks = [ - compare_or_regex_search(self.values, s[0], regex=regex, mask=mask) + # error: Value of type variable "ArrayLike" of "compare_or_regex_search" + # cannot be "Union[ndarray, ExtensionArray]" + compare_or_regex_search( # type: ignore[type-var] + self.values, s[0], regex=regex, mask=mask + ) for s in pairs ] else: # GH#38086 faster if we know we dont need to check for regex - masks = [missing.mask_missing(self.values, s[0]) for s in pairs] - masks = [extract_bool_array(x) for x in masks] + # error: Value of type variable "ArrayLike" of "mask_missing" cannot be + # "Union[ndarray, ExtensionArray]" + masks = [ + missing.mask_missing(self.values, s[0]) # type: ignore[type-var] + for s in pairs + ] + + # error: Value of type variable "ArrayLike" of "extract_bool_array" cannot be + # "Union[ndarray, ExtensionArray, bool]" + masks = [extract_bool_array(x) for x in masks] # type: ignore[type-var] rb = [self if inplace else self.copy()] for i, (src, dest) in enumerate(pairs): @@ -928,7 +960,9 @@ def _replace_coerce( nb = self.coerce_to_target_dtype(value) if nb is self and not inplace: nb = nb.copy() - putmask_inplace(nb.values, mask, value) + # error: Value of type variable "ArrayLike" of "putmask_inplace" cannot + # be "Union[ndarray, ExtensionArray]" + putmask_inplace(nb.values, mask, value) # type: ignore[type-var] return [nb] else: regex = should_use_regex(regex, to_replace) @@ -1001,7 +1035,9 @@ def setitem(self, indexer, value): # length checking check_setitem_lengths(indexer, value, values) - exact_match = is_exact_shape_match(values, arr_value) + # error: Value of type variable "ArrayLike" of "is_exact_shape_match" cannot be + # "Union[Any, ndarray, ExtensionArray]" + exact_match = is_exact_shape_match(values, arr_value) # type: ignore[type-var] if is_empty_indexer(indexer, arr_value): # GH#8669 empty indexers @@ -1040,7 +1076,11 @@ def setitem(self, indexer, value): values[indexer] = value.to_numpy(values.dtype).reshape(-1, 1) else: - value = setitem_datetimelike_compat(values, len(values[indexer]), value) + # error: Argument 1 to "setitem_datetimelike_compat" has incompatible type + # "Union[ndarray, ExtensionArray]"; expected "ndarray" + value = setitem_datetimelike_compat( + values, len(values[indexer]), value # type: ignore[arg-type] + ) values[indexer] = value if transpose: @@ -1065,7 +1105,9 @@ def putmask(self, mask, new) -> List[Block]: List[Block] """ orig_mask = mask - mask, noop = validate_putmask(self.values.T, mask) + # error: Value of type variable "ArrayLike" of "validate_putmask" cannot be + # "Union[ndarray, ExtensionArray]" + mask, noop = validate_putmask(self.values.T, mask) # type: ignore[type-var] assert not isinstance(new, (ABCIndex, ABCSeries, ABCDataFrame)) # if we are passed a scalar None, convert it here @@ -1074,7 +1116,9 @@ def putmask(self, mask, new) -> List[Block]: if self._can_hold_element(new): - putmask_without_repeat(self.values.T, mask, new) + # error: Argument 1 to "putmask_without_repeat" has incompatible type + # "Union[ndarray, ExtensionArray]"; expected "ndarray" + putmask_without_repeat(self.values.T, mask, new) # type: ignore[arg-type] return [self] elif noop: @@ -1089,7 +1133,10 @@ def putmask(self, mask, new) -> List[Block]: elif self.ndim == 1 or self.shape[0] == 1: # no need to split columns - nv = putmask_smart(self.values.T, mask, new).T + + # error: Argument 1 to "putmask_smart" has incompatible type "Union[ndarray, + # ExtensionArray]"; expected "ndarray" + nv = putmask_smart(self.values.T, mask, new).T # type: ignore[arg-type] return [self.make_block(nv)] else: @@ -1285,7 +1332,9 @@ def take_nd( else: allow_fill = True - new_values = algos.take_nd( + # error: Value of type variable "ArrayLike" of "take_nd" cannot be + # "Union[ndarray, ExtensionArray]" + new_values = algos.take_nd( # type: ignore[type-var] values, indexer, axis=axis, allow_fill=allow_fill, fill_value=fill_value ) @@ -1309,7 +1358,12 @@ def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> List[Blo """ shift the block by periods, possibly upcast """ # convert integer to float if necessary. need to do a lot more than # that, handle boolean etc also - new_values, fill_value = maybe_upcast(self.values, fill_value) + + # error: Argument 1 to "maybe_upcast" has incompatible type "Union[ndarray, + # ExtensionArray]"; expected "ndarray" + new_values, fill_value = maybe_upcast( + self.values, fill_value # type: ignore[arg-type] + ) new_values = shift(new_values, periods, axis, fill_value) @@ -1344,7 +1398,9 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]: if transpose: values = values.T - icond, noop = validate_putmask(values, ~cond) + # error: Value of type variable "ArrayLike" of "validate_putmask" cannot be + # "Union[ndarray, ExtensionArray]" + icond, noop = validate_putmask(values, ~cond) # type: ignore[type-var] if is_valid_na_for_dtype(other, self.dtype) and not self.is_object: other = self.fill_value @@ -1362,7 +1418,13 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]: blocks = block.where(orig_other, cond, errors=errors, axis=axis) return self._maybe_downcast(blocks, "infer") - alt = setitem_datetimelike_compat(values, icond.sum(), other) + # error: Argument 1 to "setitem_datetimelike_compat" has incompatible type + # "Union[ndarray, ExtensionArray]"; expected "ndarray" + # error: Argument 2 to "setitem_datetimelike_compat" has incompatible type + # "number[Any]"; expected "int" + alt = setitem_datetimelike_compat( + values, icond.sum(), other # type: ignore[arg-type] + ) if alt is not other: result = values.copy() np.putmask(result, icond, alt) @@ -1449,7 +1511,11 @@ def quantile( assert axis == 1 # only ever called this way assert is_list_like(qs) # caller is responsible for this - result = quantile_compat(self.values, qs, interpolation, axis) + # error: Value of type variable "ArrayLike" of "quantile_compat" cannot be + # "Union[ndarray, ExtensionArray]" + result = quantile_compat( # type: ignore[type-var] + self.values, qs, interpolation, axis + ) return new_block(result, placement=self.mgr_locs, ndim=2) @@ -1489,7 +1555,9 @@ def iget(self, col): elif isinstance(col, slice): if col != slice(None): raise NotImplementedError(col) - return self.values[[loc]] + # error: Invalid index type "List[Any]" for "ExtensionArray"; expected + # type "Union[int, slice, ndarray]" + return self.values[[loc]] # type: ignore[index] return self.values[loc] else: if col != 0: @@ -1615,7 +1683,9 @@ def to_native_types(self, na_rep="nan", quoting=None, **kwargs): values = self.values mask = isna(values) - values = np.asarray(values.astype(object)) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + values = np.asarray(values.astype(object)) # type: ignore[assignment] values[mask] = na_rep # TODO(EA2D): reshape not needed with 2D EAs @@ -1742,7 +1812,10 @@ def where(self, other, cond, errors="raise", axis: int = 0) -> List[Block]: # The default `other` for Series / Frame is np.nan # we want to replace that with the correct NA value # for the type - other = self.dtype.na_value + + # error: Item "dtype[Any]" of "Union[dtype[Any], ExtensionDtype]" has no + # attribute "na_value" + other = self.dtype.na_value # type: ignore[union-attr] if is_sparse(self.values): # TODO(SparseArray.__setitem__): remove this if condition @@ -1832,7 +1905,9 @@ def _can_hold_element(self, element: Any) -> bool: if isinstance(element, (IntegerArray, FloatingArray)): if element._mask.any(): return False - return can_hold_element(self.dtype, element) + # error: Argument 1 to "can_hold_element" has incompatible type + # "Union[dtype[Any], ExtensionDtype]"; expected "dtype[Any]" + return can_hold_element(self.dtype, element) # type: ignore[arg-type] @property def _can_hold_na(self): @@ -2317,5 +2392,7 @@ def ensure_block_shape(values: ArrayLike, ndim: int = 1) -> ArrayLike: # block.shape is incorrect for "2D" ExtensionArrays # We can't, and don't need to, reshape. - values = np.asarray(values).reshape(1, -1) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + values = np.asarray(values).reshape(1, -1) # type: ignore[assignment] return values diff --git a/pandas/core/internals/concat.py b/pandas/core/internals/concat.py index 924d2a77e5da5..64777ef31ac6e 100644 --- a/pandas/core/internals/concat.py +++ b/pandas/core/internals/concat.py @@ -187,7 +187,9 @@ def _get_mgr_concatenation_plan(mgr: BlockManager, indexers: Dict[int, np.ndarra blk = mgr.blocks[0] return [(blk.mgr_locs, JoinUnit(blk, mgr_shape, indexers))] - ax0_indexer = None + # error: Incompatible types in assignment (expression has type "None", variable + # has type "ndarray") + ax0_indexer = None # type: ignore[assignment] blknos = mgr.blknos blklocs = mgr.blklocs @@ -329,7 +331,9 @@ def get_reindexed_values(self, empty_dtype: DtypeObj, upcasted_na) -> ArrayLike: if self.is_valid_na_for(empty_dtype): blk_dtype = getattr(self.block, "dtype", None) - if blk_dtype == np.dtype(object): + # error: Value of type variable "_DTypeScalar" of "dtype" cannot be + # "object" + if blk_dtype == np.dtype(object): # type: ignore[type-var] # we want to avoid filling with np.nan if we are # using None; we already know that we are all # nulls @@ -340,11 +344,17 @@ def get_reindexed_values(self, empty_dtype: DtypeObj, upcasted_na) -> ArrayLike: if is_datetime64tz_dtype(empty_dtype): # TODO(EA2D): special case unneeded with 2D EAs i8values = np.full(self.shape[1], fill_value.value) - return DatetimeArray(i8values, dtype=empty_dtype) + # error: Incompatible return value type (got "DatetimeArray", + # expected "ndarray") + return DatetimeArray( # type: ignore[return-value] + i8values, dtype=empty_dtype + ) elif is_extension_array_dtype(blk_dtype): pass elif is_extension_array_dtype(empty_dtype): - cls = empty_dtype.construct_array_type() + # error: Item "dtype[Any]" of "Union[dtype[Any], ExtensionDtype]" + # has no attribute "construct_array_type" + cls = empty_dtype.construct_array_type() # type: ignore[union-attr] missing_arr = cls._from_sequence([], dtype=empty_dtype) ncols, nrows = self.shape assert ncols == 1, ncols @@ -355,7 +365,15 @@ def get_reindexed_values(self, empty_dtype: DtypeObj, upcasted_na) -> ArrayLike: else: # NB: we should never get here with empty_dtype integer or bool; # if we did, the missing_arr.fill would cast to gibberish - missing_arr = np.empty(self.shape, dtype=empty_dtype) + + # error: Argument "dtype" to "empty" has incompatible type + # "Union[dtype[Any], ExtensionDtype]"; expected "Union[dtype[Any], + # None, type, _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, + # Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, + # Any]]]" + missing_arr = np.empty( + self.shape, dtype=empty_dtype # type: ignore[arg-type] + ) missing_arr.fill(fill_value) return missing_arr @@ -421,14 +439,21 @@ def _concatenate_join_units( elif any(isinstance(t, ExtensionArray) for t in to_concat): # concatting with at least one EA means we are concatting a single column # the non-EA values are 2D arrays with shape (1, n) - to_concat = [t if isinstance(t, ExtensionArray) else t[0, :] for t in to_concat] + + # error: Invalid index type "Tuple[int, slice]" for "ExtensionArray"; expected + # type "Union[int, slice, ndarray]" + to_concat = [ + t if isinstance(t, ExtensionArray) else t[0, :] # type: ignore[index] + for t in to_concat + ] concat_values = concat_compat(to_concat, axis=0, ea_compat_axis=True) concat_values = ensure_block_shape(concat_values, 2) else: concat_values = concat_compat(to_concat, axis=concat_axis) - return concat_values + # error: Incompatible return value type (got "ExtensionArray", expected "ndarray") + return concat_values # type: ignore[return-value] def _dtype_to_na_value(dtype: DtypeObj, has_none_blocks: bool): @@ -436,7 +461,9 @@ def _dtype_to_na_value(dtype: DtypeObj, has_none_blocks: bool): Find the NA value to go with this dtype. """ if is_extension_array_dtype(dtype): - return dtype.na_value + # error: Item "dtype[Any]" of "Union[dtype[Any], ExtensionDtype]" has no + # attribute "na_value" + return dtype.na_value # type: ignore[union-attr] elif dtype.kind in ["m", "M"]: return dtype.type("NaT") elif dtype.kind in ["f", "c"]: diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 0b712267ccf11..0ea8c3eb994a3 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -162,10 +162,17 @@ def rec_array_to_mgr( if isinstance(data, np.ma.MaskedArray): new_arrays = fill_masked_arrays(data, arr_columns) else: - new_arrays = arrays + # error: Incompatible types in assignment (expression has type + # "List[ExtensionArray]", variable has type "List[ndarray]") + new_arrays = arrays # type: ignore[assignment] # create the manager - arrays, arr_columns = reorder_arrays(new_arrays, arr_columns, columns) + + # error: Argument 1 to "reorder_arrays" has incompatible type "List[ndarray]"; + # expected "List[ExtensionArray]" + arrays, arr_columns = reorder_arrays( + new_arrays, arr_columns, columns # type: ignore[arg-type] + ) if columns is None: columns = arr_columns @@ -357,12 +364,22 @@ def dict_to_mgr( if missing.any() and not is_integer_dtype(dtype): if dtype is None or ( not is_extension_array_dtype(dtype) - and np.issubdtype(dtype, np.flexible) + # error: Argument 1 to "issubdtype" has incompatible type + # "Union[dtype, ExtensionDtype]"; expected "Union[dtype, None, + # type, _SupportsDtype, str, Tuple[Any, int], Tuple[Any, + # Union[int, Sequence[int]]], List[Any], _DtypeDict, Tuple[Any, + # Any]]" + and np.issubdtype(dtype, np.flexible) # type: ignore[arg-type] ): # GH#1783 - nan_dtype = np.dtype(object) + + # error: Value of type variable "_DTypeScalar" of "dtype" cannot be + # "object" + nan_dtype = np.dtype(object) # type: ignore[type-var] else: - nan_dtype = dtype + # error: Incompatible types in assignment (expression has type + # "Union[dtype, ExtensionDtype]", variable has type "dtype") + nan_dtype = dtype # type: ignore[assignment] val = construct_1d_arraylike_from_scalar(np.nan, len(index), nan_dtype) arrays.loc[missing] = [val] * missing.sum() @@ -557,7 +574,9 @@ def extract_index(data) -> Index: else: index = ibase.default_index(lengths[0]) - return ensure_index(index) + # error: Value of type variable "AnyArrayLike" of "ensure_index" cannot be + # "Optional[Index]" + return ensure_index(index) # type: ignore[type-var] def reorder_arrays( @@ -660,7 +679,9 @@ def to_arrays( if not len(data): if isinstance(data, np.ndarray): - columns = data.dtype.names + # error: Incompatible types in assignment (expression has type + # "Optional[Tuple[str, ...]]", variable has type "Optional[Index]") + columns = data.dtype.names # type: ignore[assignment] if columns is not None: # i.e. numpy structured array arrays = [data[name] for name in columns] @@ -689,8 +710,17 @@ def to_arrays( data = [tuple(x) for x in data] content = _list_to_arrays(data) - content, columns = _finalize_columns_and_data(content, columns, dtype) - return content, columns + # error: Incompatible types in assignment (expression has type "List[ndarray]", + # variable has type "List[Union[Union[str, int, float, bool], Union[Any, Any, Any, + # Any]]]") + content, columns = _finalize_columns_and_data( # type: ignore[assignment] + content, columns, dtype + ) + # error: Incompatible return value type (got "Tuple[ndarray, Index]", expected + # "Tuple[List[ExtensionArray], Index]") + # error: Incompatible return value type (got "Tuple[ndarray, Index]", expected + # "Tuple[List[ndarray], Index]") + return content, columns # type: ignore[return-value] def _list_to_arrays(data: List[Union[Tuple, List]]) -> np.ndarray: @@ -731,7 +761,11 @@ def _list_of_series_to_arrays( values = extract_array(s, extract_numpy=True) aligned_values.append(algorithms.take_nd(values, indexer)) - content = np.vstack(aligned_values) + # error: Argument 1 to "vstack" has incompatible type "List[ExtensionArray]"; + # expected "Sequence[Union[Union[int, float, complex, str, bytes, generic], + # Sequence[Union[int, float, complex, str, bytes, generic]], + # Sequence[Sequence[Any]], _SupportsArray]]" + content = np.vstack(aligned_values) # type: ignore[arg-type] return content, columns @@ -781,17 +815,34 @@ def _finalize_columns_and_data( """ Ensure we have valid columns, cast object dtypes if possible. """ - content = list(content.T) + # error: Incompatible types in assignment (expression has type "List[Any]", variable + # has type "ndarray") + content = list(content.T) # type: ignore[assignment] try: - columns = _validate_or_indexify_columns(content, columns) + # error: Argument 1 to "_validate_or_indexify_columns" has incompatible type + # "ndarray"; expected "List[Any]" + columns = _validate_or_indexify_columns( + content, columns # type: ignore[arg-type] + ) except AssertionError as err: # GH#26429 do not raise user-facing AssertionError raise ValueError(err) from err if len(content) and content[0].dtype == np.object_: - content = _convert_object_array(content, dtype=dtype) - return content, columns + # error: Incompatible types in assignment (expression has type + # "List[Union[Union[str, int, float, bool], Union[Any, Any, Any, Any]]]", + # variable has type "ndarray") + # error: Argument 1 to "_convert_object_array" has incompatible type "ndarray"; + # expected "List[Union[Union[str, int, float, bool], Union[Any, Any, Any, + # Any]]]" + content = _convert_object_array( # type: ignore[assignment] + content, dtype=dtype # type: ignore[arg-type] + ) + # error: Incompatible return value type (got "Tuple[ndarray, Union[Index, + # List[Union[str, int]]]]", expected "Tuple[List[ndarray], Union[Index, + # List[Union[str, int]]]]") + return content, columns # type: ignore[return-value] def _validate_or_indexify_columns( diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 2daa1ce8dc9a4..476bd836bf216 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -173,8 +173,12 @@ def __init__( # Populate known_consolidate, blknos, and blklocs lazily self._known_consolidated = False - self._blknos = None - self._blklocs = None + # error: Incompatible types in assignment (expression has type "None", + # variable has type "ndarray") + self._blknos = None # type: ignore[assignment] + # error: Incompatible types in assignment (expression has type "None", + # variable has type "ndarray") + self._blklocs = None # type: ignore[assignment] @classmethod def _simple_new(cls, blocks: Tuple[Block, ...], axes: List[Index]): @@ -316,7 +320,11 @@ def arrays(self) -> List[ArrayLike]: Not to be used in actual code, and return value is not the same as the ArrayManager method (list of 1D arrays vs iterator of 2D ndarrays / 1D EAs). """ - return [blk.values for blk in self.blocks] + # error: List comprehension has incompatible type List[Union[ndarray, + # ExtensionArray]]; expected List[ExtensionArray] + # error: List comprehension has incompatible type List[Union[ndarray, + # ExtensionArray]]; expected List[ndarray] + return [blk.values for blk in self.blocks] # type: ignore[misc] def __getstate__(self): block_values = [b.values for b in self.blocks] @@ -889,13 +897,21 @@ def as_array( blk = self.blocks[0] if blk.is_extension: # Avoid implicit conversion of extension blocks to object - arr = blk.values.to_numpy(dtype=dtype, na_value=na_value).reshape( - blk.shape - ) + + # error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no + # attribute "to_numpy" + arr = blk.values.to_numpy( # type: ignore[union-attr] + dtype=dtype, na_value=na_value + ).reshape(blk.shape) else: arr = np.asarray(blk.get_values()) if dtype: - arr = arr.astype(dtype, copy=False) + # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has + # incompatible type "Union[ExtensionDtype, str, dtype[Any], + # Type[object]]"; expected "Union[dtype[Any], None, type, + # _SupportsDType, str, Union[Tuple[Any, int], Tuple[Any, Union[int, + # Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, Any]]]" + arr = arr.astype(dtype, copy=False) # type: ignore[arg-type] else: arr = self._interleave(dtype=dtype, na_value=na_value) # The underlying data was copied within _interleave @@ -928,7 +944,12 @@ def _interleave( elif is_dtype_equal(dtype, str): dtype = "object" - result = np.empty(self.shape, dtype=dtype) + # error: Argument "dtype" to "empty" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected + # "Union[dtype[Any], None, type, _SupportsDType, str, Union[Tuple[Any, int], + # Tuple[Any, Union[int, Sequence[int]]], List[Any], _DTypeDict, Tuple[Any, + # Any]]]" + result = np.empty(self.shape, dtype=dtype) # type: ignore[arg-type] itemmask = np.zeros(self.shape[0]) @@ -936,9 +957,17 @@ def _interleave( rl = blk.mgr_locs if blk.is_extension: # Avoid implicit conversion of extension blocks to object - arr = blk.values.to_numpy(dtype=dtype, na_value=na_value) + + # error: Item "ndarray" of "Union[ndarray, ExtensionArray]" has no + # attribute "to_numpy" + arr = blk.values.to_numpy( # type: ignore[union-attr] + dtype=dtype, na_value=na_value + ) else: - arr = blk.get_values(dtype) + # error: Argument 1 to "get_values" of "Block" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected + # "Union[dtype[Any], ExtensionDtype, None]" + arr = blk.get_values(dtype) # type: ignore[arg-type] result[rl.indexer] = arr itemmask[rl.indexer] = 1 @@ -989,7 +1018,12 @@ def fast_xs(self, loc: int) -> ArrayLike: # we'll eventually construct an ExtensionArray. result = np.empty(n, dtype=object) else: - result = np.empty(n, dtype=dtype) + # error: Argument "dtype" to "empty" has incompatible type + # "Union[dtype, ExtensionDtype, None]"; expected "Union[dtype, + # None, type, _SupportsDtype, str, Tuple[Any, int], Tuple[Any, + # Union[int, Sequence[int]]], List[Any], _DtypeDict, Tuple[Any, + # Any]]" + result = np.empty(n, dtype=dtype) # type: ignore[arg-type] for blk in self.blocks: # Such assignment may incorrectly coerce NaT to None @@ -1000,7 +1034,9 @@ def fast_xs(self, loc: int) -> ArrayLike: if isinstance(dtype, ExtensionDtype): result = dtype.construct_array_type()._from_sequence(result, dtype=dtype) - return result + # error: Incompatible return value type (got "ndarray", expected + # "ExtensionArray") + return result # type: ignore[return-value] def consolidate(self) -> BlockManager: """ @@ -1123,7 +1159,11 @@ def value_getitem(placement): # We have 6 tests where loc is _not_ an int. # In this case, get_blkno_placements will yield only one tuple, # containing (self._blknos[loc], BlockPlacement(slice(0, 1, 1))) - loc = [loc] + + # error: Incompatible types in assignment (expression has type + # "List[Union[int, slice, ndarray]]", variable has type "Union[int, + # slice, ndarray]") + loc = [loc] # type: ignore[assignment] # Accessing public blknos ensures the public versions are initialized blknos = self.blknos[loc] @@ -1461,7 +1501,11 @@ def _make_na_block(self, placement, fill_value=None): block_shape[0] = len(placement) dtype, fill_value = infer_dtype_from_scalar(fill_value) - block_values = np.empty(block_shape, dtype=dtype) + # error: Argument "dtype" to "empty" has incompatible type "Union[dtype, + # ExtensionDtype]"; expected "Union[dtype, None, type, _SupportsDtype, str, + # Tuple[Any, int], Tuple[Any, Union[int, Sequence[int]]], List[Any], _DtypeDict, + # Tuple[Any, Any]]" + block_values = np.empty(block_shape, dtype=dtype) # type: ignore[arg-type] block_values.fill(fill_value) return new_block(block_values, placement=placement, ndim=block_values.ndim) @@ -1503,7 +1547,9 @@ def _equal_values(self: T, other: T) -> bool: return False left = self.blocks[0].values right = other.blocks[0].values - return array_equals(left, right) + # error: Value of type variable "ArrayLike" of "array_equals" cannot be + # "Union[ndarray, ExtensionArray]" + return array_equals(left, right) # type: ignore[type-var] return blockwise_all(self, other, array_equals) @@ -1884,7 +1930,12 @@ def _multi_blockify(tuples, dtype: Optional[Dtype] = None): new_blocks = [] for dtype, tup_block in grouper: - values, placement = _stack_arrays(list(tup_block), dtype) + # error: Argument 2 to "_stack_arrays" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[str], Type[float], Type[int], + # Type[complex], Type[bool], Type[object], None]"; expected "dtype[Any]" + values, placement = _stack_arrays( + list(tup_block), dtype # type: ignore[arg-type] + ) block = new_block(values, placement=placement, ndim=2) new_blocks.append(block) @@ -1958,7 +2009,11 @@ def _merge_blocks( # TODO: optimization potential in case all mgrs contain slices and # combination of those slices is a slice, too. new_mgr_locs = np.concatenate([b.mgr_locs.as_array for b in blocks]) - new_values = np.vstack([b.values for b in blocks]) + # error: List comprehension has incompatible type List[Union[ndarray, + # ExtensionArray]]; expected List[Union[complex, generic, Sequence[Union[int, + # float, complex, str, bytes, generic]], Sequence[Sequence[Any]], + # _SupportsArray]] + new_values = np.vstack([b.values for b in blocks]) # type: ignore[misc] argsort = np.argsort(new_mgr_locs) new_values = new_values[argsort] diff --git a/pandas/core/internals/ops.py b/pandas/core/internals/ops.py index dbd309f0836a5..103092ba37b70 100644 --- a/pandas/core/internals/ops.py +++ b/pandas/core/internals/ops.py @@ -108,21 +108,35 @@ def _get_same_shape_values( # TODO(EA2D): with 2D EAs only this first clause would be needed if not (left_ea or right_ea): - lvals = lvals[rblk.mgr_locs.indexer, :] + # error: Invalid index type "Tuple[Any, slice]" for "Union[ndarray, + # ExtensionArray]"; expected type "Union[int, slice, ndarray]" + lvals = lvals[rblk.mgr_locs.indexer, :] # type: ignore[index] assert lvals.shape == rvals.shape, (lvals.shape, rvals.shape) elif left_ea and right_ea: assert lvals.shape == rvals.shape, (lvals.shape, rvals.shape) elif right_ea: # lvals are 2D, rvals are 1D - lvals = lvals[rblk.mgr_locs.indexer, :] + + # error: Invalid index type "Tuple[Any, slice]" for "Union[ndarray, + # ExtensionArray]"; expected type "Union[int, slice, ndarray]" + lvals = lvals[rblk.mgr_locs.indexer, :] # type: ignore[index] assert lvals.shape[0] == 1, lvals.shape - lvals = lvals[0, :] + # error: Invalid index type "Tuple[int, slice]" for "Union[Any, + # ExtensionArray]"; expected type "Union[int, slice, ndarray]" + lvals = lvals[0, :] # type: ignore[index] else: # lvals are 1D, rvals are 2D assert rvals.shape[0] == 1, rvals.shape - rvals = rvals[0, :] - - return lvals, rvals + # error: Invalid index type "Tuple[int, slice]" for "Union[ndarray, + # ExtensionArray]"; expected type "Union[int, slice, ndarray]" + rvals = rvals[0, :] # type: ignore[index] + + # error: Incompatible return value type (got "Tuple[Union[ndarray, ExtensionArray], + # Union[ndarray, ExtensionArray]]", expected "Tuple[ExtensionArray, + # ExtensionArray]") + # error: Incompatible return value type (got "Tuple[Union[ndarray, ExtensionArray], + # Union[ndarray, ExtensionArray]]", expected "Tuple[ndarray, ndarray]") + return lvals, rvals # type: ignore[return-value] def blockwise_all(left: BlockManager, right: BlockManager, op) -> bool: diff --git a/pandas/core/missing.py b/pandas/core/missing.py index dc42a175409c2..48b2084319292 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -75,7 +75,11 @@ def mask_missing(arr: ArrayLike, values_to_mask) -> np.ndarray: # known to be holdable by arr. # When called from Series._single_replace, values_to_mask is tuple or list dtype, values_to_mask = infer_dtype_from(values_to_mask) - values_to_mask = np.array(values_to_mask, dtype=dtype) + # error: Argument "dtype" to "array" has incompatible type "Union[dtype[Any], + # ExtensionDtype]"; expected "Union[dtype[Any], None, type, _SupportsDType, str, + # Union[Tuple[Any, int], Tuple[Any, Union[int, Sequence[int]]], List[Any], + # _DTypeDict, Tuple[Any, Any]]]" + values_to_mask = np.array(values_to_mask, dtype=dtype) # type: ignore[arg-type] na_mask = isna(values_to_mask) nonna = values_to_mask[~na_mask] @@ -305,7 +309,12 @@ def interpolate_1d( if method in NP_METHODS: # np.interp requires sorted X values, #21037 - indexer = np.argsort(inds[valid]) + + # error: Argument 1 to "argsort" has incompatible type "Union[ExtensionArray, + # Any]"; expected "Union[Union[int, float, complex, str, bytes, generic], + # Sequence[Union[int, float, complex, str, bytes, generic]], + # Sequence[Sequence[Any]], _SupportsArray]" + indexer = np.argsort(inds[valid]) # type: ignore[arg-type] result[invalid] = np.interp( inds[invalid], inds[valid][indexer], yvalues[valid][indexer] ) @@ -708,7 +717,9 @@ def _pad_1d( ) -> tuple[np.ndarray, np.ndarray]: mask = _fillna_prep(values, mask) algos.pad_inplace(values, mask, limit=limit) - return values, mask + # error: Incompatible return value type (got "Tuple[ndarray, Optional[ndarray]]", + # expected "Tuple[ndarray, ndarray]") + return values, mask # type: ignore[return-value] @_datetimelike_compat @@ -719,7 +730,9 @@ def _backfill_1d( ) -> tuple[np.ndarray, np.ndarray]: mask = _fillna_prep(values, mask) algos.backfill_inplace(values, mask, limit=limit) - return values, mask + # error: Incompatible return value type (got "Tuple[ndarray, Optional[ndarray]]", + # expected "Tuple[ndarray, ndarray]") + return values, mask # type: ignore[return-value] @_datetimelike_compat @@ -839,4 +852,7 @@ def _rolling_window(a: np.ndarray, window: int): # https://stackoverflow.com/a/6811241 shape = a.shape[:-1] + (a.shape[-1] - window + 1, window) strides = a.strides + (a.strides[-1],) - return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) + # error: Module has no attribute "stride_tricks" + return np.lib.stride_tricks.as_strided( # type: ignore[attr-defined] + a, shape=shape, strides=strides + ) diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 2592492f1c14c..f17569d114389 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -411,7 +411,11 @@ def new_func( if datetimelike: result = _wrap_results(result, orig_values.dtype, fill_value=iNaT) if not skipna: - result = _mask_datetimelike_result(result, axis, mask, orig_values) + # error: Argument 3 to "_mask_datetimelike_result" has incompatible type + # "Optional[ndarray]"; expected "ndarray" + result = _mask_datetimelike_result( + result, axis, mask, orig_values # type: ignore[arg-type] + ) return result @@ -486,7 +490,9 @@ def nanany( False """ values, _, _, _, _ = _get_values(values, skipna, fill_value=False, mask=mask) - return values.any(axis) + # error: Incompatible return value type (got "Union[bool_, ndarray]", expected + # "bool") + return values.any(axis) # type: ignore[return-value] def nanall( @@ -524,7 +530,9 @@ def nanall( False """ values, _, _, _, _ = _get_values(values, skipna, fill_value=True, mask=mask) - return values.all(axis) + # error: Incompatible return value type (got "Union[bool_, ndarray]", expected + # "bool") + return values.all(axis) # type: ignore[return-value] @disallow("M8") @@ -567,12 +575,22 @@ def nansum( if is_float_dtype(dtype): dtype_sum = dtype elif is_timedelta64_dtype(dtype): - dtype_sum = np.float64 + # error: Incompatible types in assignment (expression has type + # "Type[float64]", variable has type "dtype") + dtype_sum = np.float64 # type: ignore[assignment] the_sum = values.sum(axis, dtype=dtype_sum) - the_sum = _maybe_null_out(the_sum, axis, mask, values.shape, min_count=min_count) + # error: Incompatible types in assignment (expression has type "float", variable has + # type "Union[number, ndarray]") + # error: Argument 1 to "_maybe_null_out" has incompatible type "Union[number, + # ndarray]"; expected "ndarray" + the_sum = _maybe_null_out( # type: ignore[assignment] + the_sum, axis, mask, values.shape, min_count=min_count # type: ignore[arg-type] + ) - return the_sum + # error: Incompatible return value type (got "Union[number, ndarray]", expected + # "float") + return the_sum # type: ignore[return-value] def _mask_datetimelike_result( @@ -634,12 +652,18 @@ def nanmean( # not using needs_i8_conversion because that includes period if dtype.kind in ["m", "M"]: - dtype_sum = np.float64 + # error: Incompatible types in assignment (expression has type "Type[float64]", + # variable has type "dtype[Any]") + dtype_sum = np.float64 # type: ignore[assignment] elif is_integer_dtype(dtype): - dtype_sum = np.float64 + # error: Incompatible types in assignment (expression has type "Type[float64]", + # variable has type "dtype[Any]") + dtype_sum = np.float64 # type: ignore[assignment] elif is_float_dtype(dtype): dtype_sum = dtype - dtype_count = dtype + # error: Incompatible types in assignment (expression has type "dtype[Any]", + # variable has type "Type[float64]") + dtype_count = dtype # type: ignore[assignment] count = _get_counts(values.shape, mask, axis, dtype=dtype_count) the_sum = _ensure_numeric(values.sum(axis, dtype=dtype_sum)) @@ -791,7 +815,9 @@ def _get_counts_nanvar( """ dtype = get_dtype(dtype) count = _get_counts(value_counts, mask, axis, dtype=dtype) - d = count - dtype.type(ddof) + # error: Unsupported operand types for - ("int" and "generic") + # error: Unsupported operand types for - ("float" and "generic") + d = count - dtype.type(ddof) # type: ignore[operator] # always return NaN, never inf if is_scalar(count): @@ -799,11 +825,16 @@ def _get_counts_nanvar( count = np.nan d = np.nan else: - mask2: np.ndarray = count <= ddof + # error: Incompatible types in assignment (expression has type + # "Union[bool, Any]", variable has type "ndarray") + mask2: np.ndarray = count <= ddof # type: ignore[assignment] if mask2.any(): np.putmask(d, mask2, np.nan) np.putmask(count, mask2, np.nan) - return count, d + # error: Incompatible return value type (got "Tuple[Union[int, float, + # ndarray], Any]", expected "Tuple[Union[int, ndarray], Union[int, + # ndarray]]") + return count, d # type: ignore[return-value] @bottleneck_switch(ddof=1) @@ -958,7 +989,11 @@ def nansem( if not is_float_dtype(values.dtype): values = values.astype("f8") - count, _ = _get_counts_nanvar(values.shape, mask, axis, ddof, values.dtype) + # error: Argument 1 to "_get_counts_nanvar" has incompatible type + # "Tuple[int, ...]"; expected "Tuple[int]" + count, _ = _get_counts_nanvar( + values.shape, mask, axis, ddof, values.dtype # type: ignore[arg-type] + ) var = nanvar(values, axis=axis, skipna=skipna, ddof=ddof) return np.sqrt(var) / np.sqrt(count) @@ -1038,7 +1073,8 @@ def nanargmax( array([2, 2, 1, 1], dtype=int64) """ values, mask, _, _, _ = _get_values(values, True, fill_value_typ="-inf", mask=mask) - result = values.argmax(axis) + # error: Need type annotation for 'result' + result = values.argmax(axis) # type: ignore[var-annotated] result = _maybe_arg_null_out(result, axis, mask, skipna) return result @@ -1083,7 +1119,8 @@ def nanargmin( array([0, 0, 1, 1], dtype=int64) """ values, mask, _, _, _ = _get_values(values, True, fill_value_typ="+inf", mask=mask) - result = values.argmin(axis) + # error: Need type annotation for 'result' + result = values.argmin(axis) # type: ignore[var-annotated] result = _maybe_arg_null_out(result, axis, mask, skipna) return result @@ -1304,7 +1341,13 @@ def nanprod( values = values.copy() values[mask] = 1 result = values.prod(axis) - return _maybe_null_out(result, axis, mask, values.shape, min_count=min_count) + # error: Argument 1 to "_maybe_null_out" has incompatible type "Union[number, + # ndarray]"; expected "ndarray" + # error: Incompatible return value type (got "Union[ndarray, float]", expected + # "float") + return _maybe_null_out( # type: ignore[return-value] + result, axis, mask, values.shape, min_count=min_count # type: ignore[arg-type] + ) def _maybe_arg_null_out( @@ -1317,10 +1360,14 @@ def _maybe_arg_null_out( if axis is None or not getattr(result, "ndim", False): if skipna: if mask.all(): - result = -1 + # error: Incompatible types in assignment (expression has type + # "int", variable has type "ndarray") + result = -1 # type: ignore[assignment] else: if mask.any(): - result = -1 + # error: Incompatible types in assignment (expression has type + # "int", variable has type "ndarray") + result = -1 # type: ignore[assignment] else: if skipna: na_mask = mask.all(axis) @@ -1361,7 +1408,9 @@ def _get_counts( n = mask.size - mask.sum() else: n = np.prod(values_shape) - return dtype.type(n) + # error: Incompatible return value type (got "Union[Any, generic]", + # expected "Union[int, float, ndarray]") + return dtype.type(n) # type: ignore[return-value] if mask is not None: count = mask.shape[axis] - mask.sum(axis) @@ -1369,11 +1418,23 @@ def _get_counts( count = values_shape[axis] if is_scalar(count): - return dtype.type(count) + # error: Incompatible return value type (got "Union[Any, generic]", + # expected "Union[int, float, ndarray]") + return dtype.type(count) # type: ignore[return-value] try: - return count.astype(dtype) + # error: Incompatible return value type (got "Union[ndarray, generic]", expected + # "Union[int, float, ndarray]") + # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has incompatible type + # "Union[ExtensionDtype, dtype]"; expected "Union[dtype, None, type, + # _SupportsDtype, str, Tuple[Any, int], Tuple[Any, Union[int, Sequence[int]]], + # List[Any], _DtypeDict, Tuple[Any, Any]]" + return count.astype(dtype) # type: ignore[return-value,arg-type] except AttributeError: - return np.array(count, dtype=dtype) + # error: Argument "dtype" to "array" has incompatible type + # "Union[ExtensionDtype, dtype]"; expected "Union[dtype, None, type, + # _SupportsDtype, str, Tuple[Any, int], Tuple[Any, Union[int, + # Sequence[int]]], List[Any], _DtypeDict, Tuple[Any, Any]]" + return np.array(count, dtype=dtype) # type: ignore[arg-type] def _maybe_null_out( @@ -1403,7 +1464,9 @@ def _maybe_null_out( result[null_mask] = None elif result is not NaT: if check_below_min_count(shape, mask, min_count): - result = np.nan + # error: Incompatible types in assignment (expression has type + # "float", variable has type "ndarray") + result = np.nan # type: ignore[assignment] return result diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py index 10807dffb026b..9153eb25032e7 100644 --- a/pandas/core/ops/array_ops.py +++ b/pandas/core/ops/array_ops.py @@ -88,7 +88,11 @@ def _masked_arith_op(x: np.ndarray, y, op): 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) + # error: Argument "dtype" to "empty" has incompatible type + # "Union[dtype, ExtensionDtype]"; expected "Union[dtype, None, type, + # _SupportsDtype, str, Tuple[Any, int], Tuple[Any, Union[int, + # Sequence[int]]], List[Any], _DtypeDict, Tuple[Any, Any]]" + result = np.empty(x.size, dtype=dtype) # type: ignore[arg-type] if len(x) != len(y): raise ValueError(x.shape, y.shape) diff --git a/pandas/core/ops/mask_ops.py b/pandas/core/ops/mask_ops.py index 501bc0159e641..968833cd1ae44 100644 --- a/pandas/core/ops/mask_ops.py +++ b/pandas/core/ops/mask_ops.py @@ -109,7 +109,9 @@ def kleene_xor( if right is libmissing.NA: result = np.zeros_like(left) else: - result = left ^ right + # error: Incompatible types in assignment (expression has type + # "Union[bool, Any]", variable has type "ndarray") + result = left ^ right # type: ignore[assignment] if right_mask is None: if right is libmissing.NA: diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 80a44e8fda39b..09249eba9c3f5 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -143,10 +143,17 @@ def melt( mcolumns = id_vars + var_name + [value_name] - mdata[value_name] = frame._values.ravel("F") + # error: Incompatible types in assignment (expression has type "ndarray", + # target has type "Series") + mdata[value_name] = frame._values.ravel("F") # type: ignore[assignment] for i, col in enumerate(var_name): # asanyarray will keep the columns as an Index - mdata[col] = np.asanyarray(frame.columns._get_level_values(i)).repeat(N) + + # error: Incompatible types in assignment (expression has type "ndarray", target + # has type "Series") + mdata[col] = np.asanyarray( # type: ignore[assignment] + frame.columns._get_level_values(i) + ).repeat(N) result = frame._constructor(mdata, columns=mcolumns) diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 9291dcf552786..a048217d6b1f0 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -2064,8 +2064,13 @@ def _factorize_keys( if is_datetime64tz_dtype(lk.dtype) and is_datetime64tz_dtype(rk.dtype): # Extract the ndarray (UTC-localized) values # Note: we dont need the dtypes to match, as these can still be compared - lk = cast("DatetimeArray", lk)._ndarray - rk = cast("DatetimeArray", rk)._ndarray + + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + lk = cast("DatetimeArray", lk)._ndarray # type: ignore[assignment] + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + rk = cast("DatetimeArray", rk)._ndarray # type: ignore[assignment] elif ( is_categorical_dtype(lk.dtype) @@ -2075,14 +2080,27 @@ def _factorize_keys( assert isinstance(lk, Categorical) assert isinstance(rk, Categorical) # Cast rk to encoding so we can compare codes with lk - rk = lk._encode_with_my_categories(rk) - lk = ensure_int64(lk.codes) - rk = ensure_int64(rk.codes) + # error: <nothing> has no attribute "_encode_with_my_categories" + rk = lk._encode_with_my_categories(rk) # type: ignore[attr-defined] + + # error: <nothing> has no attribute "codes" + lk = ensure_int64(lk.codes) # type: ignore[attr-defined] + # error: "ndarray" has no attribute "codes" + rk = ensure_int64(rk.codes) # type: ignore[attr-defined] elif is_extension_array_dtype(lk.dtype) and is_dtype_equal(lk.dtype, rk.dtype): - lk, _ = lk._values_for_factorize() - rk, _ = rk._values_for_factorize() + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + # error: Item "ndarray" of "Union[Any, ndarray]" has no attribute + # "_values_for_factorize" + lk, _ = lk._values_for_factorize() # type: ignore[union-attr,assignment] + + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "ExtensionArray") + # error: Item "ndarray" of "Union[Any, ndarray]" has no attribute + # "_values_for_factorize" + rk, _ = rk._values_for_factorize() # type: ignore[union-attr,assignment] if is_integer_dtype(lk.dtype) and is_integer_dtype(rk.dtype): # GH#23917 TODO: needs tests for case where lk is integer-dtype diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index d0026d7acbe65..0c0b37791f883 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -486,7 +486,11 @@ def pivot( cols = [] append = index is None - indexed = data.set_index(cols + columns, append=append) + # error: Unsupported operand types for + ("List[Any]" and "ExtensionArray") + # error: Unsupported left operand type for + ("ExtensionArray") + indexed = data.set_index( + cols + columns, append=append # type: ignore[operator] + ) else: if index is None: index = [Series(data.index, name=data.index.name)] diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index f0a2ef0cb1869..13119b9997002 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -169,7 +169,9 @@ def _make_selectors(self): self.full_shape = ngroups, stride selector = self.sorted_labels[-1] + stride * comp_index + self.lift - mask = np.zeros(np.prod(self.full_shape), dtype=bool) + # error: Argument 1 to "zeros" has incompatible type "number"; expected + # "Union[int, Sequence[int]]" + mask = np.zeros(np.prod(self.full_shape), dtype=bool) # type: ignore[arg-type] mask.put(selector, True) if mask.sum() < len(self.index): @@ -952,7 +954,9 @@ def _get_dummies_1d( if dtype is None: dtype = np.uint8 - dtype = np.dtype(dtype) + # error: Argument 1 to "dtype" has incompatible type "Union[ExtensionDtype, str, + # dtype[Any], Type[object]]"; expected "Type[Any]" + dtype = np.dtype(dtype) # type: ignore[arg-type] if is_object_dtype(dtype): raise ValueError("dtype=object is not a valid dtype for get_dummies") diff --git a/pandas/core/series.py b/pandas/core/series.py index 468c3baca92c3..b92ada9537bd4 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -353,7 +353,9 @@ def __init__( copy = False elif isinstance(data, np.ndarray): - if len(data.dtype): + # error: Argument 1 to "len" has incompatible type "dtype"; expected + # "Sized" + if len(data.dtype): # type: ignore[arg-type] # GH#13296 we are dealing with a compound dtype, which # should be treated as 2D raise ValueError( @@ -402,7 +404,12 @@ def __init__( elif copy: data = data.copy() else: - data = sanitize_array(data, index, dtype, copy) + # error: Argument 3 to "sanitize_array" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[object], None]"; expected + # "Union[dtype[Any], ExtensionDtype, None]" + data = sanitize_array( + data, index, dtype, copy # type: ignore[arg-type] + ) manager = get_option("mode.data_manager") if manager == "block": @@ -453,7 +460,10 @@ def _init_dict(self, data, index=None, dtype: Optional[Dtype] = None): # Input is now list-like, so rely on "standard" construction: # TODO: passing np.float64 to not break anything yet. See GH-17261 - s = create_series_with_explicit_dtype( + + # error: Value of type variable "ArrayLike" of + # "create_series_with_explicit_dtype" cannot be "Tuple[Any, ...]" + s = create_series_with_explicit_dtype( # type: ignore[type-var] values, index=keys, dtype=dtype, dtype_if_empty=np.float64 ) @@ -1053,7 +1063,9 @@ def __setitem__(self, key, value): def _set_with_engine(self, key, value): # fails with AttributeError for IntervalIndex loc = self.index._engine.get_loc(key) - validate_numeric_casting(self.dtype, value) + # error: Argument 1 to "validate_numeric_casting" has incompatible type + # "Union[dtype, ExtensionDtype]"; expected "dtype" + validate_numeric_casting(self.dtype, value) # type: ignore[arg-type] self._values[loc] = value def _set_with(self, key, value): @@ -2005,7 +2017,9 @@ def drop_duplicates(self, keep="first", inplace=False) -> Optional[Series]: else: return result - def duplicated(self, keep="first") -> Series: + # error: Return type "Series" of "duplicated" incompatible with return type + # "ndarray" in supertype "IndexOpsMixin" + def duplicated(self, keep="first") -> Series: # type: ignore[override] """ Indicate duplicate Series values. @@ -2988,7 +3002,12 @@ def combine(self, other, func, fill_value=None) -> Series: # TODO: can we do this for only SparseDtype? # The function can return something of any type, so check # if the type is compatible with the calling EA. - new_values = maybe_cast_to_extension_array(type(self._values), new_values) + + # error: Value of type variable "ArrayLike" of + # "maybe_cast_to_extension_array" cannot be "List[Any]" + new_values = maybe_cast_to_extension_array( + type(self._values), new_values # type: ignore[type-var] + ) return self._constructor(new_values, index=new_index, name=new_name) def combine_first(self, other) -> Series: diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index 973fed2c1436f..ba81866602361 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -43,6 +43,7 @@ _INT64_MAX = np.iinfo(np.int64).max +# error: Function "numpy.array" is not valid as a type def get_indexer_indexer( target: Index, level: Union[str, int, List[str], List[int]], @@ -51,7 +52,7 @@ def get_indexer_indexer( na_position: str, sort_remaining: bool, key: IndexKeyFunc, -) -> Optional[np.array]: +) -> Optional[np.array]: # type: ignore[valid-type] """ Helper method that return the indexer according to input parameters for the sort_index method of DataFrame and Series. @@ -584,11 +585,16 @@ def get_group_index_sorter( df.groupby(key)[col].transform('first') """ if ngroups is None: - ngroups = 1 + group_index.max() + # error: Incompatible types in assignment (expression has type "number[Any]", + # variable has type "Optional[int]") + ngroups = 1 + group_index.max() # type: ignore[assignment] count = len(group_index) alpha = 0.0 # taking complexities literally; there may be beta = 1.0 # some room for fine-tuning these parameters - do_groupsort = count > 0 and ((alpha + beta * ngroups) < (count * np.log(count))) + # error: Unsupported operand types for * ("float" and "None") + do_groupsort = count > 0 and ( + (alpha + beta * ngroups) < (count * np.log(count)) # type: ignore[operator] + ) if do_groupsort: sorter, _ = algos.groupsort_indexer(ensure_int64(group_index), ngroups) return ensure_platform_int(sorter) diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 32a99c0a020b2..3508624e51a9d 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -604,15 +604,27 @@ def cat(self, others=None, sep=None, na_rep=None, join="left"): if isinstance(self._orig, ABCIndex): # add dtype for case that result is all-NA - result = Index(result, dtype=object, name=self._orig.name) + + # error: Incompatible types in assignment (expression has type + # "Index", variable has type "ndarray") + result = Index( # type: ignore[assignment] + result, dtype=object, name=self._orig.name + ) else: # Series if is_categorical_dtype(self._orig.dtype): # We need to infer the new categories. dtype = None else: dtype = self._orig.dtype - result = Series(result, dtype=dtype, index=data.index, name=self._orig.name) - result = result.__finalize__(self._orig, method="str_cat") + # error: Incompatible types in assignment (expression has type + # "Series", variable has type "ndarray") + result = Series( # type: ignore[assignment] + result, dtype=dtype, index=data.index, name=self._orig.name + ) + # error: "ndarray" has no attribute "__finalize__" + result = result.__finalize__( # type: ignore[attr-defined] + self._orig, method="str_cat" + ) return result _shared_docs[ @@ -3030,10 +3042,16 @@ def _str_extract_noexpand(arr, pat, flags=0): names = dict(zip(regex.groupindex.values(), regex.groupindex.keys())) columns = [names.get(1 + i, i) for i in range(regex.groups)] if arr.size == 0: - result = DataFrame(columns=columns, dtype=object) + # error: Incompatible types in assignment (expression has type + # "DataFrame", variable has type "ndarray") + result = DataFrame( # type: ignore[assignment] + columns=columns, dtype=object + ) else: dtype = _result_dtype(arr) - result = DataFrame( + # error: Incompatible types in assignment (expression has type + # "DataFrame", variable has type "ndarray") + result = DataFrame( # type:ignore[assignment] [groups_or_na(val) for val in arr], columns=columns, index=arr.index, diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py index 0a4543057c386..edf32bade0657 100644 --- a/pandas/core/strings/object_array.py +++ b/pandas/core/strings/object_array.py @@ -63,10 +63,14 @@ def _str_map(self, f, na_value=None, dtype: Optional[Dtype] = None): na_value = self._str_na_value if not len(arr): - return np.ndarray(0, dtype=dtype) + # error: Argument 1 to "ndarray" has incompatible type "int"; + # expected "Sequence[int]" + return np.ndarray(0, dtype=dtype) # type: ignore[arg-type] if not isinstance(arr, np.ndarray): - arr = np.asarray(arr, dtype=object) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ObjectStringArrayMixin") + arr = np.asarray(arr, dtype=object) # type: ignore[assignment] mask = isna(arr) convert = not np.all(mask) try: diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index d58b5e5ffa83d..f7bb3083b91a9 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -245,7 +245,9 @@ def _convert_and_box_cache( from pandas import Series result = Series(arg).map(cache_array) - return _box_as_indexlike(result, utc=None, name=name) + # error: Value of type variable "ArrayLike" of "_box_as_indexlike" cannot + # be "Series" + return _box_as_indexlike(result, utc=None, name=name) # type: ignore[type-var] def _return_parsed_timezone_results(result: np.ndarray, timezones, tz, name) -> Index: @@ -362,7 +364,9 @@ def _convert_listlike_datetimes( result = np.array(["NaT"], dtype="datetime64[ns]").repeat(len(arg)) return DatetimeIndex(result, name=name) elif errors == "ignore": - result = Index(arg, name=name) + # error: Incompatible types in assignment (expression has type + # "Index", variable has type "ExtensionArray") + result = Index(arg, name=name) # type: ignore[assignment] return result raise @@ -382,10 +386,14 @@ def _convert_listlike_datetimes( require_iso8601 = not infer_datetime_format format = None - result = None + # error: Incompatible types in assignment (expression has type "None", variable has + # type "ExtensionArray") + result = None # type: ignore[assignment] if format is not None: - result = _to_datetime_with_format( + # error: Incompatible types in assignment (expression has type + # "Optional[Index]", variable has type "ndarray") + result = _to_datetime_with_format( # type: ignore[assignment] arg, orig_arg, name, tz, format, exact, errors, infer_datetime_format ) if result is not None: @@ -494,7 +502,9 @@ def _to_datetime_with_format( # fallback if result is None: - result = _array_strptime_with_fallback( + # error: Incompatible types in assignment (expression has type + # "Optional[Index]", variable has type "Optional[ndarray]") + result = _array_strptime_with_fallback( # type: ignore[assignment] arg, name, tz, fmt, exact, errors, infer_datetime_format ) if result is not None: @@ -510,7 +520,9 @@ def _to_datetime_with_format( except (ValueError, TypeError): raise e - return result + # error: Incompatible return value type (got "Optional[ndarray]", expected + # "Optional[Index]") + return result # type: ignore[return-value] def _to_datetime_with_unit(arg, unit, name, tz, errors: Optional[str]) -> Index: @@ -529,12 +541,18 @@ def _to_datetime_with_unit(arg, unit, name, tz, errors: Optional[str]) -> Index: if errors == "ignore": # Index constructor _may_ infer to DatetimeIndex - result = Index(result, name=name) + + # error: Incompatible types in assignment (expression has type "Index", variable + # has type "ExtensionArray") + result = Index(result, name=name) # type: ignore[assignment] else: - result = DatetimeIndex(result, name=name) + # error: Incompatible types in assignment (expression has type "DatetimeIndex", + # variable has type "ExtensionArray") + result = DatetimeIndex(result, name=name) # type: ignore[assignment] if not isinstance(result, DatetimeIndex): - return result + # error: Incompatible return value type (got "ExtensionArray", expected "Index") + return result # type: ignore[return-value] # GH#23758: We may still need to localize the result with tz # GH#25546: Apply tz_parsed first (from arg), then tz (from caller) @@ -1063,7 +1081,9 @@ def calc_with_mask(carg, mask): # string with NaN-like try: - mask = ~algorithms.isin(arg, list(nat_strings)) + # error: Value of type variable "AnyArrayLike" of "isin" cannot be + # "Iterable[Any]" + mask = ~algorithms.isin(arg, list(nat_strings)) # type: ignore[type-var] return calc_with_mask(arg, mask) except (ValueError, OverflowError, TypeError): pass diff --git a/pandas/core/tools/numeric.py b/pandas/core/tools/numeric.py index 1032edcb22b46..31ab78e59a556 100644 --- a/pandas/core/tools/numeric.py +++ b/pandas/core/tools/numeric.py @@ -168,7 +168,9 @@ def to_numeric(arg, errors="raise", downcast=None): mask = values._mask values = values._data[~mask] else: - mask = None + # error: Incompatible types in assignment (expression has type "None", variable + # has type "ndarray") + mask = None # type: ignore[assignment] values_dtype = getattr(values, "dtype", None) if is_numeric_dtype(values_dtype): diff --git a/pandas/core/tools/timedeltas.py b/pandas/core/tools/timedeltas.py index a335146265523..a8378e91f9375 100644 --- a/pandas/core/tools/timedeltas.py +++ b/pandas/core/tools/timedeltas.py @@ -181,5 +181,7 @@ def _convert_listlike(arg, unit=None, errors="raise", name=None): from pandas import TimedeltaIndex - value = TimedeltaIndex(value, unit="ns", name=name) + # error: Incompatible types in assignment (expression has type "TimedeltaIndex", + # variable has type "ndarray") + value = TimedeltaIndex(value, unit="ns", name=name) # type: ignore[assignment] return value diff --git a/pandas/core/util/hashing.py b/pandas/core/util/hashing.py index 9d488bb13b0f1..7d314d6a6fa1a 100644 --- a/pandas/core/util/hashing.py +++ b/pandas/core/util/hashing.py @@ -116,10 +116,14 @@ def hash_pandas_object( return Series(hash_tuples(obj, encoding, hash_key), dtype="uint64", copy=False) elif isinstance(obj, ABCIndex): - h = hash_array(obj._values, encoding, hash_key, categorize).astype( - "uint64", copy=False - ) - h = Series(h, index=obj, dtype="uint64", copy=False) + # error: Value of type variable "ArrayLike" of "hash_array" cannot be + # "Union[ExtensionArray, ndarray]" + h = hash_array( # type: ignore[type-var] + obj._values, encoding, hash_key, categorize + ).astype("uint64", copy=False) + # error: Incompatible types in assignment (expression has type "Series", + # variable has type "ndarray") + h = Series(h, index=obj, dtype="uint64", copy=False) # type: ignore[assignment] elif isinstance(obj, ABCSeries): h = hash_array(obj._values, encoding, hash_key, categorize).astype( @@ -139,7 +143,11 @@ def hash_pandas_object( arrays = itertools.chain([h], index_iter) h = combine_hash_arrays(arrays, 2) - h = Series(h, index=obj.index, dtype="uint64", copy=False) + # error: Incompatible types in assignment (expression has type "Series", + # variable has type "ndarray") + h = Series( # type: ignore[assignment] + h, index=obj.index, dtype="uint64", copy=False + ) elif isinstance(obj, ABCDataFrame): hashes = (hash_array(series._values) for _, series in obj.items()) @@ -162,10 +170,15 @@ def hash_pandas_object( hashes = (x for x in _hashes) h = combine_hash_arrays(hashes, num_items) - h = Series(h, index=obj.index, dtype="uint64", copy=False) + # error: Incompatible types in assignment (expression has type "Series", + # variable has type "ndarray") + h = Series( # type: ignore[assignment] + h, index=obj.index, dtype="uint64", copy=False + ) else: raise TypeError(f"Unexpected type for hashing {type(obj)}") - return h + # error: Incompatible return value type (got "ndarray", expected "Series") + return h # type: ignore[return-value] def hash_tuples( @@ -284,12 +297,21 @@ def hash_array( # hash values. (This check is above the complex check so that we don't ask # numpy if categorical is a subdtype of complex, as it will choke). if is_categorical_dtype(dtype): - vals = cast("Categorical", vals) - return _hash_categorical(vals, encoding, hash_key) + # error: Incompatible types in assignment (expression has type "Categorical", + # variable has type "ndarray") + vals = cast("Categorical", vals) # type: ignore[assignment] + # error: Argument 1 to "_hash_categorical" has incompatible type "ndarray"; + # expected "Categorical" + return _hash_categorical(vals, encoding, hash_key) # type: ignore[arg-type] elif is_extension_array_dtype(dtype): - vals, _ = vals._values_for_factorize() - - return _hash_ndarray(vals, encoding, hash_key, categorize) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + # error: "ndarray" has no attribute "_values_for_factorize" + vals, _ = vals._values_for_factorize() # type: ignore[assignment,attr-defined] + + # error: Argument 1 to "_hash_ndarray" has incompatible type "ExtensionArray"; + # expected "ndarray" + return _hash_ndarray(vals, encoding, hash_key, categorize) # type: ignore[arg-type] def _hash_ndarray( diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 4537e525c5086..4c9222e0805f1 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -261,7 +261,9 @@ def __init__( self.times = self._selected_obj[self.times] if not is_datetime64_ns_dtype(self.times): raise ValueError("times must be datetime64[ns] dtype.") - if len(self.times) != len(obj): + # error: Argument 1 to "len" has incompatible type "Union[str, ndarray, + # FrameOrSeries, None]"; expected "Sized" + if len(self.times) != len(obj): # type: ignore[arg-type] raise ValueError("times must be the same length as the object.") if not isinstance(self.halflife, (str, datetime.timedelta)): raise ValueError( @@ -269,7 +271,13 @@ def __init__( ) if isna(self.times).any(): raise ValueError("Cannot convert NaT values to integer") - _times = np.asarray(self.times.view(np.int64), dtype=np.float64) + # error: Item "str" of "Union[str, ndarray, FrameOrSeries, None]" has no + # attribute "view" + # error: Item "None" of "Union[str, ndarray, FrameOrSeries, None]" has no + # attribute "view" + _times = np.asarray( + self.times.view(np.int64), dtype=np.float64 # type: ignore[union-attr] + ) _halflife = float(Timedelta(self.halflife).value) self._deltas = np.diff(_times) / _halflife # Halflife is no longer applicable when calculating COM @@ -289,7 +297,13 @@ def __init__( # Without times, points are equally spaced self._deltas = np.ones(max(len(self.obj) - 1, 0), dtype=np.float64) self._com = get_center_of_mass( - self.com, self.span, self.halflife, self.alpha + # error: Argument 3 to "get_center_of_mass" has incompatible type + # "Union[float, Any, None, timedelta64, signedinteger[_64Bit]]"; + # expected "Optional[float]" + self.com, + self.span, + self.halflife, # type: ignore[arg-type] + self.alpha, ) def _get_window_indexer(self) -> BaseIndexer: diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 503849bf673d5..17d05e81b82bb 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -316,11 +316,17 @@ def _prep_values(self, values: ArrayLike) -> np.ndarray: raise TypeError(f"cannot handle this type -> {values.dtype}") from err # Convert inf to nan for C funcs - inf = np.isinf(values) + + # error: Argument 1 to "__call__" of "ufunc" has incompatible type + # "Optional[ndarray]"; expected "Union[bool, int, float, complex, + # _SupportsArray, Sequence[Any]]" + inf = np.isinf(values) # type: ignore[arg-type] if inf.any(): values = np.where(inf, np.nan, values) - return values + # error: Incompatible return value type (got "Optional[ndarray]", + # expected "ndarray") + return values # type: ignore[return-value] def _insert_on_column(self, result: DataFrame, obj: DataFrame): # if we have an 'on' column we want to put it back into @@ -418,7 +424,11 @@ def hfunc(bvalues: ArrayLike) -> ArrayLike: return getattr(res_values, "T", res_values) def hfunc2d(values: ArrayLike) -> ArrayLike: - values = self._prep_values(values) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + # error: Argument 1 to "_prep_values" of "BaseWindow" has incompatible type + # "ExtensionArray"; expected "Optional[ndarray]" + values = self._prep_values(values) # type: ignore[assignment,arg-type] return homogeneous_func(values) if isinstance(mgr, ArrayManager) and self.axis == 1: diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index ab8e19d9f8a6f..f54481f527d93 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1565,7 +1565,10 @@ def _format_strings(self) -> List[str]: if is_categorical_dtype(values.dtype): # Categorical is special for now, so that we can preserve tzinfo - array = values._internal_get_values() + + # error: Item "ExtensionArray" of "Union[Any, ExtensionArray]" has no + # attribute "_internal_get_values" + array = values._internal_get_values() # type: ignore[union-attr] else: array = np.asarray(values) @@ -1632,10 +1635,25 @@ def format_percentiles( raise ValueError("percentiles should all be in the interval [0,1]") percentiles = 100 * percentiles - int_idx = np.isclose(percentiles.astype(int), percentiles) + + # error: Item "List[Union[int, float]]" of "Union[ndarray, List[Union[int, float]], + # List[float], List[Union[str, float]]]" has no attribute "astype" + # error: Item "List[float]" of "Union[ndarray, List[Union[int, float]], List[float], + # List[Union[str, float]]]" has no attribute "astype" + # error: Item "List[Union[str, float]]" of "Union[ndarray, List[Union[int, float]], + # List[float], List[Union[str, float]]]" has no attribute "astype" + int_idx = np.isclose( + percentiles.astype(int), percentiles # type: ignore[union-attr] + ) if np.all(int_idx): - out = percentiles.astype(int).astype(str) + # error: Item "List[Union[int, float]]" of "Union[ndarray, List[Union[int, + # float]], List[float], List[Union[str, float]]]" has no attribute "astype" + # error: Item "List[float]" of "Union[ndarray, List[Union[int, float]], + # List[float], List[Union[str, float]]]" has no attribute "astype" + # error: Item "List[Union[str, float]]" of "Union[ndarray, List[Union[int, + # float]], List[float], List[Union[str, float]]]" has no attribute "astype" + out = percentiles.astype(int).astype(str) # type: ignore[union-attr] return [i + "%" for i in out] unique_pcts = np.unique(percentiles) @@ -1648,8 +1666,19 @@ def format_percentiles( ).astype(int) prec = max(1, prec) out = np.empty_like(percentiles, dtype=object) - out[int_idx] = percentiles[int_idx].astype(int).astype(str) - out[~int_idx] = percentiles[~int_idx].round(prec).astype(str) + # error: No overload variant of "__getitem__" of "list" matches argument type + # "Union[bool_, ndarray]" + out[int_idx] = ( + percentiles[int_idx].astype(int).astype(str) # type: ignore[call-overload] + ) + + # error: Item "float" of "Union[Any, float, str]" has no attribute "round" + # error: Item "str" of "Union[Any, float, str]" has no attribute "round" + # error: Invalid index type "Union[bool_, Any]" for "Union[ndarray, List[Union[int, + # float]], List[float], List[Union[str, float]]]"; expected type "int" + out[~int_idx] = ( + percentiles[~int_idx].round(prec).astype(str) # type: ignore[union-attr,index] + ) return [i + "%" for i in out] @@ -1772,7 +1801,11 @@ def get_format_timedelta64( one_day_nanos = 86400 * 10 ** 9 even_days = ( - np.logical_and(consider_values, values_int % one_day_nanos != 0).sum() == 0 + # error: Unsupported operand types for % ("ExtensionArray" and "int") + np.logical_and( + consider_values, values_int % one_day_nanos != 0 # type: ignore[operator] + ).sum() + == 0 ) if even_days: diff --git a/pandas/io/formats/string.py b/pandas/io/formats/string.py index 622001f280885..84333cfc441b2 100644 --- a/pandas/io/formats/string.py +++ b/pandas/io/formats/string.py @@ -117,7 +117,13 @@ def _join_multiline(self, strcols_input: Iterable[List[str]]) -> str: if self.fmt.index: idx = strcols.pop(0) - lwidth -= np.array([self.adj.len(x) for x in idx]).max() + adjoin_width + # error: Argument 1 to "__call__" of "_NumberOp" has incompatible type + # "None"; expected "Union[int, float, complex, number, bool_]" + # error: Incompatible types in assignment (expression has type "number", + # variable has type "Optional[int]") + lwidth -= ( # type: ignore[assignment,arg-type] + np.array([self.adj.len(x) for x in idx]).max() + adjoin_width + ) col_widths = [ np.array([self.adj.len(x) for x in col]).max() if len(col) > 0 else 0 @@ -125,7 +131,9 @@ def _join_multiline(self, strcols_input: Iterable[List[str]]) -> str: ] assert lwidth is not None - col_bins = _binify(col_widths, lwidth) + # error: Argument 1 to "_binify" has incompatible type "List[object]"; expected + # "List[int]" + col_bins = _binify(col_widths, lwidth) # type: ignore[arg-type] nbins = len(col_bins) if self.fmt.is_truncated_vertically: diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index ec09a4cc4cd89..cc5f3164385cb 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -1708,7 +1708,11 @@ def f(data: DataFrame, props: str) -> np.ndarray: if props is None: props = f"background-color: {null_color};" - return self.apply(f, axis=None, subset=subset, props=props) + # error: Argument 1 to "apply" of "Styler" has incompatible type + # "Callable[[DataFrame, str], ndarray]"; expected "Callable[..., Styler]" + return self.apply( + f, axis=None, subset=subset, props=props # type: ignore[arg-type] + ) def highlight_max( self, @@ -1751,7 +1755,11 @@ def f(data: FrameOrSeries, props: str) -> np.ndarray: if props is None: props = f"background-color: {color};" - return self.apply(f, axis=axis, subset=subset, props=props) + # error: Argument 1 to "apply" of "Styler" has incompatible type + # "Callable[[FrameOrSeries, str], ndarray]"; expected "Callable[..., Styler]" + return self.apply( + f, axis=axis, subset=subset, props=props # type: ignore[arg-type] + ) def highlight_min( self, @@ -1794,7 +1802,11 @@ def f(data: FrameOrSeries, props: str) -> np.ndarray: if props is None: props = f"background-color: {color};" - return self.apply(f, axis=axis, subset=subset, props=props) + # error: Argument 1 to "apply" of "Styler" has incompatible type + # "Callable[[FrameOrSeries, str], ndarray]"; expected "Callable[..., Styler]" + return self.apply( + f, axis=axis, subset=subset, props=props # type: ignore[arg-type] + ) @classmethod def from_custom_template(cls, searchpath, name): diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index aa654e971641f..7c83beca1ae71 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -570,7 +570,12 @@ def read_json( raise ValueError("cannot pass both convert_axes and orient='table'") if dtype is None and orient != "table": - dtype = True + # error: Incompatible types in assignment (expression has type "bool", variable + # has type "Union[ExtensionDtype, str, dtype[Any], Type[str], Type[float], + # Type[int], Type[complex], Type[bool], Type[object], Dict[Optional[Hashable], + # Union[ExtensionDtype, Union[str, dtype[Any]], Type[str], Type[float], + # Type[int], Type[complex], Type[bool], Type[object]]], None]") + dtype = True # type: ignore[assignment] if convert_axes is None and orient != "table": convert_axes = True @@ -914,7 +919,12 @@ def _try_convert_data(self, name, data, use_dtypes=True, convert_dates=True): return data, False return data.fillna(np.nan), True - elif self.dtype is True: + # error: Non-overlapping identity check (left operand type: + # "Union[ExtensionDtype, str, dtype[Any], Type[object], + # Dict[Optional[Hashable], Union[ExtensionDtype, Union[str, dtype[Any]], + # Type[str], Type[float], Type[int], Type[complex], Type[bool], + # Type[object]]]]", right operand type: "Literal[True]") + elif self.dtype is True: # type: ignore[comparison-overlap] pass else: # dtype to force @@ -923,7 +933,10 @@ def _try_convert_data(self, name, data, use_dtypes=True, convert_dates=True): ) if dtype is not None: try: - dtype = np.dtype(dtype) + # error: Argument 1 to "dtype" has incompatible type + # "Union[ExtensionDtype, str, dtype[Any], Type[object]]"; + # expected "Type[Any]" + dtype = np.dtype(dtype) # type: ignore[arg-type] return data.astype(dtype), True except (TypeError, ValueError): return data, False diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py index c05efe9e73c5a..4539ceabbb92f 100644 --- a/pandas/io/parsers/base_parser.py +++ b/pandas/io/parsers/base_parser.py @@ -658,7 +658,9 @@ def _infer_types(self, values, na_values, try_num_bool=True): na_count = 0 if issubclass(values.dtype.type, (np.number, np.bool_)): mask = algorithms.isin(values, list(na_values)) - na_count = mask.sum() + # error: Incompatible types in assignment (expression has type + # "number[Any]", variable has type "int") + na_count = mask.sum() # type: ignore[assignment] if na_count > 0: if is_integer_dtype(values): values = values.astype(np.float64) @@ -716,7 +718,10 @@ def _cast_types(self, values, cast_type, column): # TODO: this is for consistency with # c-parser which parses all categories # as strings - values = astype_nansafe(values, str) + + # error: Argument 2 to "astype_nansafe" has incompatible type + # "Type[str]"; expected "Union[dtype[Any], ExtensionDtype]" + values = astype_nansafe(values, str) # type: ignore[arg-type] cats = Index(values).unique().dropna() values = Categorical._from_inferred_categories( @@ -909,7 +914,20 @@ def _get_empty_meta( if not is_dict_like(dtype): # if dtype == None, default will be object. default_dtype = dtype or object - dtype = defaultdict(lambda: default_dtype) + # error: Argument 1 to "defaultdict" has incompatible type "Callable[[], + # Union[ExtensionDtype, str, dtype[Any], Type[object], Dict[Hashable, + # Union[ExtensionDtype, Union[str, dtype[Any]], Type[str], Type[float], + # Type[int], Type[complex], Type[bool], Type[object]]]]]"; expected + # "Optional[Callable[[], Union[ExtensionDtype, str, dtype[Any], + # Type[object]]]]" + # error: Incompatible return value type (got "Union[ExtensionDtype, str, + # dtype[Any], Type[object], Dict[Hashable, Union[ExtensionDtype, Union[str, + # dtype[Any]], Type[str], Type[float], Type[int], Type[complex], Type[bool], + # Type[object]]]]", expected "Union[ExtensionDtype, str, dtype[Any], + # Type[object]]") + dtype = defaultdict( + lambda: default_dtype # type: ignore[arg-type, return-value] + ) else: dtype = cast(dict, dtype) dtype = defaultdict( diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index ceb4900b887f1..24bd2da6cc12e 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -2092,7 +2092,9 @@ def convert(self, values: np.ndarray, nan_rep, encoding: str, errors: str): kwargs["freq"] = None new_pd_index = factory(values, **kwargs) - new_pd_index = _set_tz(new_pd_index, self.tz) + # error: Incompatible types in assignment (expression has type + # "Union[ndarray, DatetimeIndex]", variable has type "Index") + new_pd_index = _set_tz(new_pd_index, self.tz) # type: ignore[assignment] return new_pd_index, new_pd_index def take_data(self): @@ -2254,7 +2256,9 @@ def convert(self, values: np.ndarray, nan_rep, encoding: str, errors: str): """ assert isinstance(values, np.ndarray), type(values) - values = Int64Index(np.arange(len(values))) + # error: Incompatible types in assignment (expression has type + # "Int64Index", variable has type "ndarray") + values = Int64Index(np.arange(len(values))) # type: ignore[assignment] return values, values def set_attr(self): @@ -3087,10 +3091,17 @@ def write_array(self, key: str, obj: FrameOrSeries, items: Optional[Index] = Non elif is_datetime64tz_dtype(value.dtype): # store as UTC # with a zone - self._handle.create_array(self.group, key, value.asi8) + + # error: Item "ExtensionArray" of "Union[Any, ExtensionArray]" has no + # attribute "asi8" + self._handle.create_array( + self.group, key, value.asi8 # type: ignore[union-attr] + ) node = getattr(self.group, key) - node._v_attrs.tz = _get_tz(value.tz) + # error: Item "ExtensionArray" of "Union[Any, ExtensionArray]" has no + # attribute "tz" + node._v_attrs.tz = _get_tz(value.tz) # type: ignore[union-attr] node._v_attrs.value_type = "datetime64" elif is_timedelta64_dtype(value.dtype): self._handle.create_array(self.group, key, value.view("i8")) @@ -3376,7 +3387,10 @@ def validate_multiindex( @property def nrows_expected(self) -> int: """ based on our axes, compute the expected nrows """ - return np.prod([i.cvalues.shape[0] for i in self.index_axes]) + # error: Incompatible return value type (got "number", expected "int") + return np.prod( # type: ignore[return-value] + [i.cvalues.shape[0] for i in self.index_axes] + ) @property def is_exists(self) -> bool: @@ -3462,8 +3476,12 @@ def write_metadata(self, key: str, values: np.ndarray): key : str values : ndarray """ - values = Series(values) - self.parent.put( + # error: Incompatible types in assignment (expression has type + # "Series", variable has type "ndarray") + values = Series(values) # type: ignore[assignment] + # error: Value of type variable "FrameOrSeries" of "put" of "HDFStore" + # cannot be "ndarray" + self.parent.put( # type: ignore[type-var] self._get_metadata_path(key), values, format="table", @@ -4818,14 +4836,18 @@ def _set_tz( elif coerce: values = np.asarray(values, dtype="M8[ns]") - return values + # error: Incompatible return value type (got "Union[ndarray, Index]", + # expected "Union[ndarray, DatetimeIndex]") + return values # type: ignore[return-value] def _convert_index(name: str, index: Index, encoding: str, errors: str) -> IndexCol: assert isinstance(name, str) index_name = index.name - converted, dtype_name = _get_data_and_dtype_name(index) + # error: Value of type variable "ArrayLike" of "_get_data_and_dtype_name" + # cannot be "Index" + converted, dtype_name = _get_data_and_dtype_name(index) # type: ignore[type-var] kind = _dtype_to_kind(dtype_name) atom = DataIndexableCol._get_atom(converted) @@ -4966,7 +4988,12 @@ def _maybe_convert_for_string_atom( ) # itemsize is the maximum length of a string (along any dimension) - data_converted = _convert_string_array(data, encoding, errors).reshape(data.shape) + + # error: Argument 1 to "_convert_string_array" has incompatible type "Union[ndarray, + # ExtensionArray]"; expected "ndarray" + data_converted = _convert_string_array( + data, encoding, errors # type: ignore[arg-type] + ).reshape(data.shape) itemsize = data_converted.itemsize # specified min_itemsize? @@ -5142,20 +5169,26 @@ def _get_data_and_dtype_name(data: ArrayLike): Convert the passed data into a storable form and a dtype string. """ if isinstance(data, Categorical): - data = data.codes + # error: Incompatible types in assignment (expression has type + # "ndarray", variable has type "ExtensionArray") + data = data.codes # type: ignore[assignment] # For datetime64tz we need to drop the TZ in tests TODO: why? dtype_name = data.dtype.name.split("[")[0] if data.dtype.kind in ["m", "M"]: - data = np.asarray(data.view("i8")) + # error: Incompatible types in assignment (expression has type "ndarray", + # variable has type "ExtensionArray") + data = np.asarray(data.view("i8")) # type: ignore[assignment] # TODO: we used to reshape for the dt64tz case, but no longer # doing that doesn't seem to break anything. why? elif isinstance(data, PeriodIndex): data = data.asi8 - data = np.asarray(data) + # error: Incompatible types in assignment (expression has type "ndarray", variable + # has type "ExtensionArray") + data = np.asarray(data) # type: ignore[assignment] return data, dtype_name diff --git a/pandas/io/sql.py b/pandas/io/sql.py index c028e1f5c5dbe..fb08abb6fea45 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -898,7 +898,9 @@ def insert_data(self): mask = isna(d) d[mask] = None - data_list[i] = d + # error: No overload variant of "__setitem__" of "list" matches + # argument types "int", "ndarray" + data_list[i] = d # type: ignore[call-overload] return column_names, data_list @@ -1545,7 +1547,13 @@ def to_sql( """ if dtype: if not is_dict_like(dtype): - dtype = {col_name: dtype for col_name in frame} + # error: Value expression in dictionary comprehension has incompatible + # type "Union[ExtensionDtype, str, dtype[Any], Type[object], + # Dict[Optional[Hashable], Union[ExtensionDtype, Union[str, dtype[Any]], + # Type[str], Type[float], Type[int], Type[complex], Type[bool], + # Type[object]]]]"; expected type "Union[ExtensionDtype, str, + # dtype[Any], Type[object]]" + dtype = {col_name: dtype for col_name in frame} # type: ignore[misc] else: dtype = cast(dict, dtype) @@ -2022,7 +2030,13 @@ def to_sql( """ if dtype: if not is_dict_like(dtype): - dtype = {col_name: dtype for col_name in frame} + # error: Value expression in dictionary comprehension has incompatible + # type "Union[ExtensionDtype, str, dtype[Any], Type[object], + # Dict[Optional[Hashable], Union[ExtensionDtype, Union[str, dtype[Any]], + # Type[str], Type[float], Type[int], Type[complex], Type[bool], + # Type[object]]]]"; expected type "Union[ExtensionDtype, str, + # dtype[Any], Type[object]]" + dtype = {col_name: dtype for col_name in frame} # type: ignore[misc] else: dtype = cast(dict, dtype) diff --git a/pandas/io/stata.py b/pandas/io/stata.py index ebc0395aec0b2..c01a369bf0054 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -1233,7 +1233,9 @@ def g(typ: int) -> Union[str, np.dtype]: if typ <= 2045: return str(typ) try: - return self.DTYPE_MAP_XML[typ] + # error: Incompatible return value type (got "Type[number]", expected + # "Union[str, dtype]") + return self.DTYPE_MAP_XML[typ] # type: ignore[return-value] except KeyError as err: raise ValueError(f"cannot convert stata dtype [{typ}]") from err @@ -1666,7 +1668,12 @@ def read( if self.dtyplist[i] is not None: col = data.columns[i] dtype = data[col].dtype - if dtype != np.dtype(object) and dtype != self.dtyplist[i]: + # error: Value of type variable "_DTypeScalar" of "dtype" cannot be + # "object" + if ( + dtype != np.dtype(object) # type: ignore[type-var] + and dtype != self.dtyplist[i] + ): requires_type_conversion = True data_formatted.append( (col, Series(data[col], ix, self.dtyplist[i])) diff --git a/pandas/tests/io/parser/common/test_chunksize.py b/pandas/tests/io/parser/common/test_chunksize.py index 4bc3f3c38f506..6d5aeaa713687 100644 --- a/pandas/tests/io/parser/common/test_chunksize.py +++ b/pandas/tests/io/parser/common/test_chunksize.py @@ -143,7 +143,10 @@ def test_read_chunksize_jagged_names(all_parsers): parser = all_parsers data = "\n".join(["0"] * 7 + [",".join(["0"] * 10)]) - expected = DataFrame([[0] + [np.nan] * 9] * 7 + [[0] * 10]) + # error: List item 0 has incompatible type "float"; expected "int" + expected = DataFrame( + [[0] + [np.nan] * 9] * 7 + [[0] * 10] # type: ignore[list-item] + ) with parser.read_csv(StringIO(data), names=range(10), chunksize=4) as reader: result = concat(reader) tm.assert_frame_equal(result, expected) diff --git a/pandas/tseries/frequencies.py b/pandas/tseries/frequencies.py index 048d138608ef9..c5b875b8f027e 100644 --- a/pandas/tseries/frequencies.py +++ b/pandas/tseries/frequencies.py @@ -385,7 +385,8 @@ def _is_business_daily(self) -> bool: shifts = np.diff(self.index.asi8) shifts = np.floor_divide(shifts, _ONE_DAY) weekdays = np.mod(first_weekday + np.cumsum(shifts), 7) - return np.all( + # error: Incompatible return value type (got "bool_", expected "bool") + return np.all( # type: ignore[return-value] ((weekdays == 0) & (shifts == 3)) | ((weekdays > 0) & (weekdays <= 4) & (shifts == 1)) ) diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py index c39647522aaf1..752ed43849d2b 100644 --- a/pandas/util/_test_decorators.py +++ b/pandas/util/_test_decorators.py @@ -212,7 +212,9 @@ def skip_if_np_lt(ver_str: str, *args, reason: Optional[str] = None): if reason is None: reason = f"NumPy {ver_str} or greater required" return pytest.mark.skipif( - np.__version__ < LooseVersion(ver_str), *args, reason=reason + np.__version__ < LooseVersion(ver_str), + *args, + reason=reason, ) diff --git a/requirements-dev.txt b/requirements-dev.txt index 37adbbb8e671f..f60e3bf0daea7 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -1,7 +1,7 @@ # This file is auto-generated from environment.yml, do not modify. # See that file for comments about the need/usage of each dependency. -numpy>=1.16.5, <1.20 +numpy>=1.16.5 python-dateutil>=2.7.3 pytz asv diff --git a/setup.cfg b/setup.cfg index fdc0fbdbd6b57..a0b6a0cdfc260 100644 --- a/setup.cfg +++ b/setup.cfg @@ -192,3 +192,42 @@ check_untyped_defs = False [mypy-pandas.io.clipboard] check_untyped_defs = False + +[mypy-pandas.io.formats.string] +ignore_errors = True + +[mypy-pandas.tests.apply.test_series_apply] +ignore_errors = True + +[mypy-pandas.tests.arithmetic.conftest] +ignore_errors = True + +[mypy-pandas.tests.arrays.sparse.test_combine_concat] +ignore_errors = True + +[mypy-pandas.tests.dtypes.test_common] +ignore_errors = True + +[mypy-pandas.tests.frame.methods.test_to_records] +ignore_errors = True + +[mypy-pandas.tests.groupby.test_rank] +ignore_errors = True + +[mypy-pandas.tests.groupby.transform.test_transform] +ignore_errors = True + +[mypy-pandas.tests.indexes.interval.test_interval] +ignore_errors = True + +[mypy-pandas.tests.indexing.test_categorical] +ignore_errors = True + +[mypy-pandas.tests.io.excel.test_writers] +ignore_errors = True + +[mypy-pandas.tests.reductions.test_reductions] +ignore_errors = True + +[mypy-pandas.tests.test_expressions] +ignore_errors = True
xref #39513
https://api.github.com/repos/pandas-dev/pandas/pulls/36092
2020-09-03T15:54:38Z
2021-03-10T20:42:50Z
2021-03-10T20:42:49Z
2021-03-10T21:32:56Z
DOC: add mypy version to whatsnew\v1.2.0.rst
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index b07351d05defb..e65daa439a225 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -136,6 +136,8 @@ If installed, we now require: +-----------------+-----------------+----------+---------+ | pytest (dev) | 5.0.1 | | X | +-----------------+-----------------+----------+---------+ +| mypy (dev) | 0.782 | | X | ++-----------------+-----------------+----------+---------+ For `optional libraries <https://dev.pandas.io/docs/install.html#dependencies>`_ the general recommendation is to use the latest version. The following table lists the lowest version per library that is currently being tested throughout the development of pandas.
xref https://github.com/pandas-dev/pandas/pull/36012#issuecomment-685188102
https://api.github.com/repos/pandas-dev/pandas/pulls/36090
2020-09-03T12:36:39Z
2020-09-03T16:35:04Z
2020-09-03T16:35:04Z
2020-09-03T16:45:03Z
STY: add code check for use of builtin filter function
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 852f66763683b..35c4b284599a1 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -179,6 +179,10 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then invgrep -R --include="*.py" -E "super\(\w*, (self|cls)\)" pandas RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Check for use of builtin filter function' ; echo $MSG + invgrep -R --include="*.py" -P '(?<!def)[\(\s]filter\(' pandas + RET=$(($RET + $?)) ; echo $MSG "DONE" + # Check for the following code in testing: `np.testing` and `np.array_equal` MSG='Check for invalid testing' ; echo $MSG invgrep -r -E --include '*.py' --exclude testing.py '(numpy|np)(\.testing|\.array_equal)' pandas/tests/
xref https://github.com/pandas-dev/pandas/pull/35717#issuecomment-674051885
https://api.github.com/repos/pandas-dev/pandas/pulls/36089
2020-09-03T12:15:40Z
2020-09-05T03:19:00Z
2020-09-05T03:18:59Z
2020-09-05T07:30:48Z
TYP: activate Check for missing error codes
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 852f66763683b..2e0f27fefca0b 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -230,10 +230,9 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then invgrep -R --include="*.py" -P '# type: (?!ignore)' pandas RET=$(($RET + $?)) ; echo $MSG "DONE" - # https://github.com/python/mypy/issues/7384 - # MSG='Check for missing error codes with # type: ignore' ; echo $MSG - # invgrep -R --include="*.py" -P '# type: ignore(?!\[)' pandas - # RET=$(($RET + $?)) ; echo $MSG "DONE" + MSG='Check for missing error codes with # type: ignore' ; echo $MSG + invgrep -R --include="*.py" -P '# type:\s?ignore(?!\[)' pandas + RET=$(($RET + $?)) ; echo $MSG "DONE" MSG='Check for use of foo.__class__ instead of type(foo)' ; echo $MSG invgrep -R --include=*.{py,pyx} '\.__class__' pandas diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 1b5e1d81f00d6..5a44f87400b79 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -468,10 +468,9 @@ def _ndarray(self) -> np.ndarray: def _from_backing_data(self: _T, arr: np.ndarray) -> _T: # Note: we do not retain `freq` + # error: Too many arguments for "NDArrayBackedExtensionArray" # error: Unexpected keyword argument "dtype" for "NDArrayBackedExtensionArray" - # TODO: add my error code - # https://github.com/python/mypy/issues/7384 - return type(self)(arr, dtype=self.dtype) # type: ignore + return type(self)(arr, dtype=self.dtype) # type: ignore[call-arg] # ------------------------------------------------------------------ diff --git a/pandas/core/groupby/categorical.py b/pandas/core/groupby/categorical.py index 4d5acf527a867..3f04339803bf6 100644 --- a/pandas/core/groupby/categorical.py +++ b/pandas/core/groupby/categorical.py @@ -98,8 +98,10 @@ def recode_from_groupby( """ # we re-order to the original category orderings if sort: - return ci.set_categories(c.categories) # type: ignore [attr-defined] + # error: "CategoricalIndex" has no attribute "set_categories" + return ci.set_categories(c.categories) # type: ignore[attr-defined] # we are not sorting, so add unobserved to the end new_cats = c.categories[~c.categories.isin(ci.categories)] - return ci.add_categories(new_cats) # type: ignore [attr-defined] + # error: "CategoricalIndex" has no attribute "add_categories" + return ci.add_categories(new_cats) # type: ignore[attr-defined] diff --git a/pandas/io/common.py b/pandas/io/common.py index 9328f90ce67a3..2b13d54ec3aed 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -374,7 +374,11 @@ def get_compression_method( if isinstance(compression, Mapping): compression_args = dict(compression) try: - compression_method = compression_args.pop("method") # type: ignore + # error: Incompatible types in assignment (expression has type + # "Union[str, int, None]", variable has type "Optional[str]") + compression_method = compression_args.pop( # type: ignore[assignment] + "method" + ) except KeyError as err: raise ValueError("If mapping, compression must have key 'method'") from err else: diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 2d64e1b051444..147e4efd74bc3 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -656,7 +656,7 @@ def _plot(cls, ax: "Axes", x, y, style=None, is_errorbar: bool = False, **kwds): if style is not None: args = (x, y, style) else: - args = (x, y) # type:ignore[assignment] + args = (x, y) # type: ignore[assignment] return ax.plot(*args, **kwds) def _get_index_name(self) -> Optional[str]:
xref #35311
https://api.github.com/repos/pandas-dev/pandas/pulls/36088
2020-09-03T12:05:01Z
2020-09-04T20:59:52Z
2020-09-04T20:59:52Z
2020-09-05T10:10:50Z
DOC: Add trailing dot
diff --git a/doc/source/development/contributing_docstring.rst b/doc/source/development/contributing_docstring.rst index 0c780ad5f5847..33f30e1d97512 100644 --- a/doc/source/development/contributing_docstring.rst +++ b/doc/source/development/contributing_docstring.rst @@ -32,18 +32,18 @@ The next example gives an idea of what a docstring looks like: Parameters ---------- num1 : int - First number to add + First number to add. num2 : int - Second number to add + Second number to add. Returns ------- int - The sum of `num1` and `num2` + The sum of `num1` and `num2`. See Also -------- - subtract : Subtract one integer from another + subtract : Subtract one integer from another. Examples -------- @@ -998,4 +998,4 @@ mapping function names to docstrings. Wherever possible, we prefer using See ``pandas.core.generic.NDFrame.fillna`` for an example template, and ``pandas.core.series.Series.fillna`` and ``pandas.core.generic.frame.fillna`` -for the filled versions. \ No newline at end of file +for the filled versions.
https://api.github.com/repos/pandas-dev/pandas/pulls/36087
2020-09-03T11:38:59Z
2020-09-03T16:14:10Z
2020-09-03T16:14:10Z
2020-09-03T16:14:18Z
DOC: minor fixes to whatsnew\v1.1.2.rst
diff --git a/doc/source/whatsnew/v1.1.2.rst b/doc/source/whatsnew/v1.1.2.rst index c740c7b3882c9..ac9fe9d2fca26 100644 --- a/doc/source/whatsnew/v1.1.2.rst +++ b/doc/source/whatsnew/v1.1.2.rst @@ -30,9 +30,9 @@ Bug fixes - Bug in :meth:`DataFrame.eval` with ``object`` dtype column binary operations (:issue:`35794`) - Bug in :class:`Series` constructor raising a ``TypeError`` when constructing sparse datetime64 dtypes (:issue:`35762`) - Bug in :meth:`DataFrame.apply` with ``result_type="reduce"`` returning with incorrect index (:issue:`35683`) -- Bug in :meth:`DateTimeIndex.format` and :meth:`PeriodIndex.format` with ``name=True`` setting the first item to ``"None"`` where it should bw ``""`` (:issue:`35712`) +- Bug in :meth:`DateTimeIndex.format` and :meth:`PeriodIndex.format` with ``name=True`` setting the first item to ``"None"`` where it should be ``""`` (:issue:`35712`) - Bug in :meth:`Float64Index.__contains__` incorrectly raising ``TypeError`` instead of returning ``False`` (:issue:`35788`) -- Bug in :class:`DataFrame` indexing returning an incorrect :class:`Series` in some cases when the series has been altered and a cache not invalidated (:issue:`36051`) +- Bug in :class:`DataFrame` indexing returning an incorrect :class:`Series` in some cases when the series has been altered and a cache not invalidated (:issue:`33675`) .. --------------------------------------------------------------------------- @@ -40,7 +40,7 @@ Bug fixes Other ~~~~~ -- :meth:`factorize` now supports ``na_sentinel=None`` to include NaN in the uniques of the values and remove ``dropna`` keyword which was unintentionally exposed to public facing API in 1.1 version from :meth:`factorize`(:issue:`35667`) +- :meth:`factorize` now supports ``na_sentinel=None`` to include NaN in the uniques of the values and remove ``dropna`` keyword which was unintentionally exposed to public facing API in 1.1 version from :meth:`factorize` (:issue:`35667`) .. ---------------------------------------------------------------------------
https://pandas.pydata.org/pandas-docs/dev/whatsnew/v1.1.2.html
https://api.github.com/repos/pandas-dev/pandas/pulls/36086
2020-09-03T11:25:04Z
2020-09-03T16:29:47Z
2020-09-03T16:29:47Z
2020-09-03T16:46:30Z
CI: MyPy fixup
diff --git a/pandas/io/common.py b/pandas/io/common.py index 97dbc7f1031a2..9328f90ce67a3 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -165,11 +165,16 @@ def is_fsspec_url(url: FilePathOrBuffer) -> bool: ) -def get_filepath_or_buffer( # type: ignore[assignment] +# https://github.com/python/mypy/issues/8708 +# error: Incompatible default for argument "encoding" (default has type "None", +# argument has type "str") +# error: Incompatible default for argument "mode" (default has type "None", +# argument has type "str") +def get_filepath_or_buffer( filepath_or_buffer: FilePathOrBuffer, - encoding: EncodingVar = None, + encoding: EncodingVar = None, # type: ignore[assignment] compression: CompressionOptions = None, - mode: ModeVar = None, + mode: ModeVar = None, # type: ignore[assignment] storage_options: StorageOptions = None, ) -> IOargs[ModeVar, EncodingVar]: """
https://github.com/pandas-dev/pandas/runs/1064831108 ``` mypy --version mypy 0.782 Performing static analysis using mypy pandas/io/common.py:168: error: unused 'type: ignore' comment pandas/io/common.py:170: error: Incompatible default for argument "encoding" (default has type "None", argument has type "str") [assignment] pandas/io/common.py:172: error: Incompatible default for argument "mode" (default has type "None", argument has type "str") [assignment] Found 3 errors in 1 file (checked 1037 source files) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/36085
2020-09-03T08:39:18Z
2020-09-03T10:20:52Z
2020-09-03T10:20:52Z
2020-09-03T10:22:21Z