title
stringlengths
1
185
diff
stringlengths
0
32.2M
body
stringlengths
0
123k
url
stringlengths
57
58
created_at
stringlengths
20
20
closed_at
stringlengths
20
20
merged_at
stringlengths
20
20
updated_at
stringlengths
20
20
BUG: avoid unnecessary casting when unstacking index with unused levels
diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index dc305f36f32ec..dc3df2f16c6b3 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -444,6 +444,8 @@ Reshaping ^^^^^^^^^ - Bug in :func:`DataFrame.stack` which fails trying to sort mixed type levels under Python 3 (:issue:`18310`) +- Bug in :func:`DataFrame.unstack` which casts int to float if ``columns`` is a ``MultiIndex`` with unused levels (:issue:`17845`) +- Bug in :func:`DataFrame.unstack` which raises an error if ``index`` is a ``MultiIndex`` with unused labels on the unstacked level (:issue:`18562`) - Fixed construction of a :class:`Series` from a ``dict`` containing ``NaN`` as key (:issue:`18480`) - Bug in :func:`Series.rank` where ``Series`` containing ``NaT`` modifies the ``Series`` inplace (:issue:`18521`) - Bug in :func:`cut` which fails when using readonly arrays (:issue:`18773`) diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index d6aed064e49f8..cadd63cc7c665 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -89,18 +89,19 @@ def __init__(self, values, index, level=-1, value_columns=None, if value_columns is None and values.shape[1] != 1: # pragma: no cover raise ValueError('must pass column labels for multi-column data') - self.index = index + self.index = index.remove_unused_levels() self.level = self.index._get_level_number(level) # when index includes `nan`, need to lift levels/strides by 1 self.lift = 1 if -1 in self.index.labels[self.level] else 0 - self.new_index_levels = list(index.levels) - self.new_index_names = list(index.names) + self.new_index_levels = list(self.index.levels) + self.new_index_names = list(self.index.names) self.removed_name = self.new_index_names.pop(self.level) self.removed_level = self.new_index_levels.pop(self.level) + self.removed_level_full = index.levels[self.level] self._make_sorted_values_labels() self._make_selectors() @@ -150,21 +151,10 @@ def _make_selectors(self): self.compressor = comp_index.searchsorted(np.arange(ngroups)) def get_result(self): - # TODO: find a better way than this masking business - - values, value_mask = self.get_new_values() + values, _ = self.get_new_values() columns = self.get_new_columns() index = self.get_new_index() - # filter out missing levels - if values.shape[1] > 0: - col_inds, obs_ids = compress_group_index(self.sorted_labels[-1]) - # rare case, level values not observed - if len(obs_ids) < self.full_shape[1]: - inds = (value_mask.sum(0) > 0).nonzero()[0] - values = algos.take_nd(values, inds, axis=1) - columns = columns[inds] - # may need to coerce categoricals here if self.is_categorical is not None: categories = self.is_categorical.categories @@ -253,17 +243,28 @@ def get_new_columns(self): width = len(self.value_columns) propagator = np.repeat(np.arange(width), stride) if isinstance(self.value_columns, MultiIndex): - new_levels = self.value_columns.levels + (self.removed_level,) + new_levels = self.value_columns.levels + (self.removed_level_full,) new_names = self.value_columns.names + (self.removed_name,) new_labels = [lab.take(propagator) for lab in self.value_columns.labels] else: - new_levels = [self.value_columns, self.removed_level] + new_levels = [self.value_columns, self.removed_level_full] new_names = [self.value_columns.name, self.removed_name] new_labels = [propagator] - new_labels.append(np.tile(np.arange(stride) - self.lift, width)) + # The two indices differ only if the unstacked level had unused items: + if len(self.removed_level_full) != len(self.removed_level): + # In this case, we remap the new labels to the original level: + repeater = self.removed_level_full.get_indexer(self.removed_level) + if self.lift: + repeater = np.insert(repeater, 0, -1) + else: + # Otherwise, we just use each level item exactly once: + repeater = np.arange(stride) - self.lift + + # The entire level is then just a repetition of the single chunk: + new_labels.append(np.tile(repeater, width)) return MultiIndex(levels=new_levels, labels=new_labels, names=new_names, verify_integrity=False) diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index 5ff4f58774322..7907486c7c98d 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -560,6 +560,74 @@ def test_unstack_dtypes(self): assert left.shape == (3, 2) tm.assert_frame_equal(left, right) + def test_unstack_unused_levels(self): + # GH 17845: unused labels in index make unstack() cast int to float + idx = pd.MultiIndex.from_product([['a'], ['A', 'B', 'C', 'D']])[:-1] + df = pd.DataFrame([[1, 0]] * 3, index=idx) + + result = df.unstack() + exp_col = pd.MultiIndex.from_product([[0, 1], ['A', 'B', 'C']]) + expected = pd.DataFrame([[1, 1, 1, 0, 0, 0]], index=['a'], + columns=exp_col) + tm.assert_frame_equal(result, expected) + assert((result.columns.levels[1] == idx.levels[1]).all()) + + # Unused items on both levels + levels = [[0, 1, 7], [0, 1, 2, 3]] + labels = [[0, 0, 1, 1], [0, 2, 0, 2]] + idx = pd.MultiIndex(levels, labels) + block = np.arange(4).reshape(2, 2) + df = pd.DataFrame(np.concatenate([block, block + 4]), index=idx) + result = df.unstack() + expected = pd.DataFrame(np.concatenate([block * 2, block * 2 + 1], + axis=1), + columns=idx) + tm.assert_frame_equal(result, expected) + assert((result.columns.levels[1] == idx.levels[1]).all()) + + # With mixed dtype and NaN + levels = [['a', 2, 'c'], [1, 3, 5, 7]] + labels = [[0, -1, 1, 1], [0, 2, -1, 2]] + idx = pd.MultiIndex(levels, labels) + data = np.arange(8) + df = pd.DataFrame(data.reshape(4, 2), index=idx) + + cases = ((0, [13, 16, 6, 9, 2, 5, 8, 11], + [np.nan, 'a', 2], [np.nan, 5, 1]), + (1, [8, 11, 1, 4, 12, 15, 13, 16], + [np.nan, 5, 1], [np.nan, 'a', 2])) + for level, idces, col_level, idx_level in cases: + result = df.unstack(level=level) + exp_data = np.zeros(18) * np.nan + exp_data[idces] = data + cols = pd.MultiIndex.from_product([[0, 1], col_level]) + expected = pd.DataFrame(exp_data.reshape(3, 6), + index=idx_level, columns=cols) + # Broken (GH 18455): + # tm.assert_frame_equal(result, expected) + diff = result - expected + assert(diff.sum().sum() == 0) + assert((diff + 1).sum().sum() == 8) + + assert((result.columns.levels[1] == idx.levels[level]).all()) + + @pytest.mark.parametrize("cols", [['A', 'C'], slice(None)]) + def test_unstack_unused_level(self, cols): + # GH 18562 : unused labels on the unstacked level + df = pd.DataFrame([[2010, 'a', 'I'], + [2011, 'b', 'II']], + columns=['A', 'B', 'C']) + + ind = df.set_index(['A', 'B', 'C'], drop=False) + selection = ind.loc[(slice(None), slice(None), 'I'), cols] + result = selection.unstack() + + expected = ind.iloc[[0]][cols] + expected.columns = MultiIndex.from_product([expected.columns, ['I']], + names=[None, 'C']) + expected.index = expected.index.droplevel('C') + tm.assert_frame_equal(result, expected) + def test_unstack_nan_index(self): # GH7466 cast = lambda val: '{0:1}'.format('' if val != val else val) nan = np.nan
closes #17845 closes #18562 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/18460
2017-11-23T23:08:03Z
2018-01-16T00:18:49Z
2018-01-16T00:18:48Z
2018-01-17T16:43:24Z
CLN/DEPR: remove pd.ordered_merge
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 92d9123d2cf4c..9716aab69143d 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -95,6 +95,7 @@ Removal of prior version deprecations/changes - The ``levels`` and ``labels`` attributes of a ``MultiIndex`` can no longer be set directly (:issue:`4039`). - ``pd.tseries.util.pivot_annual`` has been removed (deprecated since v0.19). Use ``pivot_table`` instead (:issue:`18370`) - ``pd.tseries.util.isleapyear`` has been removed (deprecated since v0.19). Use ``.is_leap_year`` property in Datetime-likes instead (:issue:`18370`) +- ``pd.ordered_merge`` has been removed (deprecated since v0.19). Use ``pd..merge_ordered`` instead (:issue:`18459`) .. _whatsnew_0220.performance: diff --git a/pandas/core/reshape/api.py b/pandas/core/reshape/api.py index 454a3965d74a6..11d69359f5c65 100644 --- a/pandas/core/reshape/api.py +++ b/pandas/core/reshape/api.py @@ -3,7 +3,6 @@ from pandas.core.reshape.concat import concat from pandas.core.reshape.melt import melt, lreshape, wide_to_long from pandas.core.reshape.reshape import pivot_simple as pivot, get_dummies -from pandas.core.reshape.merge import ( - merge, ordered_merge, merge_ordered, merge_asof) +from pandas.core.reshape.merge import merge, merge_ordered, merge_asof from pandas.core.reshape.pivot import pivot_table, crosstab from pandas.core.reshape.tile import cut, qcut diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index d00aa1003988a..e4b31939250a7 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -139,19 +139,6 @@ def _groupby_and_merge(by, on, left, right, _merge_pieces, return result, lby -def ordered_merge(left, right, on=None, - left_on=None, right_on=None, - left_by=None, right_by=None, - fill_method=None, suffixes=('_x', '_y')): - - warnings.warn("ordered_merge is deprecated and replaced by merge_ordered", - FutureWarning, stacklevel=2) - return merge_ordered(left, right, on=on, - left_on=left_on, right_on=right_on, - left_by=left_by, right_by=right_by, - fill_method=fill_method, suffixes=suffixes) - - def merge_ordered(left, right, on=None, left_on=None, right_on=None, left_by=None, right_by=None, @@ -204,7 +191,7 @@ def merge_ordered(left, right, on=None, 4 c 2 b 5 e 3 b - >>> ordered_merge(A, B, fill_method='ffill', left_by='group') + >>> merge_ordered(A, B, fill_method='ffill', left_by='group') key lvalue group rvalue 0 a 1 a NaN 1 b 1 a 1 @@ -253,9 +240,6 @@ def _merger(x, y): return result -ordered_merge.__doc__ = merge_ordered.__doc__ - - def merge_asof(left, right, on=None, left_on=None, right_on=None, left_index=False, right_index=False, diff --git a/pandas/tests/api/test_api.py b/pandas/tests/api/test_api.py index fad455d6391c3..0d1ea1c775aeb 100644 --- a/pandas/tests/api/test_api.py +++ b/pandas/tests/api/test_api.py @@ -103,7 +103,7 @@ class TestPDApi(Base): 'rolling_kurt', 'rolling_max', 'rolling_mean', 'rolling_median', 'rolling_min', 'rolling_quantile', 'rolling_skew', 'rolling_std', 'rolling_sum', - 'rolling_var', 'rolling_window', 'ordered_merge', + 'rolling_var', 'rolling_window', 'pnow', 'match', 'groupby', 'get_store', 'plot_params', 'scatter_matrix'] diff --git a/pandas/tests/reshape/test_merge_ordered.py b/pandas/tests/reshape/test_merge_ordered.py index 9b1806ee52c1d..a4c8793cc0ade 100644 --- a/pandas/tests/reshape/test_merge_ordered.py +++ b/pandas/tests/reshape/test_merge_ordered.py @@ -6,7 +6,7 @@ from numpy import nan -class TestOrderedMerge(object): +class TestMergeOrdered(object): def setup_method(self, method): self.left = DataFrame({'key': ['a', 'c', 'e'], @@ -15,13 +15,6 @@ def setup_method(self, method): self.right = DataFrame({'key': ['b', 'c', 'd', 'f'], 'rvalue': [1, 2, 3., 4]}) - def test_deprecation(self): - - with tm.assert_produces_warning(FutureWarning): - pd.ordered_merge(self.left, self.right, on='key') - - # GH #813 - def test_basic(self): result = merge_ordered(self.left, self.right, on='key') expected = DataFrame({'key': ['a', 'b', 'c', 'd', 'e', 'f'],
- [ x] xref #13358 - [x ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ x] whatsnew entry ``pd.ordered_merge`` was deprecated in #13358 (pandas v.0.19). This PR removes it from the code base.
https://api.github.com/repos/pandas-dev/pandas/pulls/18459
2017-11-23T22:50:44Z
2017-11-24T20:03:18Z
2017-11-24T20:03:18Z
2017-11-24T20:32:20Z
DEPR: Deprecate NDFrame.as_matrix
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 7229bd38fffa9..f1354161f1608 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -87,7 +87,7 @@ Deprecations ~~~~~~~~~~~~ - ``Series.from_array`` and ``SparseSeries.from_array`` are deprecated. Use the normal constructor ``Series(..)`` and ``SparseSeries(..)`` instead (:issue:`18213`). -- +- ``DataFrame.as_matrix`` is deprecated. Use ``DataFrame.values`` instead (:issue:`18458`). - .. _whatsnew_0220.prior_deprecations: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 548f228cdd96b..54b0089335b19 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3735,6 +3735,9 @@ def _get_bool_data(self): def as_matrix(self, columns=None): """ + DEPRECATED: as_matrix will be removed in a future version. + Use :meth:`DataFrame.values` instead. + Convert the frame to its Numpy-array representation. Parameters @@ -3770,10 +3773,11 @@ def as_matrix(self, columns=None): -------- pandas.DataFrame.values """ + warnings.warn("Method .as_matrix will be removed in a future version. " + "Use .values instead.", FutureWarning, stacklevel=2) self._consolidate_inplace() - if self._AXIS_REVERSED: - return self._data.as_matrix(columns).T - return self._data.as_matrix(columns) + return self._data.as_array(transpose=self._AXIS_REVERSED, + items=columns) @property def values(self): @@ -3791,7 +3795,8 @@ def values(self): int32. By numpy.find_common_type convention, mixing int64 and uint64 will result in a flot64 dtype. """ - return self.as_matrix() + self._consolidate_inplace() + return self._data.as_array(transpose=self._AXIS_REVERSED) @property def _values(self): @@ -3801,11 +3806,11 @@ def _values(self): @property def _get_values(self): # compat - return self.as_matrix() + return self.values def get_values(self): """same as values (but handles sparseness conversions)""" - return self.as_matrix() + return self.values def get_dtype_counts(self): """Return the counts of dtypes in this object.""" diff --git a/pandas/core/internals.py b/pandas/core/internals.py index e537cb2edc1c4..4f25a19d437ca 100644 --- a/pandas/core/internals.py +++ b/pandas/core/internals.py @@ -3484,7 +3484,7 @@ def replace_list(self, src_list, dest_list, inplace=False, regex=False, mgr = self # figure out our mask a-priori to avoid repeated replacements - values = self.as_matrix() + values = self.as_array() def comp(s): if isna(s): @@ -3670,9 +3670,24 @@ def copy(self, deep=True, mgr=None): return self.apply('copy', axes=new_axes, deep=deep, do_integrity_check=False) - def as_matrix(self, items=None): + def as_array(self, transpose=False, items=None): + """Convert the blockmanager data into an numpy array. + + Parameters + ---------- + transpose : boolean, default False + If True, transpose the return array + items : list of strings or None + Names of block items that will be included in the returned + array. ``None`` means that all block items will be used + + Returns + ------- + arr : ndarray + """ if len(self.blocks) == 0: - return np.empty(self.shape, dtype=float) + arr = np.empty(self.shape, dtype=float) + return arr.transpose() if transpose else arr if items is not None: mgr = self.reindex_axis(items, axis=0) @@ -3680,9 +3695,11 @@ def as_matrix(self, items=None): mgr = self if self._is_single_block or not self.is_mixed_type: - return mgr.blocks[0].get_values() + arr = mgr.blocks[0].get_values() else: - return mgr._interleave() + arr = mgr._interleave() + + return arr.transpose() if transpose else arr def _interleave(self): """ diff --git a/pandas/core/panel.py b/pandas/core/panel.py index 0a5e705071b5e..0f3c5cb85249a 100644 --- a/pandas/core/panel.py +++ b/pandas/core/panel.py @@ -464,7 +464,7 @@ def to_excel(self, path, na_rep='', engine=None, **kwargs): def as_matrix(self): self._consolidate_inplace() - return self._data.as_matrix() + return self._data.as_array() # ---------------------------------------------------------------------- # Getting and setting elements diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index e81e31b718498..0b562269ea29d 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -243,31 +243,31 @@ def test_itertuples(self): def test_len(self): assert len(self.frame) == len(self.frame.index) - def test_as_matrix(self): + def test_values(self): frame = self.frame - mat = frame.as_matrix() + arr = frame.values - frameCols = frame.columns - for i, row in enumerate(mat): + frame_cols = frame.columns + for i, row in enumerate(arr): for j, value in enumerate(row): - col = frameCols[j] + col = frame_cols[j] if np.isnan(value): assert np.isnan(frame[col][i]) else: assert value == frame[col][i] # mixed type - mat = self.mixed_frame.as_matrix(['foo', 'A']) - assert mat[0, 0] == 'bar' + arr = self.mixed_frame[['foo', 'A']].values + assert arr[0, 0] == 'bar' df = self.klass({'real': [1, 2, 3], 'complex': [1j, 2j, 3j]}) - mat = df.as_matrix() - assert mat[0, 0] == 1j + arr = df.values + assert arr[0, 0] == 1j # single block corner case - mat = self.frame.as_matrix(['A', 'B']) + arr = self.frame[['A', 'B']].values expected = self.frame.reindex(columns=['A', 'B']).values - assert_almost_equal(mat, expected) + assert_almost_equal(arr, expected) def test_transpose(self): frame = self.frame @@ -311,8 +311,8 @@ def test_class_axis(self): DataFrame.index # no exception! DataFrame.columns # no exception! - def test_more_asMatrix(self): - values = self.mixed_frame.as_matrix() + def test_more_values(self): + values = self.mixed_frame.values assert values.shape[1] == len(self.mixed_frame.columns) def test_repr_with_mi_nat(self): @@ -369,6 +369,13 @@ def test_values(self): self.frame.values[:, 0] = 5. assert (self.frame.values[:, 0] == 5).all() + def test_as_matrix_deprecated(self): + # GH18458 + with tm.assert_produces_warning(FutureWarning): + result = self.frame.as_matrix(columns=self.frame.columns.tolist()) + expected = self.frame.values + tm.assert_numpy_array_equal(result, expected) + def test_deepcopy(self): cp = deepcopy(self.frame) series = cp['A'] diff --git a/pandas/tests/frame/test_block_internals.py b/pandas/tests/frame/test_block_internals.py index c29821ba51284..8b1fd7d50cb4d 100644 --- a/pandas/tests/frame/test_block_internals.py +++ b/pandas/tests/frame/test_block_internals.py @@ -67,10 +67,10 @@ def test_consolidate_inplace(self): for letter in range(ord('A'), ord('Z')): self.frame[chr(letter)] = chr(letter) - def test_as_matrix_consolidate(self): + def test_values_consolidate(self): self.frame['E'] = 7. assert not self.frame._data.is_consolidated() - _ = self.frame.as_matrix() # noqa + _ = self.frame.values # noqa assert self.frame._data.is_consolidated() def test_modify_values(self): @@ -91,50 +91,50 @@ def test_boolean_set_uncons(self): self.frame[self.frame > 1] = 2 assert_almost_equal(expected, self.frame.values) - def test_as_matrix_numeric_cols(self): + def test_values_numeric_cols(self): self.frame['foo'] = 'bar' - values = self.frame.as_matrix(['A', 'B', 'C', 'D']) + values = self.frame[['A', 'B', 'C', 'D']].values assert values.dtype == np.float64 - def test_as_matrix_lcd(self): + def test_values_lcd(self): # mixed lcd - values = self.mixed_float.as_matrix(['A', 'B', 'C', 'D']) + values = self.mixed_float[['A', 'B', 'C', 'D']].values assert values.dtype == np.float64 - values = self.mixed_float.as_matrix(['A', 'B', 'C']) + values = self.mixed_float[['A', 'B', 'C']].values assert values.dtype == np.float32 - values = self.mixed_float.as_matrix(['C']) + values = self.mixed_float[['C']].values assert values.dtype == np.float16 # GH 10364 # B uint64 forces float because there are other signed int types - values = self.mixed_int.as_matrix(['A', 'B', 'C', 'D']) + values = self.mixed_int[['A', 'B', 'C', 'D']].values assert values.dtype == np.float64 - values = self.mixed_int.as_matrix(['A', 'D']) + values = self.mixed_int[['A', 'D']].values assert values.dtype == np.int64 # B uint64 forces float because there are other signed int types - values = self.mixed_int.as_matrix(['A', 'B', 'C']) + values = self.mixed_int[['A', 'B', 'C']].values assert values.dtype == np.float64 # as B and C are both unsigned, no forcing to float is needed - values = self.mixed_int.as_matrix(['B', 'C']) + values = self.mixed_int[['B', 'C']].values assert values.dtype == np.uint64 - values = self.mixed_int.as_matrix(['A', 'C']) + values = self.mixed_int[['A', 'C']].values assert values.dtype == np.int32 - values = self.mixed_int.as_matrix(['C', 'D']) + values = self.mixed_int[['C', 'D']].values assert values.dtype == np.int64 - values = self.mixed_int.as_matrix(['A']) + values = self.mixed_int[['A']].values assert values.dtype == np.int32 - values = self.mixed_int.as_matrix(['C']) + values = self.mixed_int[['C']].values assert values.dtype == np.uint8 def test_constructor_with_convert(self): diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index 5b903c5a1eaf6..f0a21cde4fbd9 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -439,7 +439,7 @@ def test_columns_with_dups(self): xp.columns = ['A', 'A', 'B'] assert_frame_equal(rs, xp) - def test_as_matrix_duplicates(self): + def test_values_duplicates(self): df = DataFrame([[1, 2, 'a', 'b'], [1, 2, 'a', 'b']], columns=['one', 'one', 'two', 'two']) diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 4c0c7d8598a8e..a22d0174947e1 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -476,7 +476,7 @@ def test_copy(self, mgr): def test_sparse(self): mgr = create_mgr('a: sparse-1; b: sparse-2') # what to test here? - assert mgr.as_matrix().dtype == np.float64 + assert mgr.as_array().dtype == np.float64 def test_sparse_mixed(self): mgr = create_mgr('a: sparse-1; b: sparse-2; c: f8') @@ -485,32 +485,32 @@ def test_sparse_mixed(self): # what to test here? - def test_as_matrix_float(self): + def test_as_array_float(self): mgr = create_mgr('c: f4; d: f2; e: f8') - assert mgr.as_matrix().dtype == np.float64 + assert mgr.as_array().dtype == np.float64 mgr = create_mgr('c: f4; d: f2') - assert mgr.as_matrix().dtype == np.float32 + assert mgr.as_array().dtype == np.float32 - def test_as_matrix_int_bool(self): + def test_as_array_int_bool(self): mgr = create_mgr('a: bool-1; b: bool-2') - assert mgr.as_matrix().dtype == np.bool_ + assert mgr.as_array().dtype == np.bool_ mgr = create_mgr('a: i8-1; b: i8-2; c: i4; d: i2; e: u1') - assert mgr.as_matrix().dtype == np.int64 + assert mgr.as_array().dtype == np.int64 mgr = create_mgr('c: i4; d: i2; e: u1') - assert mgr.as_matrix().dtype == np.int32 + assert mgr.as_array().dtype == np.int32 - def test_as_matrix_datetime(self): + def test_as_array_datetime(self): mgr = create_mgr('h: datetime-1; g: datetime-2') - assert mgr.as_matrix().dtype == 'M8[ns]' + assert mgr.as_array().dtype == 'M8[ns]' - def test_as_matrix_datetime_tz(self): + def test_as_array_datetime_tz(self): mgr = create_mgr('h: M8[ns, US/Eastern]; g: M8[ns, CET]') assert mgr.get('h').dtype == 'datetime64[ns, US/Eastern]' assert mgr.get('g').dtype == 'datetime64[ns, CET]' - assert mgr.as_matrix().dtype == 'object' + assert mgr.as_array().dtype == 'object' def test_astype(self): # coerce all @@ -607,49 +607,49 @@ def test_interleave(self): for dtype in ['f8', 'i8', 'object', 'bool', 'complex', 'M8[ns]', 'm8[ns]']: mgr = create_mgr('a: {0}'.format(dtype)) - assert mgr.as_matrix().dtype == dtype + assert mgr.as_array().dtype == dtype mgr = create_mgr('a: {0}; b: {0}'.format(dtype)) - assert mgr.as_matrix().dtype == dtype + assert mgr.as_array().dtype == dtype # will be converted according the actual dtype of the underlying mgr = create_mgr('a: category') - assert mgr.as_matrix().dtype == 'i8' + assert mgr.as_array().dtype == 'i8' mgr = create_mgr('a: category; b: category') - assert mgr.as_matrix().dtype == 'i8' + assert mgr.as_array().dtype == 'i8' mgr = create_mgr('a: category; b: category2') - assert mgr.as_matrix().dtype == 'object' + assert mgr.as_array().dtype == 'object' mgr = create_mgr('a: category2') - assert mgr.as_matrix().dtype == 'object' + assert mgr.as_array().dtype == 'object' mgr = create_mgr('a: category2; b: category2') - assert mgr.as_matrix().dtype == 'object' + assert mgr.as_array().dtype == 'object' # combinations mgr = create_mgr('a: f8') - assert mgr.as_matrix().dtype == 'f8' + assert mgr.as_array().dtype == 'f8' mgr = create_mgr('a: f8; b: i8') - assert mgr.as_matrix().dtype == 'f8' + assert mgr.as_array().dtype == 'f8' mgr = create_mgr('a: f4; b: i8') - assert mgr.as_matrix().dtype == 'f8' + assert mgr.as_array().dtype == 'f8' mgr = create_mgr('a: f4; b: i8; d: object') - assert mgr.as_matrix().dtype == 'object' + assert mgr.as_array().dtype == 'object' mgr = create_mgr('a: bool; b: i8') - assert mgr.as_matrix().dtype == 'object' + assert mgr.as_array().dtype == 'object' mgr = create_mgr('a: complex') - assert mgr.as_matrix().dtype == 'complex' + assert mgr.as_array().dtype == 'complex' mgr = create_mgr('a: f8; b: category') - assert mgr.as_matrix().dtype == 'object' + assert mgr.as_array().dtype == 'object' mgr = create_mgr('a: M8[ns]; b: category') - assert mgr.as_matrix().dtype == 'object' + assert mgr.as_array().dtype == 'object' mgr = create_mgr('a: M8[ns]; b: bool') - assert mgr.as_matrix().dtype == 'object' + assert mgr.as_array().dtype == 'object' mgr = create_mgr('a: M8[ns]; b: i8') - assert mgr.as_matrix().dtype == 'object' + assert mgr.as_array().dtype == 'object' mgr = create_mgr('a: m8[ns]; b: bool') - assert mgr.as_matrix().dtype == 'object' + assert mgr.as_array().dtype == 'object' mgr = create_mgr('a: m8[ns]; b: i8') - assert mgr.as_matrix().dtype == 'object' + assert mgr.as_array().dtype == 'object' mgr = create_mgr('a: M8[ns]; b: m8[ns]') - assert mgr.as_matrix().dtype == 'object' + assert mgr.as_array().dtype == 'object' def test_interleave_non_unique_cols(self): df = DataFrame([ @@ -831,7 +831,7 @@ def test_equals_block_order_different_dtypes(self): def test_single_mgr_ctor(self): mgr = create_single_mgr('f8', num_rows=5) - assert mgr.as_matrix().tolist() == [0., 1., 2., 3., 4.] + assert mgr.as_array().tolist() == [0., 1., 2., 3., 4.] def test_validate_bool_args(self): invalid_values = [1, "True", [1, 2, 3], 5.0] @@ -878,7 +878,7 @@ class TestIndexing(object): def test_get_slice(self): def assert_slice_ok(mgr, axis, slobj): # import pudb; pudb.set_trace() - mat = mgr.as_matrix() + mat = mgr.as_array() # we maybe using an ndarray to test slicing and # might not be the full length of the axis @@ -889,7 +889,7 @@ def assert_slice_ok(mgr, axis, slobj): len(ax) - len(slobj), dtype=bool)]) sliced = mgr.get_slice(slobj, axis=axis) mat_slobj = (slice(None), ) * axis + (slobj, ) - tm.assert_numpy_array_equal(mat[mat_slobj], sliced.as_matrix(), + tm.assert_numpy_array_equal(mat[mat_slobj], sliced.as_array(), check_dtype=False) tm.assert_index_equal(mgr.axes[axis][slobj], sliced.axes[axis]) @@ -930,10 +930,10 @@ def assert_slice_ok(mgr, axis, slobj): def test_take(self): def assert_take_ok(mgr, axis, indexer): - mat = mgr.as_matrix() + mat = mgr.as_array() taken = mgr.take(indexer, axis) tm.assert_numpy_array_equal(np.take(mat, indexer, axis), - taken.as_matrix(), check_dtype=False) + taken.as_array(), check_dtype=False) tm.assert_index_equal(mgr.axes[axis].take(indexer), taken.axes[axis]) @@ -950,14 +950,14 @@ def assert_take_ok(mgr, axis, indexer): def test_reindex_axis(self): def assert_reindex_axis_is_ok(mgr, axis, new_labels, fill_value): - mat = mgr.as_matrix() + mat = mgr.as_array() indexer = mgr.axes[axis].get_indexer_for(new_labels) reindexed = mgr.reindex_axis(new_labels, axis, fill_value=fill_value) tm.assert_numpy_array_equal(algos.take_nd(mat, indexer, axis, fill_value=fill_value), - reindexed.as_matrix(), + reindexed.as_array(), check_dtype=False) tm.assert_index_equal(reindexed.axes[axis], new_labels) @@ -996,13 +996,13 @@ def test_reindex_indexer(self): def assert_reindex_indexer_is_ok(mgr, axis, new_labels, indexer, fill_value): - mat = mgr.as_matrix() + mat = mgr.as_array() reindexed_mat = algos.take_nd(mat, indexer, axis, fill_value=fill_value) reindexed = mgr.reindex_indexer(new_labels, indexer, axis, fill_value=fill_value) tm.assert_numpy_array_equal(reindexed_mat, - reindexed.as_matrix(), + reindexed.as_array(), check_dtype=False) tm.assert_index_equal(reindexed.axes[axis], new_labels) diff --git a/pandas/tests/sparse/test_frame.py b/pandas/tests/sparse/test_frame.py index e65059156c5b9..bb5dbdcaaa7c4 100644 --- a/pandas/tests/sparse/test_frame.py +++ b/pandas/tests/sparse/test_frame.py @@ -78,16 +78,16 @@ def test_fill_value_when_combine_const(self): res = df.add(2, fill_value=0) tm.assert_sp_frame_equal(res, exp) - def test_as_matrix(self): - empty = self.empty.as_matrix() + def test_values(self): + empty = self.empty.values assert empty.shape == (0, 0) no_cols = SparseDataFrame(index=np.arange(10)) - mat = no_cols.as_matrix() + mat = no_cols.values assert mat.shape == (10, 0) no_index = SparseDataFrame(columns=np.arange(10)) - mat = no_index.as_matrix() + mat = no_index.values assert mat.shape == (0, 10) def test_copy(self):
- [x ] xref #18262 - [x ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ x] whatsnew entry Deprecating ``NDFrame.as_matrix`` as per discussion in #18262.
https://api.github.com/repos/pandas-dev/pandas/pulls/18458
2017-11-23T22:21:30Z
2017-11-26T15:04:04Z
2017-11-26T15:04:04Z
2017-11-26T15:07:25Z
CI: temp skip geopandas downstream tests (GH18456)
diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index 0f0abd8cd3400..1ec25bc8bb295 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -92,6 +92,7 @@ def test_pandas_datareader(): pandas_datareader.get_data_google('AAPL') +@pytest.mark.skip(reason="import issue with fiona GH18456") def test_geopandas(): geopandas = import_module('geopandas') # noqa
xref https://github.com/pandas-dev/pandas/issues/18456
https://api.github.com/repos/pandas-dev/pandas/pulls/18457
2017-11-23T21:45:44Z
2017-11-23T21:46:10Z
2017-11-23T21:46:10Z
2017-11-23T21:46:15Z
Remove unused from datetime.pxd, check for fastpath in ensure_datetime64ns
diff --git a/pandas/_libs/src/datetime.pxd b/pandas/_libs/src/datetime.pxd index 3fc3625a06634..0624779e50497 100644 --- a/pandas/_libs/src/datetime.pxd +++ b/pandas/_libs/src/datetime.pxd @@ -5,7 +5,6 @@ from cpython cimport PyUnicode_Check, PyUnicode_AsASCIIString cdef extern from "numpy/ndarrayobject.h": - ctypedef int64_t npy_timedelta ctypedef int64_t npy_datetime ctypedef enum NPY_CASTING: @@ -15,15 +14,10 @@ cdef extern from "numpy/ndarrayobject.h": NPY_SAME_KIND_CASTING NPY_UNSAFE_CASTING -cdef extern from "numpy_helper.h": - npy_datetime get_datetime64_value(object o) - npy_timedelta get_timedelta64_value(object o) - cdef extern from "numpy/npy_common.h": ctypedef unsigned char npy_bool cdef extern from "datetime/np_datetime.h": - ctypedef enum PANDAS_DATETIMEUNIT: PANDAS_FR_Y PANDAS_FR_M @@ -44,20 +38,12 @@ cdef extern from "datetime/np_datetime.h": npy_int64 year npy_int32 month, day, hour, min, sec, us, ps, as - npy_datetime pandas_datetimestruct_to_datetime( - PANDAS_DATETIMEUNIT fr, pandas_datetimestruct *d) nogil - void pandas_datetime_to_datetimestruct(npy_datetime val, PANDAS_DATETIMEUNIT fr, pandas_datetimestruct *result) nogil - int days_per_month_table[2][12] - int dayofweek(int y, int m, int d) nogil - int is_leapyear(int64_t year) nogil - PANDAS_DATETIMEUNIT get_datetime64_unit(object o) cdef extern from "datetime/np_datetime_strings.h": - int parse_iso_8601_datetime(char *str, int len, PANDAS_DATETIMEUNIT unit, NPY_CASTING casting, pandas_datetimestruct *out, diff --git a/pandas/_libs/src/numpy_helper.h b/pandas/_libs/src/numpy_helper.h index ad683459ad878..8a9a05723d9fe 100644 --- a/pandas/_libs/src/numpy_helper.h +++ b/pandas/_libs/src/numpy_helper.h @@ -18,14 +18,6 @@ The full license is in the LICENSE file, distributed with this software. PANDAS_INLINE npy_int64 get_nat(void) { return NPY_MIN_INT64; } -PANDAS_INLINE npy_datetime get_datetime64_value(PyObject* obj) { - return ((PyDatetimeScalarObject*)obj)->obval; -} - -PANDAS_INLINE npy_timedelta get_timedelta64_value(PyObject* obj) { - return ((PyTimedeltaScalarObject*)obj)->obval; -} - PANDAS_INLINE int is_integer_object(PyObject* obj) { return (!PyBool_Check(obj)) && PyArray_IsIntegerScalar(obj); } diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index 16e88bcaeea3e..f58ad0a86d106 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -104,13 +104,16 @@ def ensure_datetime64ns(ndarray arr): return result unit = get_datetime64_unit(arr.flat[0]) - for i in range(n): - if ivalues[i] != NPY_NAT: - pandas_datetime_to_datetimestruct(ivalues[i], unit, &dts) - iresult[i] = dtstruct_to_dt64(&dts) - check_dts_bounds(&dts) - else: - iresult[i] = NPY_NAT + if unit == PANDAS_FR_ns: + result = arr + else: + for i in range(n): + if ivalues[i] != NPY_NAT: + pandas_datetime_to_datetimestruct(ivalues[i], unit, &dts) + iresult[i] = dtstruct_to_dt64(&dts) + check_dts_bounds(&dts) + else: + iresult[i] = NPY_NAT return result
Still a hodgepodge, but a somewhat smaller hodgepodge.
https://api.github.com/repos/pandas-dev/pandas/pulls/18453
2017-11-23T16:59:55Z
2017-11-24T20:05:55Z
2017-11-24T20:05:55Z
2017-11-24T20:33:55Z
CLN: ASV binary ops benchmark
diff --git a/asv_bench/benchmarks/binary_ops.py b/asv_bench/benchmarks/binary_ops.py index 0ca21b929ea17..429965c06cb48 100644 --- a/asv_bench/benchmarks/binary_ops.py +++ b/asv_bench/benchmarks/binary_ops.py @@ -1,4 +1,5 @@ -from .pandas_vb_common import * +import numpy as np +from pandas import DataFrame, Series, date_range try: import pandas.core.computation.expressions as expr except ImportError: @@ -6,12 +7,14 @@ class Ops(object): + goal_time = 0.2 params = [[True, False], ['default', 1]] param_names = ['use_numexpr', 'threads'] def setup(self, use_numexpr, threads): + np.random.seed(1234) self.df = DataFrame(np.random.randn(20000, 100)) self.df2 = DataFrame(np.random.randn(20000, 100)) @@ -20,18 +23,17 @@ def setup(self, use_numexpr, threads): if not use_numexpr: expr.set_use_numexpr(False) - def time_frame_add(self, use_numexpr, threads): - (self.df + self.df2) + self.df + self.df2 def time_frame_mult(self, use_numexpr, threads): - (self.df * self.df2) + self.df * self.df2 def time_frame_multi_and(self, use_numexpr, threads): - self.df[((self.df > 0) & (self.df2 > 0))] + self.df[(self.df > 0) & (self.df2 > 0)] def time_frame_comparison(self, use_numexpr, threads): - (self.df > self.df2) + self.df > self.df2 def teardown(self, use_numexpr, threads): expr.set_use_numexpr(True) @@ -39,75 +41,70 @@ def teardown(self, use_numexpr, threads): class Ops2(object): + goal_time = 0.2 def setup(self): - self.df = DataFrame(np.random.randn(1000, 1000)) - self.df2 = DataFrame(np.random.randn(1000, 1000)) + N = 10**3 + np.random.seed(1234) + self.df = DataFrame(np.random.randn(N, N)) + self.df2 = DataFrame(np.random.randn(N, N)) - self.df_int = DataFrame( - np.random.random_integers(np.iinfo(np.int16).min, - np.iinfo(np.int16).max, - size=(1000, 1000))) - self.df2_int = DataFrame( - np.random.random_integers(np.iinfo(np.int16).min, - np.iinfo(np.int16).max, - size=(1000, 1000))) + self.df_int = DataFrame(np.random.randint(np.iinfo(np.int16).min, + np.iinfo(np.int16).max, + size=(N, N))) + self.df2_int = DataFrame(np.random.randint(np.iinfo(np.int16).min, + np.iinfo(np.int16).max, + size=(N, N))) - ## Division + # Division def time_frame_float_div(self): - (self.df // self.df2) + self.df // self.df2 def time_frame_float_div_by_zero(self): - (self.df / 0) + self.df / 0 def time_frame_float_floor_by_zero(self): - (self.df // 0) + self.df // 0 def time_frame_int_div_by_zero(self): - (self.df_int / 0) + self.df_int / 0 - ## Modulo + # Modulo def time_frame_int_mod(self): - (self.df / self.df2) + self.df_int % self.df2_int def time_frame_float_mod(self): - (self.df / self.df2) + self.df % self.df2 class Timeseries(object): + goal_time = 0.2 - def setup(self): - self.N = 1000000 + params = [None, 'US/Eastern'] + param_names = ['tz'] + + def setup(self, tz): + self.N = 10**6 self.halfway = ((self.N // 2) - 1) - self.s = Series(date_range('20010101', periods=self.N, freq='T')) + self.s = Series(date_range('20010101', periods=self.N, freq='T', + tz=tz)) self.ts = self.s[self.halfway] - self.s2 = Series(date_range('20010101', periods=self.N, freq='s')) + self.s2 = Series(date_range('20010101', periods=self.N, freq='s', + tz=tz)) - def time_series_timestamp_compare(self): - (self.s <= self.ts) + def time_series_timestamp_compare(self, tz): + self.s <= self.ts - def time_timestamp_series_compare(self): - (self.ts >= self.s) + def time_timestamp_series_compare(self, tz): + self.ts >= self.s - def time_timestamp_ops_diff1(self): + def time_timestamp_ops_diff(self, tz): self.s2.diff() - def time_timestamp_ops_diff2(self): - (self.s - self.s.shift()) - - - -class TimeseriesTZ(Timeseries): - - def setup(self): - self.N = 1000000 - self.halfway = ((self.N // 2) - 1) - self.s = Series(date_range('20010101', periods=self.N, freq='T', tz='US/Eastern')) - self.ts = self.s[self.halfway] - - self.s2 = Series(date_range('20010101', periods=self.N, freq='s', tz='US/Eastern')) + def time_timestamp_ops_diff_with_shift(self, tz): + self.s - self.s.shift()
- Utilized `params` of timezones in the `Timeseries` class instead of creating a subclass of `TimeseriesTZ` - Division was being tested instead of modulo in `time_frame_int_mod` and `time_frame_float_mod` - Added `np.random.seed(1234)` in setup classes where random data is created xref #8144 - Renamed `time_timestamp_ops_diff2` to `time_timestamp_ops_diff_with_shift` - Replaced the depreciated `np.random.random_integers` with `np.random.randint` - Ran flake8 and replaced star imports ``` asv run -q -b ^binary_ops [ 0.00%] ·· Benchmarking conda-py3.6-Cython-matplotlib-numexpr-numpy-openpyxl-pytables-pytest-scipy-sqlalchemy-xlrd-xlsxwriter-xlwt [ 7.14%] ··· Running binary_ops.Ops.time_frame_add 46.1ms;... [ 14.29%] ··· Running binary_ops.Ops.time_frame_comparison 16.5ms;... [ 21.43%] ··· Running binary_ops.Ops.time_frame_mult 55.3ms;... [ 28.57%] ··· Running binary_ops.Ops.time_frame_multi_and 126ms;... [ 35.71%] ··· Running binary_ops.Ops2.time_frame_float_div 73.0ms [ 42.86%] ··· Running binary_ops.Ops2.time_frame_float_div_by_zero 80.7ms [ 50.00%] ··· Running binary_ops.Ops2.time_frame_float_floor_by_zero 83.9ms [ 57.14%] ··· Running binary_ops.Ops2.time_frame_float_mod 25.3ms [ 64.29%] ··· Running binary_ops.Ops2.time_frame_int_div_by_zero 97.2ms [ 71.43%] ··· Running binary_ops.Ops2.time_frame_int_mod 46.1ms [ 78.57%] ··· Running binary_ops.Timeseries.time_series_timestamp_compare 5.40ms;... [ 85.71%] ··· Running binary_ops.Timeseries.time_timestamp_ops_diff 42.8ms;... [ 92.86%] ··· Running binary_ops.Timeseries.time_timestamp_ops_diff_with_shift 157ms;... [100.00%] ··· Running binary_ops.Timeseries.time_timestamp_series_compare 5.55ms;... ```
https://api.github.com/repos/pandas-dev/pandas/pulls/18444
2017-11-23T03:46:09Z
2017-11-25T14:37:53Z
2017-11-25T14:37:53Z
2017-12-20T02:04:44Z
Cross off a few tslibs-TODOs
diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 956aeaf39b021..2ec4b5cf19b72 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -929,19 +929,6 @@ def write_csv_rows(list data, ndarray data_index, # ------------------------------------------------------------------------------ # Groupby-related functions -@cython.boundscheck(False) -def arrmap(ndarray[object] index, object func): - cdef int length = index.shape[0] - cdef int i = 0 - - cdef ndarray[object] result = np.empty(length, dtype=np.object_) - - for i from 0 <= i < length: - result[i] = func(index[i]) - - return result - - @cython.wraparound(False) @cython.boundscheck(False) def is_lexsorted(list list_of_arrays): diff --git a/pandas/_libs/period.pyx b/pandas/_libs/period.pyx index d09459898321e..2b09e9376bd3d 100644 --- a/pandas/_libs/period.pyx +++ b/pandas/_libs/period.pyx @@ -559,7 +559,6 @@ cdef class _Period(object): int64_t ordinal object freq - _comparables = ['name', 'freqstr'] _typ = 'period' def __cinit__(self, ordinal, freq): diff --git a/pandas/_libs/src/datetime/np_datetime.c b/pandas/_libs/src/datetime/np_datetime.c index 7278cbaff86ca..3c63f42f14b83 100644 --- a/pandas/_libs/src/datetime/np_datetime.c +++ b/pandas/_libs/src/datetime/np_datetime.c @@ -564,18 +564,15 @@ void pandas_datetime_to_datetimestruct(npy_datetime val, PANDAS_DATETIMEUNIT fr, void pandas_timedelta_to_timedeltastruct(npy_timedelta val, PANDAS_DATETIMEUNIT fr, - pandas_timedeltastruct *result) { + pandas_timedeltastruct *result) { pandas_datetime_metadata meta; meta.base = fr; - meta.num - 1; + meta.num = 1; convert_timedelta_to_timedeltastruct(&meta, val, result); } -PANDAS_DATETIMEUNIT get_datetime64_unit(PyObject *obj) { - return (PANDAS_DATETIMEUNIT)((PyDatetimeScalarObject *)obj)->obmeta.base; -} /* * Converts a datetime from a datetimestruct to a datetime based @@ -1001,7 +998,6 @@ int convert_datetime_to_datetimestruct(pandas_datetime_metadata *meta, int convert_timedelta_to_timedeltastruct(pandas_timedelta_metadata *meta, npy_timedelta td, pandas_timedeltastruct *out) { - npy_int64 perday; npy_int64 frac; npy_int64 sfrac; npy_int64 ifrac; @@ -1016,11 +1012,11 @@ int convert_timedelta_to_timedeltastruct(pandas_timedelta_metadata *meta, // put frac in seconds if (td < 0 && td % (1000LL * 1000LL * 1000LL) != 0) - frac = td / (1000LL * 1000LL * 1000LL) - 1; + frac = td / (1000LL * 1000LL * 1000LL) - 1; else frac = td / (1000LL * 1000LL * 1000LL); - if (frac < 0) { + if (frac < 0) { sign = -1; // even fraction @@ -1030,66 +1026,66 @@ int convert_timedelta_to_timedeltastruct(pandas_timedelta_metadata *meta, } else { frac = -frac; } - } else { + } else { sign = 1; out->days = 0; - } + } - if (frac >= 86400) { + if (frac >= 86400) { out->days += frac / 86400LL; frac -= out->days * 86400LL; - } + } - if (frac >= 3600) { + if (frac >= 3600) { out->hrs = frac / 3600LL; frac -= out->hrs * 3600LL; - } else { + } else { out->hrs = 0; - } + } - if (frac >= 60) { + if (frac >= 60) { out->min = frac / 60LL; frac -= out->min * 60LL; - } else { + } else { out->min = 0; - } + } - if (frac >= 0) { + if (frac >= 0) { out->sec = frac; frac -= out->sec; - } else { + } else { out->sec = 0; - } + } - sfrac = (out->hrs * 3600LL + out->min * 60LL - + out->sec) * (1000LL * 1000LL * 1000LL); + sfrac = (out->hrs * 3600LL + out->min * 60LL + + out->sec) * (1000LL * 1000LL * 1000LL); - if (sign < 0) + if (sign < 0) out->days = -out->days; - ifrac = td - (out->days * DAY_NS + sfrac); + ifrac = td - (out->days * DAY_NS + sfrac); - if (ifrac != 0) { + if (ifrac != 0) { out->ms = ifrac / (1000LL * 1000LL); ifrac -= out->ms * 1000LL * 1000LL; out->us = ifrac / 1000LL; ifrac -= out->us * 1000LL; out->ns = ifrac; - } else { + } else { out->ms = 0; out->us = 0; out->ns = 0; - } + } - out->seconds = out->hrs * 3600 + out->min * 60 + out->sec; - out->microseconds = out->ms * 1000 + out->us; - out->nanoseconds = out->ns; - break; + out->seconds = out->hrs * 3600 + out->min * 60 + out->sec; + out->microseconds = out->ms * 1000 + out->us; + out->nanoseconds = out->ns; + break; default: PyErr_SetString(PyExc_RuntimeError, - "NumPy datetime metadata is corrupted with invalid " - "base unit"); + "NumPy timedelta metadata is corrupted with " + "invalid base unit"); return -1; } diff --git a/pandas/_libs/src/datetime/np_datetime.h b/pandas/_libs/src/datetime/np_datetime.h index c51a4bddac82f..7ee7e1e99a704 100644 --- a/pandas/_libs/src/datetime/np_datetime.h +++ b/pandas/_libs/src/datetime/np_datetime.h @@ -148,7 +148,4 @@ convert_timedelta_to_timedeltastruct(pandas_timedelta_metadata *meta, pandas_timedeltastruct *out); -PANDAS_DATETIMEUNIT get_datetime64_unit(PyObject *obj); - - #endif // PANDAS__LIBS_SRC_DATETIME_NP_DATETIME_H_ diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 2c43bed4ad053..6d8cf39114f6f 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -60,7 +60,7 @@ from tslibs.conversion cimport (tz_convert_single, _TSObject, from tslibs.conversion import tz_convert_single from tslibs.nattype import NaT, nat_strings, iNaT -from tslibs.nattype cimport _checknull_with_nat, NPY_NAT +from tslibs.nattype cimport checknull_with_nat, NPY_NAT from tslibs.timestamps cimport (create_timestamp_from_ts, _NS_UPPER_BOUND, _NS_LOWER_BOUND) @@ -409,7 +409,7 @@ cpdef array_with_unit_to_datetime(ndarray values, unit, errors='coerce'): for i in range(n): val = values[i] - if _checknull_with_nat(val): + if checknull_with_nat(val): iresult[i] = NPY_NAT elif is_integer_object(val) or is_float_object(val): @@ -475,7 +475,7 @@ cpdef array_with_unit_to_datetime(ndarray values, unit, errors='coerce'): for i in range(n): val = values[i] - if _checknull_with_nat(val): + if checknull_with_nat(val): oresult[i] = NaT elif is_integer_object(val) or is_float_object(val): @@ -526,7 +526,7 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', for i in range(n): val = values[i] - if _checknull_with_nat(val): + if checknull_with_nat(val): iresult[i] = NPY_NAT elif PyDateTime_Check(val): @@ -686,7 +686,7 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', val = values[i] # set as nan except if its a NaT - if _checknull_with_nat(val): + if checknull_with_nat(val): if PyFloat_Check(val): oresult[i] = np.nan else: @@ -704,7 +704,7 @@ cpdef array_to_datetime(ndarray[object] values, errors='raise', for i in range(n): val = values[i] - if _checknull_with_nat(val): + if checknull_with_nat(val): oresult[i] = val elif is_string_object(val): diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index f58ad0a86d106..7f3cc0a7e81dd 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -40,7 +40,7 @@ from timezones cimport ( from parsing import parse_datetime_string from nattype import nat_strings, NaT -from nattype cimport NPY_NAT, _checknull_with_nat +from nattype cimport NPY_NAT, checknull_with_nat # ---------------------------------------------------------------------- # Constants @@ -143,7 +143,7 @@ def datetime_to_datetime64(ndarray[object] values): iresult = result.view('i8') for i in range(n): val = values[i] - if _checknull_with_nat(val): + if checknull_with_nat(val): iresult[i] = NPY_NAT elif PyDateTime_Check(val): if val.tzinfo is not None: diff --git a/pandas/_libs/tslibs/nattype.pxd b/pandas/_libs/tslibs/nattype.pxd index 34fa1e70305e7..96e02142d501b 100644 --- a/pandas/_libs/tslibs/nattype.pxd +++ b/pandas/_libs/tslibs/nattype.pxd @@ -6,4 +6,4 @@ cdef int64_t NPY_NAT cdef bint _nat_scalar_rules[6] -cdef bint _checknull_with_nat(object val) +cdef bint checknull_with_nat(object val) diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index d2f6006b41f65..2e7b861b24fa8 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -572,7 +572,7 @@ NaT = NaTType() # ---------------------------------------------------------------------- -cdef inline bint _checknull_with_nat(object val): +cdef inline bint checknull_with_nat(object val): """ utility to check if a value is a nat or not """ return val is None or ( PyFloat_Check(val) and val != val) or val is NaT diff --git a/pandas/_libs/tslibs/strptime.pyx b/pandas/_libs/tslibs/strptime.pyx index 439cc21a360c7..65594de586bac 100644 --- a/pandas/_libs/tslibs/strptime.pyx +++ b/pandas/_libs/tslibs/strptime.pyx @@ -38,7 +38,7 @@ from np_datetime cimport (check_dts_bounds, from util cimport is_string_object -from nattype cimport _checknull_with_nat, NPY_NAT +from nattype cimport checknull_with_nat, NPY_NAT from nattype import nat_strings @@ -142,7 +142,7 @@ def array_strptime(ndarray[object] values, object fmt, iresult[i] = NPY_NAT continue else: - if _checknull_with_nat(val): + if checknull_with_nat(val): iresult[i] = NPY_NAT continue else: diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 6ea30642625fe..b37e5dc620260 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -30,7 +30,7 @@ from np_datetime cimport (cmp_scalar, reverse_ops, td64_to_tdstruct, pandas_timedeltastruct) from nattype import nat_strings, NaT -from nattype cimport _checknull_with_nat, NPY_NAT +from nattype cimport checknull_with_nat, NPY_NAT # ---------------------------------------------------------------------- # Constants @@ -111,7 +111,7 @@ cpdef convert_to_timedelta64(object ts, object unit): # kludgy here until we have a timedelta scalar # handle the numpy < 1.7 case """ - if _checknull_with_nat(ts): + if checknull_with_nat(ts): return np.timedelta64(NPY_NAT) elif isinstance(ts, Timedelta): # already in the proper format @@ -443,7 +443,7 @@ cdef inline timedelta_from_spec(object number, object frac, object unit): cdef bint _validate_ops_compat(other): # return True if we are compat with operating - if _checknull_with_nat(other): + if checknull_with_nat(other): return True elif PyDelta_Check(other) or is_timedelta64_object(other): return True @@ -837,7 +837,7 @@ class Timedelta(_Timedelta): elif is_integer_object(value) or is_float_object(value): # unit=None is de-facto 'ns' value = convert_to_timedelta64(value, unit) - elif _checknull_with_nat(value): + elif checknull_with_nat(value): return NaT else: raise ValueError(
This is a hodge-podge addressing a few of the items in #17652. Individual commits should be item-specific(ish). - remove unused lib.arrmap - de-privatize _checknull_with_nat - fix a couple of C warnings caused by timedelta_struct - remove Period._comparables
https://api.github.com/repos/pandas-dev/pandas/pulls/18443
2017-11-23T03:42:00Z
2017-11-25T15:10:24Z
2017-11-25T15:10:24Z
2017-12-08T19:40:01Z
CLN: ASV attrs_caching benchmark
diff --git a/asv_bench/benchmarks/attrs_caching.py b/asv_bench/benchmarks/attrs_caching.py index b7610037bed4d..3c091be7a8424 100644 --- a/asv_bench/benchmarks/attrs_caching.py +++ b/asv_bench/benchmarks/attrs_caching.py @@ -1,4 +1,5 @@ -from .pandas_vb_common import * +import numpy as np +from pandas import DataFrame try: from pandas.util import cache_readonly @@ -7,9 +8,11 @@ class DataFrameAttributes(object): + goal_time = 0.2 def setup(self): + np.random.seed(1234) self.df = DataFrame(np.random.randn(10, 6)) self.cur_index = self.df.index @@ -21,6 +24,7 @@ def time_set_index(self): class CacheReadonly(object): + goal_time = 0.2 def setup(self):
- Added `np.random.seed(1234)` in setup classes where random data is created xref #8144 - Ran flake 8 and replaced star imports (with pep8 in mind, I think we should avoid `from .pandas_vb_common import *`) ``` $asv run -q -b ^attrs_caching [ 33.33%] ··· Running attrs_caching.CacheReadonly.time_cache_readonly 9.12μs [ 66.67%] ··· Running attrs_caching.DataFrameAttributes.time_get_index 14.5μs [100.00%] ··· Running attrs_caching.DataFrameAttributes.time_set_index 27.3μs ```
https://api.github.com/repos/pandas-dev/pandas/pulls/18441
2017-11-23T02:53:19Z
2017-11-23T15:54:43Z
2017-11-23T15:54:43Z
2017-11-24T00:41:33Z
BUG: in Python3 MultiIndex.from_tuples cannot take "zipped" tuples
diff --git a/doc/source/whatsnew/v0.22.0.txt b/doc/source/whatsnew/v0.22.0.txt index 4bdff1355874e..a32035d0d906f 100644 --- a/doc/source/whatsnew/v0.22.0.txt +++ b/doc/source/whatsnew/v0.22.0.txt @@ -140,6 +140,7 @@ Indexing - Bug in :func:`Series.truncate` which raises ``TypeError`` with a monotonic ``PeriodIndex`` (:issue:`17717`) - Bug in :func:`DataFrame.groupby` where tuples were interpreted as lists of keys rather than as keys (:issue:`17979`, :issue:`18249`) - Bug in :func:`MultiIndex.remove_unused_levels`` which would fill nan values (:issue:`18417`) +- Bug in :func:`MultiIndex.from_tuples`` which would fail to take zipped tuples in python3 (:issue:`18434`) - Bug in :class:`IntervalIndex` where empty and purely NA data was constructed inconsistently depending on the construction method (:issue:`18421`) - diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 81d892fba0fe2..456999b94c523 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1162,6 +1162,11 @@ def from_arrays(cls, arrays, sortorder=None, names=None): MultiIndex.from_product : Make a MultiIndex from cartesian product of iterables """ + if not is_list_like(arrays): + raise TypeError("Input must be a list / sequence of array-likes.") + elif is_iterator(arrays): + arrays = list(arrays) + # Check if lengths of all arrays are equal or not, # raise ValueError, if not for i in range(1, len(arrays)): @@ -1206,6 +1211,11 @@ def from_tuples(cls, tuples, sortorder=None, names=None): MultiIndex.from_product : Make a MultiIndex from cartesian product of iterables """ + if not is_list_like(tuples): + raise TypeError('Input must be a list / sequence of tuple-likes.') + elif is_iterator(tuples): + tuples = list(tuples) + if len(tuples) == 0: if names is None: msg = 'Cannot infer number of levels from empty list' @@ -1260,6 +1270,11 @@ def from_product(cls, iterables, sortorder=None, names=None): from pandas.core.categorical import _factorize_from_iterables from pandas.core.reshape.util import cartesian_product + if not is_list_like(iterables): + raise TypeError("Input must be a list / sequence of iterables.") + elif is_iterator(iterables): + iterables = list(iterables) + labels, levels = _factorize_from_iterables(iterables) labels = cartesian_product(labels) return MultiIndex(levels, labels, sortorder=sortorder, names=names) diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 2f8c27f1abb7d..5c2a0254b072b 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -672,8 +672,9 @@ def test_from_arrays(self): for lev, lab in zip(self.index.levels, self.index.labels): arrays.append(np.asarray(lev).take(lab)) - result = MultiIndex.from_arrays(arrays) - assert list(result) == list(self.index) + # list of arrays as input + result = MultiIndex.from_arrays(arrays, names=self.index.names) + tm.assert_index_equal(result, self.index) # infer correctly result = MultiIndex.from_arrays([[pd.NaT, Timestamp('20130101')], @@ -681,6 +682,21 @@ def test_from_arrays(self): assert result.levels[0].equals(Index([Timestamp('20130101')])) assert result.levels[1].equals(Index(['a', 'b'])) + def test_from_arrays_iterator(self): + # GH 18434 + arrays = [] + for lev, lab in zip(self.index.levels, self.index.labels): + arrays.append(np.asarray(lev).take(lab)) + + # iterator as input + result = MultiIndex.from_arrays(iter(arrays), names=self.index.names) + tm.assert_index_equal(result, self.index) + + # invalid iterator input + with tm.assert_raises_regex( + TypeError, "Input must be a list / sequence of array-likes."): + MultiIndex.from_arrays(0) + def test_from_arrays_index_series_datetimetz(self): idx1 = pd.date_range('2015-01-01 10:00', freq='D', periods=3, tz='US/Eastern') @@ -825,7 +841,25 @@ def test_from_product(self): expected = MultiIndex.from_tuples(tuples, names=names) tm.assert_index_equal(result, expected) - assert result.names == names + + def test_from_product_iterator(self): + # GH 18434 + first = ['foo', 'bar', 'buz'] + second = ['a', 'b', 'c'] + names = ['first', 'second'] + tuples = [('foo', 'a'), ('foo', 'b'), ('foo', 'c'), ('bar', 'a'), + ('bar', 'b'), ('bar', 'c'), ('buz', 'a'), ('buz', 'b'), + ('buz', 'c')] + expected = MultiIndex.from_tuples(tuples, names=names) + + # iterator as input + result = MultiIndex.from_product(iter([first, second]), names=names) + tm.assert_index_equal(result, expected) + + # Invalid non-iterable input + with tm.assert_raises_regex( + TypeError, "Input must be a list / sequence of iterables."): + MultiIndex.from_product(0) def test_from_product_empty(self): # 0 levels @@ -1725,8 +1759,28 @@ def test_from_tuples(self): 'from empty list', MultiIndex.from_tuples, []) - idx = MultiIndex.from_tuples(((1, 2), (3, 4)), names=['a', 'b']) - assert len(idx) == 2 + expected = MultiIndex(levels=[[1, 3], [2, 4]], + labels=[[0, 1], [0, 1]], + names=['a', 'b']) + + # input tuples + result = MultiIndex.from_tuples(((1, 2), (3, 4)), names=['a', 'b']) + tm.assert_index_equal(result, expected) + + def test_from_tuples_iterator(self): + # GH 18434 + # input iterator for tuples + expected = MultiIndex(levels=[[1, 3], [2, 4]], + labels=[[0, 1], [0, 1]], + names=['a', 'b']) + + result = MultiIndex.from_tuples(zip([1, 3], [2, 4]), names=['a', 'b']) + tm.assert_index_equal(result, expected) + + # input non-iterables + with tm.assert_raises_regex( + TypeError, 'Input must be a list / sequence of tuple-likes.'): + MultiIndex.from_tuples(0) def test_from_tuples_empty(self): # GH 16777
MultiIndex.from_tuples accept zipped tuples in python 3. Ensures compatibility between 2 and 3. - [x] closes #18434 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/18440
2017-11-23T02:43:00Z
2017-11-25T20:56:49Z
2017-11-25T20:56:49Z
2017-11-25T22:13:05Z
REF: smarter NaN handling in remove_unused_levels()
diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index cc99505b53bf5..81d892fba0fe2 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1365,31 +1365,29 @@ def remove_unused_levels(self): new_labels = [] changed = False - for idx, (lev, lab) in enumerate(zip(self.levels, self.labels)): - na_idxs = np.where(lab == -1)[0] - - if len(na_idxs): - lab = np.delete(lab, na_idxs) + for lev, lab in zip(self.levels, self.labels): uniques = algos.unique(lab) + na_idx = np.where(uniques == -1)[0] # nothing unused - if len(uniques) != len(lev): + if len(uniques) != len(lev) + len(na_idx): changed = True + if len(na_idx): + # Just ensure that -1 is in first position: + uniques[[0, na_idx[0]]] = uniques[[na_idx[0], 0]] + # labels get mapped from uniques to 0:len(uniques) - label_mapping = np.zeros(len(lev)) - label_mapping[uniques] = np.arange(len(uniques)) + # -1 (if present) is mapped to last position + label_mapping = np.zeros(len(lev) + len(na_idx)) + # ... and reassigned value -1: + label_mapping[uniques] = np.arange(len(uniques)) - len(na_idx) lab = label_mapping[lab] # new levels are simple - lev = lev.take(uniques) - - if len(na_idxs): - lab = np.insert(lab, na_idxs - np.arange(len(na_idxs)), -1) - else: - lab = self.labels[idx] + lev = lev.take(uniques[len(na_idx):]) new_levels.append(lev) new_labels.append(lab)
- [x] tests passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Sorry for the bad timing @jreback , only after you merged #18426 this simpler way to proceed came to my mind.
https://api.github.com/repos/pandas-dev/pandas/pulls/18438
2017-11-23T00:05:02Z
2017-11-23T15:47:48Z
2017-11-23T15:47:48Z
2017-11-23T21:41:28Z
DOC: Remove obsolete reference to CONTRIBUTING.md generation
diff --git a/doc/source/development/contributing_documentation.rst b/doc/source/development/contributing_documentation.rst index 39bc582511148..583eecf1ca8ab 100644 --- a/doc/source/development/contributing_documentation.rst +++ b/doc/source/development/contributing_documentation.rst @@ -89,16 +89,6 @@ Some other important things to know about the docs: ``doc/source/reference``, else Sphinx will emit a warning. -.. note:: - - The ``.rst`` files are used to automatically generate Markdown and HTML versions - of the docs. For this reason, please do not edit ``CONTRIBUTING.md`` directly, - but instead make any changes to ``doc/source/development/contributing.rst``. Then, to - generate ``CONTRIBUTING.md``, use `pandoc <https://johnmacfarlane.net/pandoc/>`_ - with the following command:: - - pandoc doc/source/development/contributing.rst -t markdown_github > CONTRIBUTING.md - The utility script ``scripts/validate_docstrings.py`` can be used to get a csv summary of the API documentation. And also validate common errors in the docstring of a specific class, function or method. The summary also compares the list of
It seems that a note was left over after https://github.com/pandas-dev/pandas/pull/45063 from the old CONTRIBUTING.md times ([still there in devdocs](https://pandas.pydata.org/docs/dev/development/contributing_documentation.html#about-the-pandas-documentation)). The note referred to generating the file from `contributing.rst` via pandoc, but that seems to no longer apply. Suspiciously these were also the only remaining hits for `git grep CONTRIBUTING`. Removal seems straightforward enough, but I ran pre-commit just in case.
https://api.github.com/repos/pandas-dev/pandas/pulls/45699
2022-01-29T20:54:19Z
2022-01-30T17:51:44Z
2022-01-30T17:51:44Z
2022-01-30T17:51:56Z
Simplify conditional branch in _read function in readers.py
diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py index ef693fcbd3720..5f93eef4fd977 100644 --- a/pandas/io/parsers/readers.py +++ b/pandas/io/parsers/readers.py @@ -542,13 +542,11 @@ def _read( """Generic reader of line files.""" # if we pass a date_parser and parse_dates=False, we should not parse the # dates GH#44366 - if ( - kwds.get("date_parser", None) is not None - and kwds.get("parse_dates", None) is None - ): - kwds["parse_dates"] = True - elif kwds.get("parse_dates", None) is None: - kwds["parse_dates"] = False + if kwds.get("parse_dates", None) is None: + if kwds.get("date_parser", None) is None: + kwds["parse_dates"] = False + else: + kwds["parse_dates"] = True # Extract some of the arguments (pass chunksize on). iterator = kwds.get("iterator", False) @@ -564,7 +562,7 @@ def _read( "The 'chunksize' option is not supported with the 'pyarrow' engine" ) else: - chunksize = validate_integer("chunksize", kwds.get("chunksize", None), 1) + chunksize = validate_integer("chunksize", chunksize, 1) nrows = kwds.get("nrows", None)
- [ ] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/45696
2022-01-29T17:36:34Z
2022-01-30T18:14:13Z
2022-01-30T18:14:13Z
2022-01-31T03:46:10Z
TST: Nan must not be converted to string using .loc
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 2e78fb8c44eee..49aa4d3d0dbf0 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -43,6 +43,22 @@ from pandas.tests.indexing.common import Base +@pytest.mark.parametrize( + "series, new_serie, expected_ser", + [ + [[np.nan, np.nan, "b"], ["a", np.nan, np.nan], [False, True, True]], + [[np.nan, "b"], ["a", np.nan], [False, True]], + ], +) +def test_not_change_nan_loc(series, new_serie, expected_ser): + # GH 28403 + df = DataFrame({"A": series}) + df["A"].loc[:] = new_serie + expected = DataFrame({"A": expected_ser}) + tm.assert_frame_equal(df.isna(), expected) + tm.assert_frame_equal(df.notna(), ~expected) + + class TestLoc(Base): def test_loc_getitem_int(self):
- [X] Closes #28403 - [X] tests added / passed - [X] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/45695
2022-01-29T17:10:34Z
2022-02-03T17:41:39Z
2022-02-03T17:41:38Z
2022-02-03T17:42:10Z
TST/CLN: organize SparseArray tests
diff --git a/pandas/tests/arrays/sparse/test_accessor.py b/pandas/tests/arrays/sparse/test_accessor.py index e45dbb393a8de..36af5d32ae461 100644 --- a/pandas/tests/arrays/sparse/test_accessor.py +++ b/pandas/tests/arrays/sparse/test_accessor.py @@ -14,13 +14,90 @@ class TestSeriesAccessor: - # TODO: collect other Series accessor tests def test_to_dense(self): - s = pd.Series([0, 1, 0, 10], dtype="Sparse[int64]") - result = s.sparse.to_dense() + ser = pd.Series([0, 1, 0, 10], dtype="Sparse[int64]") + result = ser.sparse.to_dense() expected = pd.Series([0, 1, 0, 10]) tm.assert_series_equal(result, expected) + @pytest.mark.parametrize("attr", ["npoints", "density", "fill_value", "sp_values"]) + def test_get_attributes(self, attr): + arr = SparseArray([0, 1]) + ser = pd.Series(arr) + + result = getattr(ser.sparse, attr) + expected = getattr(arr, attr) + assert result == expected + + @td.skip_if_no_scipy + def test_from_coo(self): + import scipy.sparse + + row = [0, 3, 1, 0] + col = [0, 3, 1, 2] + data = [4, 5, 7, 9] + # TODO(scipy#13585): Remove dtype when scipy is fixed + # https://github.com/scipy/scipy/issues/13585 + sp_array = scipy.sparse.coo_matrix((data, (row, col)), dtype="int") + result = pd.Series.sparse.from_coo(sp_array) + + index = pd.MultiIndex.from_arrays([[0, 0, 1, 3], [0, 2, 1, 3]]) + expected = pd.Series([4, 9, 7, 5], index=index, dtype="Sparse[int]") + tm.assert_series_equal(result, expected) + + @td.skip_if_no_scipy + @pytest.mark.parametrize( + "sort_labels, expected_rows, expected_cols, expected_values_pos", + [ + ( + False, + [("b", 2), ("a", 2), ("b", 1), ("a", 1)], + [("z", 1), ("z", 2), ("x", 2), ("z", 0)], + {1: (1, 0), 3: (3, 3)}, + ), + ( + True, + [("a", 1), ("a", 2), ("b", 1), ("b", 2)], + [("x", 2), ("z", 0), ("z", 1), ("z", 2)], + {1: (1, 2), 3: (0, 1)}, + ), + ], + ) + def test_to_coo( + self, sort_labels, expected_rows, expected_cols, expected_values_pos + ): + import scipy.sparse + + values = SparseArray([0, np.nan, 1, 0, None, 3], fill_value=0) + index = pd.MultiIndex.from_tuples( + [ + ("b", 2, "z", 1), + ("a", 2, "z", 2), + ("a", 2, "z", 1), + ("a", 2, "x", 2), + ("b", 1, "z", 1), + ("a", 1, "z", 0), + ] + ) + ss = pd.Series(values, index=index) + + expected_A = np.zeros((4, 4)) + for value, (row, col) in expected_values_pos.items(): + expected_A[row, col] = value + + A, rows, cols = ss.sparse.to_coo( + row_levels=(0, 1), column_levels=(2, 3), sort_labels=sort_labels + ) + assert isinstance(A, scipy.sparse.coo_matrix) + tm.assert_numpy_array_equal(A.toarray(), expected_A) + assert rows == expected_rows + assert cols == expected_cols + + def test_non_sparse_raises(self): + ser = pd.Series([1, 2, 3]) + with pytest.raises(AttributeError, match=".sparse"): + ser.sparse.density + class TestFrameAccessor: def test_accessor_raises(self): diff --git a/pandas/tests/arrays/sparse/test_arithmetics.py b/pandas/tests/arrays/sparse/test_arithmetics.py index 3db1ee9faad78..8f975e942db93 100644 --- a/pandas/tests/arrays/sparse/test_arithmetics.py +++ b/pandas/tests/arrays/sparse/test_arithmetics.py @@ -27,10 +27,6 @@ def mix(request): class TestSparseArrayArithmetics: - - _base = np.array - _klass = SparseArray - def _assert(self, a, b): # We have to use tm.assert_sp_array_equal. See GH #45126 tm.assert_numpy_array_equal(a, b) @@ -54,7 +50,7 @@ def _check_numeric_ops(self, a, b, a_dense, b_dense, mix: bool, op): self._assert(result, expected) def _check_bool_result(self, res): - assert isinstance(res, self._klass) + assert isinstance(res, SparseArray) assert isinstance(res.dtype, SparseDtype) assert res.dtype.subtype == np.bool_ assert isinstance(res.fill_value, bool) @@ -133,25 +129,25 @@ def test_float_scalar( mark = pytest.mark.xfail(raises=AssertionError, reason="GH#38172") request.node.add_marker(mark) - values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) + values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) - a = self._klass(values, kind=kind, fill_value=fill_value) + a = SparseArray(values, kind=kind, fill_value=fill_value) self._check_numeric_ops(a, scalar, values, scalar, mix, op) def test_float_scalar_comparison(self, kind): - values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) + values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) - a = self._klass(values, kind=kind) + a = SparseArray(values, kind=kind) self._check_comparison_ops(a, 1, values, 1) self._check_comparison_ops(a, 0, values, 0) self._check_comparison_ops(a, 3, values, 3) - a = self._klass(values, kind=kind, fill_value=0) + a = SparseArray(values, kind=kind, fill_value=0) self._check_comparison_ops(a, 1, values, 1) self._check_comparison_ops(a, 0, values, 0) self._check_comparison_ops(a, 3, values, 3) - a = self._klass(values, kind=kind, fill_value=2) + a = SparseArray(values, kind=kind, fill_value=2) self._check_comparison_ops(a, 1, values, 1) self._check_comparison_ops(a, 0, values, 0) self._check_comparison_ops(a, 3, values, 3) @@ -160,11 +156,11 @@ def test_float_same_index_without_nans(self, kind, mix, all_arithmetic_functions # when sp_index are the same op = all_arithmetic_functions - values = self._base([0.0, 1.0, 2.0, 6.0, 0.0, 0.0, 1.0, 2.0, 1.0, 0.0]) - rvalues = self._base([0.0, 2.0, 3.0, 4.0, 0.0, 0.0, 1.0, 3.0, 2.0, 0.0]) + values = np.array([0.0, 1.0, 2.0, 6.0, 0.0, 0.0, 1.0, 2.0, 1.0, 0.0]) + rvalues = np.array([0.0, 2.0, 3.0, 4.0, 0.0, 0.0, 1.0, 3.0, 2.0, 0.0]) - a = self._klass(values, kind=kind, fill_value=0) - b = self._klass(rvalues, kind=kind, fill_value=0) + a = SparseArray(values, kind=kind, fill_value=0) + b = SparseArray(rvalues, kind=kind, fill_value=0) self._check_numeric_ops(a, b, values, rvalues, mix, op) def test_float_same_index_with_nans( @@ -180,94 +176,94 @@ def test_float_same_index_with_nans( ): mark = pytest.mark.xfail(raises=AssertionError, reason="GH#38172") request.node.add_marker(mark) - values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) - rvalues = self._base([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan]) + values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) + rvalues = np.array([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan]) - a = self._klass(values, kind=kind) - b = self._klass(rvalues, kind=kind) + a = SparseArray(values, kind=kind) + b = SparseArray(rvalues, kind=kind) self._check_numeric_ops(a, b, values, rvalues, mix, op) def test_float_same_index_comparison(self, kind): # when sp_index are the same - values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) - rvalues = self._base([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan]) + values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) + rvalues = np.array([np.nan, 2, 3, 4, np.nan, 0, 1, 3, 2, np.nan]) - a = self._klass(values, kind=kind) - b = self._klass(rvalues, kind=kind) + a = SparseArray(values, kind=kind) + b = SparseArray(rvalues, kind=kind) self._check_comparison_ops(a, b, values, rvalues) - values = self._base([0.0, 1.0, 2.0, 6.0, 0.0, 0.0, 1.0, 2.0, 1.0, 0.0]) - rvalues = self._base([0.0, 2.0, 3.0, 4.0, 0.0, 0.0, 1.0, 3.0, 2.0, 0.0]) + values = np.array([0.0, 1.0, 2.0, 6.0, 0.0, 0.0, 1.0, 2.0, 1.0, 0.0]) + rvalues = np.array([0.0, 2.0, 3.0, 4.0, 0.0, 0.0, 1.0, 3.0, 2.0, 0.0]) - a = self._klass(values, kind=kind, fill_value=0) - b = self._klass(rvalues, kind=kind, fill_value=0) + a = SparseArray(values, kind=kind, fill_value=0) + b = SparseArray(rvalues, kind=kind, fill_value=0) self._check_comparison_ops(a, b, values, rvalues) def test_float_array(self, kind, mix, all_arithmetic_functions): op = all_arithmetic_functions - values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) - rvalues = self._base([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan]) + values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) + rvalues = np.array([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan]) - a = self._klass(values, kind=kind) - b = self._klass(rvalues, kind=kind) + a = SparseArray(values, kind=kind) + b = SparseArray(rvalues, kind=kind) self._check_numeric_ops(a, b, values, rvalues, mix, op) self._check_numeric_ops(a, b * 0, values, rvalues * 0, mix, op) - a = self._klass(values, kind=kind, fill_value=0) - b = self._klass(rvalues, kind=kind) + a = SparseArray(values, kind=kind, fill_value=0) + b = SparseArray(rvalues, kind=kind) self._check_numeric_ops(a, b, values, rvalues, mix, op) - a = self._klass(values, kind=kind, fill_value=0) - b = self._klass(rvalues, kind=kind, fill_value=0) + a = SparseArray(values, kind=kind, fill_value=0) + b = SparseArray(rvalues, kind=kind, fill_value=0) self._check_numeric_ops(a, b, values, rvalues, mix, op) - a = self._klass(values, kind=kind, fill_value=1) - b = self._klass(rvalues, kind=kind, fill_value=2) + a = SparseArray(values, kind=kind, fill_value=1) + b = SparseArray(rvalues, kind=kind, fill_value=2) self._check_numeric_ops(a, b, values, rvalues, mix, op) def test_float_array_different_kind(self, mix, all_arithmetic_functions): op = all_arithmetic_functions - values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) - rvalues = self._base([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan]) + values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) + rvalues = np.array([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan]) - a = self._klass(values, kind="integer") - b = self._klass(rvalues, kind="block") + a = SparseArray(values, kind="integer") + b = SparseArray(rvalues, kind="block") self._check_numeric_ops(a, b, values, rvalues, mix, op) self._check_numeric_ops(a, b * 0, values, rvalues * 0, mix, op) - a = self._klass(values, kind="integer", fill_value=0) - b = self._klass(rvalues, kind="block") + a = SparseArray(values, kind="integer", fill_value=0) + b = SparseArray(rvalues, kind="block") self._check_numeric_ops(a, b, values, rvalues, mix, op) - a = self._klass(values, kind="integer", fill_value=0) - b = self._klass(rvalues, kind="block", fill_value=0) + a = SparseArray(values, kind="integer", fill_value=0) + b = SparseArray(rvalues, kind="block", fill_value=0) self._check_numeric_ops(a, b, values, rvalues, mix, op) - a = self._klass(values, kind="integer", fill_value=1) - b = self._klass(rvalues, kind="block", fill_value=2) + a = SparseArray(values, kind="integer", fill_value=1) + b = SparseArray(rvalues, kind="block", fill_value=2) self._check_numeric_ops(a, b, values, rvalues, mix, op) def test_float_array_comparison(self, kind): - values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) - rvalues = self._base([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan]) + values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) + rvalues = np.array([2, np.nan, 2, 3, np.nan, 0, 1, 5, 2, np.nan]) - a = self._klass(values, kind=kind) - b = self._klass(rvalues, kind=kind) + a = SparseArray(values, kind=kind) + b = SparseArray(rvalues, kind=kind) self._check_comparison_ops(a, b, values, rvalues) self._check_comparison_ops(a, b * 0, values, rvalues * 0) - a = self._klass(values, kind=kind, fill_value=0) - b = self._klass(rvalues, kind=kind) + a = SparseArray(values, kind=kind, fill_value=0) + b = SparseArray(rvalues, kind=kind) self._check_comparison_ops(a, b, values, rvalues) - a = self._klass(values, kind=kind, fill_value=0) - b = self._klass(rvalues, kind=kind, fill_value=0) + a = SparseArray(values, kind=kind, fill_value=0) + b = SparseArray(rvalues, kind=kind, fill_value=0) self._check_comparison_ops(a, b, values, rvalues) - a = self._klass(values, kind=kind, fill_value=1) - b = self._klass(rvalues, kind=kind, fill_value=2) + a = SparseArray(values, kind=kind, fill_value=1) + b = SparseArray(rvalues, kind=kind, fill_value=2) self._check_comparison_ops(a, b, values, rvalues) def test_int_array(self, kind, mix, all_arithmetic_functions): @@ -276,33 +272,33 @@ def test_int_array(self, kind, mix, all_arithmetic_functions): # have to specify dtype explicitly until fixing GH 667 dtype = np.int64 - values = self._base([0, 1, 2, 0, 0, 0, 1, 2, 1, 0], dtype=dtype) - rvalues = self._base([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=dtype) + values = np.array([0, 1, 2, 0, 0, 0, 1, 2, 1, 0], dtype=dtype) + rvalues = np.array([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=dtype) - a = self._klass(values, dtype=dtype, kind=kind) + a = SparseArray(values, dtype=dtype, kind=kind) assert a.dtype == SparseDtype(dtype) - b = self._klass(rvalues, dtype=dtype, kind=kind) + b = SparseArray(rvalues, dtype=dtype, kind=kind) assert b.dtype == SparseDtype(dtype) self._check_numeric_ops(a, b, values, rvalues, mix, op) self._check_numeric_ops(a, b * 0, values, rvalues * 0, mix, op) - a = self._klass(values, fill_value=0, dtype=dtype, kind=kind) + a = SparseArray(values, fill_value=0, dtype=dtype, kind=kind) assert a.dtype == SparseDtype(dtype) - b = self._klass(rvalues, dtype=dtype, kind=kind) + b = SparseArray(rvalues, dtype=dtype, kind=kind) assert b.dtype == SparseDtype(dtype) self._check_numeric_ops(a, b, values, rvalues, mix, op) - a = self._klass(values, fill_value=0, dtype=dtype, kind=kind) + a = SparseArray(values, fill_value=0, dtype=dtype, kind=kind) assert a.dtype == SparseDtype(dtype) - b = self._klass(rvalues, fill_value=0, dtype=dtype, kind=kind) + b = SparseArray(rvalues, fill_value=0, dtype=dtype, kind=kind) assert b.dtype == SparseDtype(dtype) self._check_numeric_ops(a, b, values, rvalues, mix, op) - a = self._klass(values, fill_value=1, dtype=dtype, kind=kind) + a = SparseArray(values, fill_value=1, dtype=dtype, kind=kind) assert a.dtype == SparseDtype(dtype, fill_value=1) - b = self._klass(rvalues, fill_value=2, dtype=dtype, kind=kind) + b = SparseArray(rvalues, fill_value=2, dtype=dtype, kind=kind) assert b.dtype == SparseDtype(dtype, fill_value=2) self._check_numeric_ops(a, b, values, rvalues, mix, op) @@ -310,46 +306,46 @@ def test_int_array_comparison(self, kind): dtype = "int64" # int32 NI ATM - values = self._base([0, 1, 2, 0, 0, 0, 1, 2, 1, 0], dtype=dtype) - rvalues = self._base([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=dtype) + values = np.array([0, 1, 2, 0, 0, 0, 1, 2, 1, 0], dtype=dtype) + rvalues = np.array([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=dtype) - a = self._klass(values, dtype=dtype, kind=kind) - b = self._klass(rvalues, dtype=dtype, kind=kind) + a = SparseArray(values, dtype=dtype, kind=kind) + b = SparseArray(rvalues, dtype=dtype, kind=kind) self._check_comparison_ops(a, b, values, rvalues) self._check_comparison_ops(a, b * 0, values, rvalues * 0) - a = self._klass(values, dtype=dtype, kind=kind, fill_value=0) - b = self._klass(rvalues, dtype=dtype, kind=kind) + a = SparseArray(values, dtype=dtype, kind=kind, fill_value=0) + b = SparseArray(rvalues, dtype=dtype, kind=kind) self._check_comparison_ops(a, b, values, rvalues) - a = self._klass(values, dtype=dtype, kind=kind, fill_value=0) - b = self._klass(rvalues, dtype=dtype, kind=kind, fill_value=0) + a = SparseArray(values, dtype=dtype, kind=kind, fill_value=0) + b = SparseArray(rvalues, dtype=dtype, kind=kind, fill_value=0) self._check_comparison_ops(a, b, values, rvalues) - a = self._klass(values, dtype=dtype, kind=kind, fill_value=1) - b = self._klass(rvalues, dtype=dtype, kind=kind, fill_value=2) + a = SparseArray(values, dtype=dtype, kind=kind, fill_value=1) + b = SparseArray(rvalues, dtype=dtype, kind=kind, fill_value=2) self._check_comparison_ops(a, b, values, rvalues) @pytest.mark.parametrize("fill_value", [True, False, np.nan]) def test_bool_same_index(self, kind, fill_value): # GH 14000 # when sp_index are the same - values = self._base([True, False, True, True], dtype=np.bool_) - rvalues = self._base([True, False, True, True], dtype=np.bool_) + values = np.array([True, False, True, True], dtype=np.bool_) + rvalues = np.array([True, False, True, True], dtype=np.bool_) - a = self._klass(values, kind=kind, dtype=np.bool_, fill_value=fill_value) - b = self._klass(rvalues, kind=kind, dtype=np.bool_, fill_value=fill_value) + a = SparseArray(values, kind=kind, dtype=np.bool_, fill_value=fill_value) + b = SparseArray(rvalues, kind=kind, dtype=np.bool_, fill_value=fill_value) self._check_logical_ops(a, b, values, rvalues) @pytest.mark.parametrize("fill_value", [True, False, np.nan]) def test_bool_array_logical(self, kind, fill_value): # GH 14000 # when sp_index are the same - values = self._base([True, False, True, False, True, True], dtype=np.bool_) - rvalues = self._base([True, False, False, True, False, True], dtype=np.bool_) + values = np.array([True, False, True, False, True, True], dtype=np.bool_) + rvalues = np.array([True, False, False, True, False, True], dtype=np.bool_) - a = self._klass(values, kind=kind, dtype=np.bool_, fill_value=fill_value) - b = self._klass(rvalues, kind=kind, dtype=np.bool_, fill_value=fill_value) + a = SparseArray(values, kind=kind, dtype=np.bool_, fill_value=fill_value) + b = SparseArray(rvalues, kind=kind, dtype=np.bool_, fill_value=fill_value) self._check_logical_ops(a, b, values, rvalues) def test_mixed_array_float_int(self, kind, mix, all_arithmetic_functions, request): @@ -361,28 +357,28 @@ def test_mixed_array_float_int(self, kind, mix, all_arithmetic_functions, reques rdtype = "int64" - values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) - rvalues = self._base([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=rdtype) + values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) + rvalues = np.array([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=rdtype) - a = self._klass(values, kind=kind) - b = self._klass(rvalues, kind=kind) + a = SparseArray(values, kind=kind) + b = SparseArray(rvalues, kind=kind) assert b.dtype == SparseDtype(rdtype) self._check_numeric_ops(a, b, values, rvalues, mix, op) self._check_numeric_ops(a, b * 0, values, rvalues * 0, mix, op) - a = self._klass(values, kind=kind, fill_value=0) - b = self._klass(rvalues, kind=kind) + a = SparseArray(values, kind=kind, fill_value=0) + b = SparseArray(rvalues, kind=kind) assert b.dtype == SparseDtype(rdtype) self._check_numeric_ops(a, b, values, rvalues, mix, op) - a = self._klass(values, kind=kind, fill_value=0) - b = self._klass(rvalues, kind=kind, fill_value=0) + a = SparseArray(values, kind=kind, fill_value=0) + b = SparseArray(rvalues, kind=kind, fill_value=0) assert b.dtype == SparseDtype(rdtype) self._check_numeric_ops(a, b, values, rvalues, mix, op) - a = self._klass(values, kind=kind, fill_value=1) - b = self._klass(rvalues, kind=kind, fill_value=2) + a = SparseArray(values, kind=kind, fill_value=1) + b = SparseArray(rvalues, kind=kind, fill_value=2) assert b.dtype == SparseDtype(rdtype, fill_value=2) self._check_numeric_ops(a, b, values, rvalues, mix, op) @@ -390,28 +386,28 @@ def test_mixed_array_comparison(self, kind): rdtype = "int64" # int32 NI ATM - values = self._base([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) - rvalues = self._base([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=rdtype) + values = np.array([np.nan, 1, 2, 0, np.nan, 0, 1, 2, 1, np.nan]) + rvalues = np.array([2, 0, 2, 3, 0, 0, 1, 5, 2, 0], dtype=rdtype) - a = self._klass(values, kind=kind) - b = self._klass(rvalues, kind=kind) + a = SparseArray(values, kind=kind) + b = SparseArray(rvalues, kind=kind) assert b.dtype == SparseDtype(rdtype) self._check_comparison_ops(a, b, values, rvalues) self._check_comparison_ops(a, b * 0, values, rvalues * 0) - a = self._klass(values, kind=kind, fill_value=0) - b = self._klass(rvalues, kind=kind) + a = SparseArray(values, kind=kind, fill_value=0) + b = SparseArray(rvalues, kind=kind) assert b.dtype == SparseDtype(rdtype) self._check_comparison_ops(a, b, values, rvalues) - a = self._klass(values, kind=kind, fill_value=0) - b = self._klass(rvalues, kind=kind, fill_value=0) + a = SparseArray(values, kind=kind, fill_value=0) + b = SparseArray(rvalues, kind=kind, fill_value=0) assert b.dtype == SparseDtype(rdtype) self._check_comparison_ops(a, b, values, rvalues) - a = self._klass(values, kind=kind, fill_value=1) - b = self._klass(rvalues, kind=kind, fill_value=2) + a = SparseArray(values, kind=kind, fill_value=1) + b = SparseArray(rvalues, kind=kind, fill_value=2) assert b.dtype == SparseDtype(rdtype, fill_value=2) self._check_comparison_ops(a, b, values, rvalues) @@ -495,36 +491,60 @@ def test_sparray_inplace(): tm.assert_sp_array_equal(sparray, expected) -@pytest.mark.parametrize("fill_value", [True, False]) -def test_invert(fill_value): - arr = np.array([True, False, False, True]) - sparray = SparseArray(arr, fill_value=fill_value) - result = ~sparray - expected = SparseArray(~arr, fill_value=not fill_value) - tm.assert_sp_array_equal(result, expected) - - result = ~pd.Series(sparray) - expected = pd.Series(expected) - tm.assert_series_equal(result, expected) - - result = ~pd.DataFrame({"A": sparray}) - expected = pd.DataFrame({"A": expected}) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("fill_value", [0, np.nan]) -@pytest.mark.parametrize("op", [operator.pos, operator.neg]) -def test_unary_op(op, fill_value): - arr = np.array([0, 1, np.nan, 2]) - sparray = SparseArray(arr, fill_value=fill_value) - result = op(sparray) - expected = SparseArray(op(arr), fill_value=op(fill_value)) - tm.assert_sp_array_equal(result, expected) - - @pytest.mark.parametrize("cons", [list, np.array, SparseArray]) def test_mismatched_length_cmp_op(cons): left = SparseArray([True, True]) right = cons([True, True, True]) with pytest.raises(ValueError, match="operands have mismatched length"): left & right + + +@pytest.mark.parametrize("op", ["add", "sub", "mul", "truediv", "floordiv", "pow"]) +def test_binary_operators(op): + op = getattr(operator, op) + data1 = np.random.randn(20) + data2 = np.random.randn(20) + + data1[::2] = np.nan + data2[::3] = np.nan + + arr1 = SparseArray(data1) + arr2 = SparseArray(data2) + + data1[::2] = 3 + data2[::3] = 3 + farr1 = SparseArray(data1, fill_value=3) + farr2 = SparseArray(data2, fill_value=3) + + def _check_op(op, first, second): + res = op(first, second) + exp = SparseArray( + op(first.to_dense(), second.to_dense()), fill_value=first.fill_value + ) + assert isinstance(res, SparseArray) + tm.assert_almost_equal(res.to_dense(), exp.to_dense()) + + res2 = op(first, second.to_dense()) + assert isinstance(res2, SparseArray) + tm.assert_sp_array_equal(res, res2) + + res3 = op(first.to_dense(), second) + assert isinstance(res3, SparseArray) + tm.assert_sp_array_equal(res, res3) + + res4 = op(first, 4) + assert isinstance(res4, SparseArray) + + # Ignore this if the actual op raises (e.g. pow). + try: + exp = op(first.to_dense(), 4) + exp_fv = op(first.fill_value, 4) + except ValueError: + pass + else: + tm.assert_almost_equal(res4.fill_value, exp_fv) + tm.assert_almost_equal(res4.to_dense(), exp) + + with np.errstate(all="ignore"): + for first_arr, second_arr in [(arr1, arr2), (farr1, farr2)]: + _check_op(op, first_arr, second_arr) diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index baa7537e3cc2f..5874e817477a9 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -1,4 +1,3 @@ -import operator import re import warnings @@ -6,7 +5,6 @@ import pytest from pandas._libs.sparse import IntIndex -import pandas.util._test_decorators as td import pandas as pd from pandas import isna @@ -24,309 +22,6 @@ def setup_method(self, method): self.arr = SparseArray(self.arr_data) self.zarr = SparseArray([0, 0, 1, 2, 3, 0, 4, 5, 0, 6], fill_value=0) - def test_constructor_dtype(self): - arr = SparseArray([np.nan, 1, 2, np.nan]) - assert arr.dtype == SparseDtype(np.float64, np.nan) - assert arr.dtype.subtype == np.float64 - assert np.isnan(arr.fill_value) - - arr = SparseArray([np.nan, 1, 2, np.nan], fill_value=0) - assert arr.dtype == SparseDtype(np.float64, 0) - assert arr.fill_value == 0 - - arr = SparseArray([0, 1, 2, 4], dtype=np.float64) - assert arr.dtype == SparseDtype(np.float64, np.nan) - assert np.isnan(arr.fill_value) - - arr = SparseArray([0, 1, 2, 4], dtype=np.int64) - assert arr.dtype == SparseDtype(np.int64, 0) - assert arr.fill_value == 0 - - arr = SparseArray([0, 1, 2, 4], fill_value=0, dtype=np.int64) - assert arr.dtype == SparseDtype(np.int64, 0) - assert arr.fill_value == 0 - - arr = SparseArray([0, 1, 2, 4], dtype=None) - assert arr.dtype == SparseDtype(np.int64, 0) - assert arr.fill_value == 0 - - arr = SparseArray([0, 1, 2, 4], fill_value=0, dtype=None) - assert arr.dtype == SparseDtype(np.int64, 0) - assert arr.fill_value == 0 - - def test_constructor_dtype_str(self): - result = SparseArray([1, 2, 3], dtype="int") - expected = SparseArray([1, 2, 3], dtype=int) - tm.assert_sp_array_equal(result, expected) - - def test_constructor_sparse_dtype(self): - result = SparseArray([1, 0, 0, 1], dtype=SparseDtype("int64", -1)) - expected = SparseArray([1, 0, 0, 1], fill_value=-1, dtype=np.int64) - tm.assert_sp_array_equal(result, expected) - assert result.sp_values.dtype == np.dtype("int64") - - def test_constructor_sparse_dtype_str(self): - result = SparseArray([1, 0, 0, 1], dtype="Sparse[int32]") - expected = SparseArray([1, 0, 0, 1], dtype=np.int32) - tm.assert_sp_array_equal(result, expected) - assert result.sp_values.dtype == np.dtype("int32") - - def test_constructor_object_dtype(self): - # GH 11856 - arr = SparseArray(["A", "A", np.nan, "B"], dtype=object) - assert arr.dtype == SparseDtype(object) - assert np.isnan(arr.fill_value) - - arr = SparseArray(["A", "A", np.nan, "B"], dtype=object, fill_value="A") - assert arr.dtype == SparseDtype(object, "A") - assert arr.fill_value == "A" - - # GH 17574 - data = [False, 0, 100.0, 0.0] - arr = SparseArray(data, dtype=object, fill_value=False) - assert arr.dtype == SparseDtype(object, False) - assert arr.fill_value is False - arr_expected = np.array(data, dtype=object) - it = (type(x) == type(y) and x == y for x, y in zip(arr, arr_expected)) - assert np.fromiter(it, dtype=np.bool_).all() - - @pytest.mark.parametrize("dtype", [SparseDtype(int, 0), int]) - def test_constructor_na_dtype(self, dtype): - with pytest.raises(ValueError, match="Cannot convert"): - SparseArray([0, 1, np.nan], dtype=dtype) - - def test_constructor_warns_when_losing_timezone(self): - # GH#32501 warn when losing timezone information - dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific") - - expected = SparseArray(np.asarray(dti, dtype="datetime64[ns]")) - - with tm.assert_produces_warning(UserWarning): - result = SparseArray(dti) - - tm.assert_sp_array_equal(result, expected) - - with tm.assert_produces_warning(UserWarning): - result = SparseArray(pd.Series(dti)) - - tm.assert_sp_array_equal(result, expected) - - def test_constructor_spindex_dtype(self): - arr = SparseArray(data=[1, 2], sparse_index=IntIndex(4, [1, 2])) - # XXX: Behavior change: specifying SparseIndex no longer changes the - # fill_value - expected = SparseArray([0, 1, 2, 0], kind="integer") - tm.assert_sp_array_equal(arr, expected) - assert arr.dtype == SparseDtype(np.int64) - assert arr.fill_value == 0 - - arr = SparseArray( - data=[1, 2, 3], - sparse_index=IntIndex(4, [1, 2, 3]), - dtype=np.int64, - fill_value=0, - ) - exp = SparseArray([0, 1, 2, 3], dtype=np.int64, fill_value=0) - tm.assert_sp_array_equal(arr, exp) - assert arr.dtype == SparseDtype(np.int64) - assert arr.fill_value == 0 - - arr = SparseArray( - data=[1, 2], sparse_index=IntIndex(4, [1, 2]), fill_value=0, dtype=np.int64 - ) - exp = SparseArray([0, 1, 2, 0], fill_value=0, dtype=np.int64) - tm.assert_sp_array_equal(arr, exp) - assert arr.dtype == SparseDtype(np.int64) - assert arr.fill_value == 0 - - arr = SparseArray( - data=[1, 2, 3], - sparse_index=IntIndex(4, [1, 2, 3]), - dtype=None, - fill_value=0, - ) - exp = SparseArray([0, 1, 2, 3], dtype=None) - tm.assert_sp_array_equal(arr, exp) - assert arr.dtype == SparseDtype(np.int64) - assert arr.fill_value == 0 - - @pytest.mark.parametrize("sparse_index", [None, IntIndex(1, [0])]) - def test_constructor_spindex_dtype_scalar(self, sparse_index): - # scalar input - arr = SparseArray(data=1, sparse_index=sparse_index, dtype=None) - exp = SparseArray([1], dtype=None) - tm.assert_sp_array_equal(arr, exp) - assert arr.dtype == SparseDtype(np.int64) - assert arr.fill_value == 0 - - arr = SparseArray(data=1, sparse_index=IntIndex(1, [0]), dtype=None) - exp = SparseArray([1], dtype=None) - tm.assert_sp_array_equal(arr, exp) - assert arr.dtype == SparseDtype(np.int64) - assert arr.fill_value == 0 - - def test_constructor_spindex_dtype_scalar_broadcasts(self): - arr = SparseArray( - data=[1, 2], sparse_index=IntIndex(4, [1, 2]), fill_value=0, dtype=None - ) - exp = SparseArray([0, 1, 2, 0], fill_value=0, dtype=None) - tm.assert_sp_array_equal(arr, exp) - assert arr.dtype == SparseDtype(np.int64) - assert arr.fill_value == 0 - - @pytest.mark.parametrize( - "data, fill_value", - [ - (np.array([1, 2]), 0), - (np.array([1.0, 2.0]), np.nan), - ([True, False], False), - ([pd.Timestamp("2017-01-01")], pd.NaT), - ], - ) - def test_constructor_inferred_fill_value(self, data, fill_value): - result = SparseArray(data).fill_value - - if isna(fill_value): - assert isna(result) - else: - assert result == fill_value - - @pytest.mark.parametrize("format", ["coo", "csc", "csr"]) - @pytest.mark.parametrize("size", [0, 10]) - @td.skip_if_no_scipy - def test_from_spmatrix(self, size, format): - import scipy.sparse - - mat = scipy.sparse.random(size, 1, density=0.5, format=format) - result = SparseArray.from_spmatrix(mat) - - result = np.asarray(result) - expected = mat.toarray().ravel() - tm.assert_numpy_array_equal(result, expected) - - @pytest.mark.parametrize("format", ["coo", "csc", "csr"]) - @td.skip_if_no_scipy - def test_from_spmatrix_including_explicit_zero(self, format): - import scipy.sparse - - mat = scipy.sparse.random(10, 1, density=0.5, format=format) - mat.data[0] = 0 - result = SparseArray.from_spmatrix(mat) - - result = np.asarray(result) - expected = mat.toarray().ravel() - tm.assert_numpy_array_equal(result, expected) - - @td.skip_if_no_scipy - def test_from_spmatrix_raises(self): - import scipy.sparse - - mat = scipy.sparse.eye(5, 4, format="csc") - - with pytest.raises(ValueError, match="not '4'"): - SparseArray.from_spmatrix(mat) - - @pytest.mark.parametrize( - "scalar,dtype", - [ - (False, SparseDtype(bool, False)), - (0.0, SparseDtype("float64", 0)), - (1, SparseDtype("int64", 1)), - ("z", SparseDtype("object", "z")), - ], - ) - def test_scalar_with_index_infer_dtype(self, scalar, dtype): - # GH 19163 - with tm.assert_produces_warning( - FutureWarning, match="The index argument has been deprecated" - ): - arr = SparseArray(scalar, index=[1, 2, 3], fill_value=scalar) - exp = SparseArray([scalar, scalar, scalar], fill_value=scalar) - - tm.assert_sp_array_equal(arr, exp) - - assert arr.dtype == dtype - assert exp.dtype == dtype - - def test_getitem_bool_sparse_array(self): - # GH 23122 - spar_bool = SparseArray([False, True] * 5, dtype=np.bool8, fill_value=True) - exp = SparseArray([np.nan, 2, np.nan, 5, 6]) - tm.assert_sp_array_equal(self.arr[spar_bool], exp) - - spar_bool = ~spar_bool - res = self.arr[spar_bool] - exp = SparseArray([np.nan, 1, 3, 4, np.nan]) - tm.assert_sp_array_equal(res, exp) - - spar_bool = SparseArray( - [False, True, np.nan] * 3, dtype=np.bool8, fill_value=np.nan - ) - res = self.arr[spar_bool] - exp = SparseArray([np.nan, 3, 5]) - tm.assert_sp_array_equal(res, exp) - - def test_getitem_bool_sparse_array_as_comparison(self): - # GH 45110 - arr = SparseArray([1, 2, 3, 4, np.nan, np.nan], fill_value=np.nan) - res = arr[arr > 2] - exp = SparseArray([3.0, 4.0], fill_value=np.nan) - tm.assert_sp_array_equal(res, exp) - - def test_get_item(self): - - assert np.isnan(self.arr[1]) - assert self.arr[2] == 1 - assert self.arr[7] == 5 - - assert self.zarr[0] == 0 - assert self.zarr[2] == 1 - assert self.zarr[7] == 5 - - errmsg = "must be an integer between -10 and 10" - - with pytest.raises(IndexError, match=errmsg): - self.arr[11] - - with pytest.raises(IndexError, match=errmsg): - self.arr[-11] - - assert self.arr[-1] == self.arr[len(self.arr) - 1] - - def test_take_scalar_raises(self): - msg = "'indices' must be an array, not a scalar '2'." - with pytest.raises(ValueError, match=msg): - self.arr.take(2) - - def test_take(self): - exp = SparseArray(np.take(self.arr_data, [2, 3])) - tm.assert_sp_array_equal(self.arr.take([2, 3]), exp) - - exp = SparseArray(np.take(self.arr_data, [0, 1, 2])) - tm.assert_sp_array_equal(self.arr.take([0, 1, 2]), exp) - - def test_take_all_empty(self): - a = pd.array([0, 0], dtype=SparseDtype("int64")) - result = a.take([0, 1], allow_fill=True, fill_value=np.nan) - tm.assert_sp_array_equal(a, result) - - def test_take_fill_value(self): - data = np.array([1, np.nan, 0, 3, 0]) - sparse = SparseArray(data, fill_value=0) - - exp = SparseArray(np.take(data, [0]), fill_value=0) - tm.assert_sp_array_equal(sparse.take([0]), exp) - - exp = SparseArray(np.take(data, [1, 3, 4]), fill_value=0) - tm.assert_sp_array_equal(sparse.take([1, 3, 4]), exp) - - def test_take_negative(self): - exp = SparseArray(np.take(self.arr_data, [-1])) - tm.assert_sp_array_equal(self.arr.take([-1]), exp) - - exp = SparseArray(np.take(self.arr_data, [-4, -3, -2])) - tm.assert_sp_array_equal(self.arr.take([-4, -3, -2]), exp) - @pytest.mark.parametrize("fill_value", [0, None, np.nan]) def test_shift_fill_value(self, fill_value): # GH #24128 @@ -337,287 +32,6 @@ def test_shift_fill_value(self, fill_value): exp = SparseArray(np.array([fill_value, 1, 0, 0, 3]), fill_value=8.0) tm.assert_sp_array_equal(res, exp) - def test_bad_take(self): - with pytest.raises(IndexError, match="bounds"): - self.arr.take([11]) - - def test_take_filling(self): - # similar tests as GH 12631 - sparse = SparseArray([np.nan, np.nan, 1, np.nan, 4]) - result = sparse.take(np.array([1, 0, -1])) - expected = SparseArray([np.nan, np.nan, 4]) - tm.assert_sp_array_equal(result, expected) - - # XXX: test change: fill_value=True -> allow_fill=True - result = sparse.take(np.array([1, 0, -1]), allow_fill=True) - expected = SparseArray([np.nan, np.nan, np.nan]) - tm.assert_sp_array_equal(result, expected) - - # allow_fill=False - result = sparse.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) - expected = SparseArray([np.nan, np.nan, 4]) - tm.assert_sp_array_equal(result, expected) - - msg = "Invalid value in 'indices'" - with pytest.raises(ValueError, match=msg): - sparse.take(np.array([1, 0, -2]), allow_fill=True) - - with pytest.raises(ValueError, match=msg): - sparse.take(np.array([1, 0, -5]), allow_fill=True) - - msg = "out of bounds value in 'indices'" - with pytest.raises(IndexError, match=msg): - sparse.take(np.array([1, -6])) - with pytest.raises(IndexError, match=msg): - sparse.take(np.array([1, 5])) - with pytest.raises(IndexError, match=msg): - sparse.take(np.array([1, 5]), allow_fill=True) - - def test_take_filling_fill_value(self): - # same tests as GH 12631 - sparse = SparseArray([np.nan, 0, 1, 0, 4], fill_value=0) - result = sparse.take(np.array([1, 0, -1])) - expected = SparseArray([0, np.nan, 4], fill_value=0) - tm.assert_sp_array_equal(result, expected) - - # fill_value - result = sparse.take(np.array([1, 0, -1]), allow_fill=True) - # XXX: behavior change. - # the old way of filling self.fill_value doesn't follow EA rules. - # It's supposed to be self.dtype.na_value (nan in this case) - expected = SparseArray([0, np.nan, np.nan], fill_value=0) - tm.assert_sp_array_equal(result, expected) - - # allow_fill=False - result = sparse.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) - expected = SparseArray([0, np.nan, 4], fill_value=0) - tm.assert_sp_array_equal(result, expected) - - msg = "Invalid value in 'indices'." - with pytest.raises(ValueError, match=msg): - sparse.take(np.array([1, 0, -2]), allow_fill=True) - with pytest.raises(ValueError, match=msg): - sparse.take(np.array([1, 0, -5]), allow_fill=True) - - msg = "out of bounds value in 'indices'" - with pytest.raises(IndexError, match=msg): - sparse.take(np.array([1, -6])) - with pytest.raises(IndexError, match=msg): - sparse.take(np.array([1, 5])) - with pytest.raises(IndexError, match=msg): - sparse.take(np.array([1, 5]), fill_value=True) - - @pytest.mark.parametrize("kind", ["block", "integer"]) - def test_take_filling_all_nan(self, kind): - sparse = SparseArray([np.nan, np.nan, np.nan, np.nan, np.nan], kind=kind) - result = sparse.take(np.array([1, 0, -1])) - expected = SparseArray([np.nan, np.nan, np.nan], kind=kind) - tm.assert_sp_array_equal(result, expected) - - result = sparse.take(np.array([1, 0, -1]), fill_value=True) - expected = SparseArray([np.nan, np.nan, np.nan], kind=kind) - tm.assert_sp_array_equal(result, expected) - - msg = "out of bounds value in 'indices'" - with pytest.raises(IndexError, match=msg): - sparse.take(np.array([1, -6])) - with pytest.raises(IndexError, match=msg): - sparse.take(np.array([1, 5])) - with pytest.raises(IndexError, match=msg): - sparse.take(np.array([1, 5]), fill_value=True) - - def test_set_item(self): - def setitem(): - self.arr[5] = 3 - - def setslice(): - self.arr[1:5] = 2 - - with pytest.raises(TypeError, match="assignment via setitem"): - setitem() - - with pytest.raises(TypeError, match="assignment via setitem"): - setslice() - - def test_constructor_from_too_large_array(self): - with pytest.raises(TypeError, match="expected dimension <= 1 data"): - SparseArray(np.arange(10).reshape((2, 5))) - - def test_constructor_from_sparse(self): - res = SparseArray(self.zarr) - assert res.fill_value == 0 - tm.assert_almost_equal(res.sp_values, self.zarr.sp_values) - - def test_constructor_copy(self): - cp = SparseArray(self.arr, copy=True) - cp.sp_values[:3] = 0 - assert not (self.arr.sp_values[:3] == 0).any() - - not_copy = SparseArray(self.arr) - not_copy.sp_values[:3] = 0 - assert (self.arr.sp_values[:3] == 0).all() - - def test_constructor_bool(self): - # GH 10648 - data = np.array([False, False, True, True, False, False]) - arr = SparseArray(data, fill_value=False, dtype=bool) - - assert arr.dtype == SparseDtype(bool) - tm.assert_numpy_array_equal(arr.sp_values, np.array([True, True])) - # Behavior change: np.asarray densifies. - # tm.assert_numpy_array_equal(arr.sp_values, np.asarray(arr)) - tm.assert_numpy_array_equal(arr.sp_index.indices, np.array([2, 3], np.int32)) - - dense = arr.to_dense() - assert dense.dtype == bool - tm.assert_numpy_array_equal(dense, data) - - def test_constructor_bool_fill_value(self): - arr = SparseArray([True, False, True], dtype=None) - assert arr.dtype == SparseDtype(np.bool_) - assert not arr.fill_value - - arr = SparseArray([True, False, True], dtype=np.bool_) - assert arr.dtype == SparseDtype(np.bool_) - assert not arr.fill_value - - arr = SparseArray([True, False, True], dtype=np.bool_, fill_value=True) - assert arr.dtype == SparseDtype(np.bool_, True) - assert arr.fill_value - - def test_constructor_float32(self): - # GH 10648 - data = np.array([1.0, np.nan, 3], dtype=np.float32) - arr = SparseArray(data, dtype=np.float32) - - assert arr.dtype == SparseDtype(np.float32) - tm.assert_numpy_array_equal(arr.sp_values, np.array([1, 3], dtype=np.float32)) - # Behavior change: np.asarray densifies. - # tm.assert_numpy_array_equal(arr.sp_values, np.asarray(arr)) - tm.assert_numpy_array_equal( - arr.sp_index.indices, np.array([0, 2], dtype=np.int32) - ) - - dense = arr.to_dense() - assert dense.dtype == np.float32 - tm.assert_numpy_array_equal(dense, data) - - def test_astype(self): - # float -> float - arr = SparseArray([None, None, 0, 2]) - result = arr.astype("Sparse[float32]") - expected = SparseArray([None, None, 0, 2], dtype=np.dtype("float32")) - tm.assert_sp_array_equal(result, expected) - - dtype = SparseDtype("float64", fill_value=0) - result = arr.astype(dtype) - expected = SparseArray._simple_new( - np.array([0.0, 2.0], dtype=dtype.subtype), IntIndex(4, [2, 3]), dtype - ) - tm.assert_sp_array_equal(result, expected) - - dtype = SparseDtype("int64", 0) - result = arr.astype(dtype) - expected = SparseArray._simple_new( - np.array([0, 2], dtype=np.int64), IntIndex(4, [2, 3]), dtype - ) - tm.assert_sp_array_equal(result, expected) - - arr = SparseArray([0, np.nan, 0, 1], fill_value=0) - with pytest.raises(ValueError, match="NA"): - arr.astype("Sparse[i8]") - - def test_astype_bool(self): - a = SparseArray([1, 0, 0, 1], dtype=SparseDtype(int, 0)) - with tm.assert_produces_warning(FutureWarning, match="astype from Sparse"): - result = a.astype(bool) - expected = SparseArray( - [True, False, False, True], dtype=SparseDtype(bool, False) - ) - tm.assert_sp_array_equal(result, expected) - - # update fill value - result = a.astype(SparseDtype(bool, False)) - expected = SparseArray( - [True, False, False, True], dtype=SparseDtype(bool, False) - ) - tm.assert_sp_array_equal(result, expected) - - def test_astype_all(self, any_real_numpy_dtype): - vals = np.array([1, 2, 3]) - arr = SparseArray(vals, fill_value=1) - typ = np.dtype(any_real_numpy_dtype) - with tm.assert_produces_warning(FutureWarning, match="astype from Sparse"): - res = arr.astype(typ) - assert res.dtype == SparseDtype(typ, 1) - assert res.sp_values.dtype == typ - - tm.assert_numpy_array_equal(np.asarray(res.to_dense()), vals.astype(typ)) - - @pytest.mark.parametrize( - "arr, dtype, expected", - [ - ( - SparseArray([0, 1]), - "float", - SparseArray([0.0, 1.0], dtype=SparseDtype(float, 0.0)), - ), - (SparseArray([0, 1]), bool, SparseArray([False, True])), - ( - SparseArray([0, 1], fill_value=1), - bool, - SparseArray([False, True], dtype=SparseDtype(bool, True)), - ), - pytest.param( - SparseArray([0, 1]), - "datetime64[ns]", - SparseArray( - np.array([0, 1], dtype="datetime64[ns]"), - dtype=SparseDtype("datetime64[ns]", pd.Timestamp("1970")), - ), - marks=[pytest.mark.xfail(reason="NumPy-7619")], - ), - ( - SparseArray([0, 1, 10]), - str, - SparseArray(["0", "1", "10"], dtype=SparseDtype(str, "0")), - ), - (SparseArray(["10", "20"]), float, SparseArray([10.0, 20.0])), - ( - SparseArray([0, 1, 0]), - object, - SparseArray([0, 1, 0], dtype=SparseDtype(object, 0)), - ), - ], - ) - def test_astype_more(self, arr, dtype, expected): - - if isinstance(dtype, SparseDtype): - warn = None - else: - warn = FutureWarning - - with tm.assert_produces_warning(warn, match="astype from SparseDtype"): - result = arr.astype(dtype) - tm.assert_sp_array_equal(result, expected) - - def test_astype_nan_raises(self): - arr = SparseArray([1.0, np.nan]) - with pytest.raises(ValueError, match="Cannot convert non-finite"): - msg = "astype from SparseDtype" - with tm.assert_produces_warning(FutureWarning, match=msg): - arr.astype(int) - - def test_astype_copy_false(self): - # GH#34456 bug caused by using .view instead of .astype in astype_nansafe - arr = SparseArray([1, 2, 3]) - - dtype = SparseDtype(float, 0) - - result = arr.astype(dtype, copy=False) - expected = SparseArray([1.0, 2.0, 3.0], fill_value=0.0) - tm.assert_sp_array_equal(result, expected) - def test_set_fill_value(self): arr = SparseArray([1.0, np.nan, 2.0], fill_value=np.nan) arr.fill_value = 2 @@ -627,7 +41,7 @@ def test_set_fill_value(self): arr.fill_value = 2 assert arr.fill_value == 2 - # XXX: this seems fine? You can construct an integer + # TODO: this seems fine? You can construct an integer # sparsearray with NaN fill value, why not update one? # coerces to int # msg = "unable to set fill_value 3\\.1 to int64 dtype" @@ -644,8 +58,9 @@ def test_set_fill_value(self): arr.fill_value = True assert arr.fill_value + # FIXME: don't leave commented-out # coerces to bool - # XXX: we can construct an sparse array of bool + # TODO: we can construct an sparse array of bool # type and use as fill_value any value # msg = "fill_value must be True, False or nan" # with pytest.raises(ValueError, match=msg): @@ -706,163 +121,6 @@ def test_dense_repr(self, vals, fill_value): tm.assert_numpy_array_equal(res2, vals) - def test_getitem(self): - def _checkit(i): - tm.assert_almost_equal(self.arr[i], self.arr.to_dense()[i]) - - for i in range(len(self.arr)): - _checkit(i) - _checkit(-i) - - def test_getitem_arraylike_mask(self): - arr = SparseArray([0, 1, 2]) - result = arr[[True, False, True]] - expected = SparseArray([0, 2]) - tm.assert_sp_array_equal(result, expected) - - @pytest.mark.parametrize( - "slc", - [ - np.s_[:], - np.s_[1:10], - np.s_[1:100], - np.s_[10:1], - np.s_[:-3], - np.s_[-5:-4], - np.s_[:-12], - np.s_[-12:], - np.s_[2:], - np.s_[2::3], - np.s_[::2], - np.s_[::-1], - np.s_[::-2], - np.s_[1:6:2], - np.s_[:-6:-2], - ], - ) - @pytest.mark.parametrize( - "as_dense", [[np.nan] * 10, [1] * 10, [np.nan] * 5 + [1] * 5, []] - ) - def test_getslice(self, slc, as_dense): - as_dense = np.array(as_dense) - arr = SparseArray(as_dense) - - result = arr[slc] - expected = SparseArray(as_dense[slc]) - - tm.assert_sp_array_equal(result, expected) - - def test_getslice_tuple(self): - dense = np.array([np.nan, 0, 3, 4, 0, 5, np.nan, np.nan, 0]) - - sparse = SparseArray(dense) - res = sparse[(slice(4, None),)] - exp = SparseArray(dense[4:]) - tm.assert_sp_array_equal(res, exp) - - sparse = SparseArray(dense, fill_value=0) - res = sparse[(slice(4, None),)] - exp = SparseArray(dense[4:], fill_value=0) - tm.assert_sp_array_equal(res, exp) - - msg = "too many indices for array" - with pytest.raises(IndexError, match=msg): - sparse[4:, :] - - with pytest.raises(IndexError, match=msg): - # check numpy compat - dense[4:, :] - - def test_boolean_slice_empty(self): - arr = SparseArray([0, 1, 2]) - res = arr[[False, False, False]] - assert res.dtype == arr.dtype - - def test_neg_operator(self): - arr = SparseArray([-1, -2, np.nan, 3], fill_value=np.nan, dtype=np.int8) - res = -arr - exp = SparseArray([1, 2, np.nan, -3], fill_value=np.nan, dtype=np.int8) - tm.assert_sp_array_equal(exp, res) - - arr = SparseArray([-1, -2, 1, 3], fill_value=-1, dtype=np.int8) - res = -arr - exp = SparseArray([1, 2, -1, -3], fill_value=1, dtype=np.int8) - tm.assert_sp_array_equal(exp, res) - - def test_abs_operator(self): - arr = SparseArray([-1, -2, np.nan, 3], fill_value=np.nan, dtype=np.int8) - res = abs(arr) - exp = SparseArray([1, 2, np.nan, 3], fill_value=np.nan, dtype=np.int8) - tm.assert_sp_array_equal(exp, res) - - arr = SparseArray([-1, -2, 1, 3], fill_value=-1, dtype=np.int8) - res = abs(arr) - exp = SparseArray([1, 2, 1, 3], fill_value=1, dtype=np.int8) - tm.assert_sp_array_equal(exp, res) - - def test_invert_operator(self): - arr = SparseArray([False, True, False, True], fill_value=False, dtype=np.bool8) - res = ~arr - exp = SparseArray( - np.invert([False, True, False, True]), fill_value=True, dtype=np.bool8 - ) - res = ~arr - tm.assert_sp_array_equal(exp, res) - - arr = SparseArray([0, 1, 0, 2, 3, 0], fill_value=0, dtype=np.int32) - res = ~arr - exp = SparseArray([-1, -2, -1, -3, -4, -1], fill_value=-1, dtype=np.int32) - - @pytest.mark.parametrize("op", ["add", "sub", "mul", "truediv", "floordiv", "pow"]) - def test_binary_operators(self, op): - op = getattr(operator, op) - data1 = np.random.randn(20) - data2 = np.random.randn(20) - - data1[::2] = np.nan - data2[::3] = np.nan - - arr1 = SparseArray(data1) - arr2 = SparseArray(data2) - - data1[::2] = 3 - data2[::3] = 3 - farr1 = SparseArray(data1, fill_value=3) - farr2 = SparseArray(data2, fill_value=3) - - def _check_op(op, first, second): - res = op(first, second) - exp = SparseArray( - op(first.to_dense(), second.to_dense()), fill_value=first.fill_value - ) - assert isinstance(res, SparseArray) - tm.assert_almost_equal(res.to_dense(), exp.to_dense()) - - res2 = op(first, second.to_dense()) - assert isinstance(res2, SparseArray) - tm.assert_sp_array_equal(res, res2) - - res3 = op(first.to_dense(), second) - assert isinstance(res3, SparseArray) - tm.assert_sp_array_equal(res, res3) - - res4 = op(first, 4) - assert isinstance(res4, SparseArray) - - # Ignore this if the actual op raises (e.g. pow). - try: - exp = op(first.to_dense(), 4) - exp_fv = op(first.fill_value, 4) - except ValueError: - pass - else: - tm.assert_almost_equal(res4.fill_value, exp_fv) - tm.assert_almost_equal(res4.to_dense(), exp) - - with np.errstate(all="ignore"): - for first_arr, second_arr in [(arr1, arr2), (farr1, farr2)]: - _check_op(op, first_arr, second_arr) - def test_pickle(self): def _check_roundtrip(obj): unpickled = tm.round_trip_pickle(obj) @@ -980,163 +238,6 @@ def test_nonzero(self): class TestSparseArrayAnalytics: - @pytest.mark.parametrize( - "data,pos,neg", - [ - ([True, True, True], True, False), - ([1, 2, 1], 1, 0), - ([1.0, 2.0, 1.0], 1.0, 0.0), - ], - ) - def test_all(self, data, pos, neg): - # GH 17570 - out = SparseArray(data).all() - assert out - - out = SparseArray(data, fill_value=pos).all() - assert out - - data[1] = neg - out = SparseArray(data).all() - assert not out - - out = SparseArray(data, fill_value=pos).all() - assert not out - - @pytest.mark.parametrize( - "data,pos,neg", - [ - ([True, True, True], True, False), - ([1, 2, 1], 1, 0), - ([1.0, 2.0, 1.0], 1.0, 0.0), - ], - ) - def test_numpy_all(self, data, pos, neg): - # GH 17570 - out = np.all(SparseArray(data)) - assert out - - out = np.all(SparseArray(data, fill_value=pos)) - assert out - - data[1] = neg - out = np.all(SparseArray(data)) - assert not out - - out = np.all(SparseArray(data, fill_value=pos)) - assert not out - - # raises with a different message on py2. - msg = "the 'out' parameter is not supported" - with pytest.raises(ValueError, match=msg): - np.all(SparseArray(data), out=np.array([])) - - @pytest.mark.parametrize( - "data,pos,neg", - [ - ([False, True, False], True, False), - ([0, 2, 0], 2, 0), - ([0.0, 2.0, 0.0], 2.0, 0.0), - ], - ) - def test_any(self, data, pos, neg): - # GH 17570 - out = SparseArray(data).any() - assert out - - out = SparseArray(data, fill_value=pos).any() - assert out - - data[1] = neg - out = SparseArray(data).any() - assert not out - - out = SparseArray(data, fill_value=pos).any() - assert not out - - @pytest.mark.parametrize( - "data,pos,neg", - [ - ([False, True, False], True, False), - ([0, 2, 0], 2, 0), - ([0.0, 2.0, 0.0], 2.0, 0.0), - ], - ) - def test_numpy_any(self, data, pos, neg): - # GH 17570 - out = np.any(SparseArray(data)) - assert out - - out = np.any(SparseArray(data, fill_value=pos)) - assert out - - data[1] = neg - out = np.any(SparseArray(data)) - assert not out - - out = np.any(SparseArray(data, fill_value=pos)) - assert not out - - msg = "the 'out' parameter is not supported" - with pytest.raises(ValueError, match=msg): - np.any(SparseArray(data), out=out) - - def test_sum(self): - data = np.arange(10).astype(float) - out = SparseArray(data).sum() - assert out == 45.0 - - data[5] = np.nan - out = SparseArray(data, fill_value=2).sum() - assert out == 40.0 - - out = SparseArray(data, fill_value=np.nan).sum() - assert out == 40.0 - - @pytest.mark.parametrize( - "arr", - [np.array([0, 1, np.nan, 1]), np.array([0, 1, 1])], - ) - @pytest.mark.parametrize("fill_value", [0, 1, np.nan]) - @pytest.mark.parametrize("min_count, expected", [(3, 2), (4, np.nan)]) - def test_sum_min_count(self, arr, fill_value, min_count, expected): - # https://github.com/pandas-dev/pandas/issues/25777 - sparray = SparseArray(arr, fill_value=fill_value) - result = sparray.sum(min_count=min_count) - if np.isnan(expected): - assert np.isnan(result) - else: - assert result == expected - - def test_bool_sum_min_count(self): - spar_bool = pd.arrays.SparseArray( - [False, True] * 5, dtype=np.bool8, fill_value=True - ) - res = spar_bool.sum(min_count=1) - assert res == 5 - res = spar_bool.sum(min_count=11) - assert isna(res) - - def test_numpy_sum(self): - data = np.arange(10).astype(float) - out = np.sum(SparseArray(data)) - assert out == 45.0 - - data[5] = np.nan - out = np.sum(SparseArray(data, fill_value=2)) - assert out == 40.0 - - out = np.sum(SparseArray(data, fill_value=np.nan)) - assert out == 40.0 - - msg = "the 'dtype' parameter is not supported" - with pytest.raises(ValueError, match=msg): - np.sum(SparseArray(data), dtype=np.int64) - - msg = "the 'out' parameter is not supported" - with pytest.raises(ValueError, match=msg): - np.sum(SparseArray(data), out=out) - @pytest.mark.parametrize( "data,expected", [ @@ -1177,32 +278,6 @@ def test_cumsum(self, data, expected, numpy): with pytest.raises(ValueError, match=msg): SparseArray(data).cumsum(axis=axis) - def test_mean(self): - data = np.arange(10).astype(float) - out = SparseArray(data).mean() - assert out == 4.5 - - data[5] = np.nan - out = SparseArray(data).mean() - assert out == 40.0 / 9 - - def test_numpy_mean(self): - data = np.arange(10).astype(float) - out = np.mean(SparseArray(data)) - assert out == 4.5 - - data[5] = np.nan - out = np.mean(SparseArray(data)) - assert out == 40.0 / 9 - - msg = "the 'dtype' parameter is not supported" - with pytest.raises(ValueError, match=msg): - np.mean(SparseArray(data), dtype=np.int64) - - msg = "the 'out' parameter is not supported" - with pytest.raises(ValueError, match=msg): - np.mean(SparseArray(data), out=out) - def test_ufunc(self): # GH 13853 make sure ufunc is applied to fill_value sparse = SparseArray([1, np.nan, 2, np.nan, -2]) @@ -1281,86 +356,6 @@ def test_npoints(self): assert arr.npoints == 1 -class TestAccessor: - @pytest.mark.parametrize("attr", ["npoints", "density", "fill_value", "sp_values"]) - def test_get_attributes(self, attr): - arr = SparseArray([0, 1]) - ser = pd.Series(arr) - - result = getattr(ser.sparse, attr) - expected = getattr(arr, attr) - assert result == expected - - @td.skip_if_no_scipy - def test_from_coo(self): - import scipy.sparse - - row = [0, 3, 1, 0] - col = [0, 3, 1, 2] - data = [4, 5, 7, 9] - # TODO(scipy#13585): Remove dtype when scipy is fixed - # https://github.com/scipy/scipy/issues/13585 - sp_array = scipy.sparse.coo_matrix((data, (row, col)), dtype="int") - result = pd.Series.sparse.from_coo(sp_array) - - index = pd.MultiIndex.from_arrays([[0, 0, 1, 3], [0, 2, 1, 3]]) - expected = pd.Series([4, 9, 7, 5], index=index, dtype="Sparse[int]") - tm.assert_series_equal(result, expected) - - @td.skip_if_no_scipy - @pytest.mark.parametrize( - "sort_labels, expected_rows, expected_cols, expected_values_pos", - [ - ( - False, - [("b", 2), ("a", 2), ("b", 1), ("a", 1)], - [("z", 1), ("z", 2), ("x", 2), ("z", 0)], - {1: (1, 0), 3: (3, 3)}, - ), - ( - True, - [("a", 1), ("a", 2), ("b", 1), ("b", 2)], - [("x", 2), ("z", 0), ("z", 1), ("z", 2)], - {1: (1, 2), 3: (0, 1)}, - ), - ], - ) - def test_to_coo( - self, sort_labels, expected_rows, expected_cols, expected_values_pos - ): - import scipy.sparse - - values = SparseArray([0, np.nan, 1, 0, None, 3], fill_value=0) - index = pd.MultiIndex.from_tuples( - [ - ("b", 2, "z", 1), - ("a", 2, "z", 2), - ("a", 2, "z", 1), - ("a", 2, "x", 2), - ("b", 1, "z", 1), - ("a", 1, "z", 0), - ] - ) - ss = pd.Series(values, index=index) - - expected_A = np.zeros((4, 4)) - for value, (row, col) in expected_values_pos.items(): - expected_A[row, col] = value - - A, rows, cols = ss.sparse.to_coo( - row_levels=(0, 1), column_levels=(2, 3), sort_labels=sort_labels - ) - assert isinstance(A, scipy.sparse.coo_matrix) - tm.assert_numpy_array_equal(A.toarray(), expected_A) - assert rows == expected_rows - assert cols == expected_cols - - def test_non_sparse_raises(self): - ser = pd.Series([1, 2, 3]) - with pytest.raises(AttributeError, match=".sparse"): - ser.sparse.density - - def test_setting_fill_value_fillna_still_works(): # This is why letting users update fill_value / dtype is bad # astype has the same problem. @@ -1468,78 +463,3 @@ def test_drop_duplicates_fill_value(): result = df.drop_duplicates() expected = pd.DataFrame({i: SparseArray([0.0], fill_value=0) for i in range(5)}) tm.assert_frame_equal(result, expected) - - -class TestMinMax: - @pytest.mark.parametrize( - "raw_data,max_expected,min_expected", - [ - (np.arange(5.0), [4], [0]), - (-np.arange(5.0), [0], [-4]), - (np.array([0, 1, 2, np.nan, 4]), [4], [0]), - (np.array([np.nan] * 5), [np.nan], [np.nan]), - (np.array([]), [np.nan], [np.nan]), - ], - ) - def test_nan_fill_value(self, raw_data, max_expected, min_expected): - arr = SparseArray(raw_data) - max_result = arr.max() - min_result = arr.min() - assert max_result in max_expected - assert min_result in min_expected - - max_result = arr.max(skipna=False) - min_result = arr.min(skipna=False) - if np.isnan(raw_data).any(): - assert np.isnan(max_result) - assert np.isnan(min_result) - else: - assert max_result in max_expected - assert min_result in min_expected - - @pytest.mark.parametrize( - "fill_value,max_expected,min_expected", - [ - (100, 100, 0), - (-100, 1, -100), - ], - ) - def test_fill_value(self, fill_value, max_expected, min_expected): - arr = SparseArray( - np.array([fill_value, 0, 1]), dtype=SparseDtype("int", fill_value) - ) - max_result = arr.max() - assert max_result == max_expected - - min_result = arr.min() - assert min_result == min_expected - - def test_only_fill_value(self): - fv = 100 - arr = SparseArray(np.array([fv, fv, fv]), dtype=SparseDtype("int", fv)) - assert len(arr._valid_sp_values) == 0 - - assert arr.max() == fv - assert arr.min() == fv - assert arr.max(skipna=False) == fv - assert arr.min(skipna=False) == fv - - @pytest.mark.parametrize("func", ["min", "max"]) - @pytest.mark.parametrize("data", [np.array([]), np.array([np.nan, np.nan])]) - @pytest.mark.parametrize( - "dtype,expected", - [ - (SparseDtype(np.float64, np.nan), np.nan), - (SparseDtype(np.float64, 5.0), np.nan), - (SparseDtype("datetime64[ns]", pd.NaT), pd.NaT), - (SparseDtype("datetime64[ns]", pd.to_datetime("2018-05-05")), pd.NaT), - ], - ) - def test_na_value_if_no_valid_values(self, func, data, dtype, expected): - arr = SparseArray(data, dtype=dtype) - result = getattr(arr, func)() - if expected is pd.NaT: - # TODO: pin down whether we wrap datetime64("NaT") - assert result is pd.NaT or np.isnat(result) - else: - assert np.isnan(result) diff --git a/pandas/tests/arrays/sparse/test_astype.py b/pandas/tests/arrays/sparse/test_astype.py new file mode 100644 index 0000000000000..88efd0f4ea09f --- /dev/null +++ b/pandas/tests/arrays/sparse/test_astype.py @@ -0,0 +1,129 @@ +import numpy as np +import pytest + +from pandas._libs.sparse import IntIndex + +from pandas import Timestamp +import pandas._testing as tm +from pandas.core.arrays.sparse import ( + SparseArray, + SparseDtype, +) + + +class TestAstype: + def test_astype(self): + # float -> float + arr = SparseArray([None, None, 0, 2]) + result = arr.astype("Sparse[float32]") + expected = SparseArray([None, None, 0, 2], dtype=np.dtype("float32")) + tm.assert_sp_array_equal(result, expected) + + dtype = SparseDtype("float64", fill_value=0) + result = arr.astype(dtype) + expected = SparseArray._simple_new( + np.array([0.0, 2.0], dtype=dtype.subtype), IntIndex(4, [2, 3]), dtype + ) + tm.assert_sp_array_equal(result, expected) + + dtype = SparseDtype("int64", 0) + result = arr.astype(dtype) + expected = SparseArray._simple_new( + np.array([0, 2], dtype=np.int64), IntIndex(4, [2, 3]), dtype + ) + tm.assert_sp_array_equal(result, expected) + + arr = SparseArray([0, np.nan, 0, 1], fill_value=0) + with pytest.raises(ValueError, match="NA"): + arr.astype("Sparse[i8]") + + def test_astype_bool(self): + a = SparseArray([1, 0, 0, 1], dtype=SparseDtype(int, 0)) + with tm.assert_produces_warning(FutureWarning, match="astype from Sparse"): + result = a.astype(bool) + expected = SparseArray( + [True, False, False, True], dtype=SparseDtype(bool, False) + ) + tm.assert_sp_array_equal(result, expected) + + # update fill value + result = a.astype(SparseDtype(bool, False)) + expected = SparseArray( + [True, False, False, True], dtype=SparseDtype(bool, False) + ) + tm.assert_sp_array_equal(result, expected) + + def test_astype_all(self, any_real_numpy_dtype): + vals = np.array([1, 2, 3]) + arr = SparseArray(vals, fill_value=1) + typ = np.dtype(any_real_numpy_dtype) + with tm.assert_produces_warning(FutureWarning, match="astype from Sparse"): + res = arr.astype(typ) + assert res.dtype == SparseDtype(typ, 1) + assert res.sp_values.dtype == typ + + tm.assert_numpy_array_equal(np.asarray(res.to_dense()), vals.astype(typ)) + + @pytest.mark.parametrize( + "arr, dtype, expected", + [ + ( + SparseArray([0, 1]), + "float", + SparseArray([0.0, 1.0], dtype=SparseDtype(float, 0.0)), + ), + (SparseArray([0, 1]), bool, SparseArray([False, True])), + ( + SparseArray([0, 1], fill_value=1), + bool, + SparseArray([False, True], dtype=SparseDtype(bool, True)), + ), + pytest.param( + SparseArray([0, 1]), + "datetime64[ns]", + SparseArray( + np.array([0, 1], dtype="datetime64[ns]"), + dtype=SparseDtype("datetime64[ns]", Timestamp("1970")), + ), + marks=[pytest.mark.xfail(reason="NumPy-7619")], + ), + ( + SparseArray([0, 1, 10]), + str, + SparseArray(["0", "1", "10"], dtype=SparseDtype(str, "0")), + ), + (SparseArray(["10", "20"]), float, SparseArray([10.0, 20.0])), + ( + SparseArray([0, 1, 0]), + object, + SparseArray([0, 1, 0], dtype=SparseDtype(object, 0)), + ), + ], + ) + def test_astype_more(self, arr, dtype, expected): + + if isinstance(dtype, SparseDtype): + warn = None + else: + warn = FutureWarning + + with tm.assert_produces_warning(warn, match="astype from SparseDtype"): + result = arr.astype(dtype) + tm.assert_sp_array_equal(result, expected) + + def test_astype_nan_raises(self): + arr = SparseArray([1.0, np.nan]) + with pytest.raises(ValueError, match="Cannot convert non-finite"): + msg = "astype from SparseDtype" + with tm.assert_produces_warning(FutureWarning, match=msg): + arr.astype(int) + + def test_astype_copy_false(self): + # GH#34456 bug caused by using .view instead of .astype in astype_nansafe + arr = SparseArray([1, 2, 3]) + + dtype = SparseDtype(float, 0) + + result = arr.astype(dtype, copy=False) + expected = SparseArray([1.0, 2.0, 3.0], fill_value=0.0) + tm.assert_sp_array_equal(result, expected) diff --git a/pandas/tests/arrays/sparse/test_constructors.py b/pandas/tests/arrays/sparse/test_constructors.py new file mode 100644 index 0000000000000..c1fcda4fcd121 --- /dev/null +++ b/pandas/tests/arrays/sparse/test_constructors.py @@ -0,0 +1,307 @@ +import numpy as np +import pytest + +from pandas._libs.sparse import IntIndex +import pandas.util._test_decorators as td + +import pandas as pd +from pandas import isna +import pandas._testing as tm +from pandas.core.arrays.sparse import ( + SparseArray, + SparseDtype, +) + + +class TestConstructors: + def test_constructor_dtype(self): + arr = SparseArray([np.nan, 1, 2, np.nan]) + assert arr.dtype == SparseDtype(np.float64, np.nan) + assert arr.dtype.subtype == np.float64 + assert np.isnan(arr.fill_value) + + arr = SparseArray([np.nan, 1, 2, np.nan], fill_value=0) + assert arr.dtype == SparseDtype(np.float64, 0) + assert arr.fill_value == 0 + + arr = SparseArray([0, 1, 2, 4], dtype=np.float64) + assert arr.dtype == SparseDtype(np.float64, np.nan) + assert np.isnan(arr.fill_value) + + arr = SparseArray([0, 1, 2, 4], dtype=np.int64) + assert arr.dtype == SparseDtype(np.int64, 0) + assert arr.fill_value == 0 + + arr = SparseArray([0, 1, 2, 4], fill_value=0, dtype=np.int64) + assert arr.dtype == SparseDtype(np.int64, 0) + assert arr.fill_value == 0 + + arr = SparseArray([0, 1, 2, 4], dtype=None) + assert arr.dtype == SparseDtype(np.int64, 0) + assert arr.fill_value == 0 + + arr = SparseArray([0, 1, 2, 4], fill_value=0, dtype=None) + assert arr.dtype == SparseDtype(np.int64, 0) + assert arr.fill_value == 0 + + def test_constructor_dtype_str(self): + result = SparseArray([1, 2, 3], dtype="int") + expected = SparseArray([1, 2, 3], dtype=int) + tm.assert_sp_array_equal(result, expected) + + def test_constructor_sparse_dtype(self): + result = SparseArray([1, 0, 0, 1], dtype=SparseDtype("int64", -1)) + expected = SparseArray([1, 0, 0, 1], fill_value=-1, dtype=np.int64) + tm.assert_sp_array_equal(result, expected) + assert result.sp_values.dtype == np.dtype("int64") + + def test_constructor_sparse_dtype_str(self): + result = SparseArray([1, 0, 0, 1], dtype="Sparse[int32]") + expected = SparseArray([1, 0, 0, 1], dtype=np.int32) + tm.assert_sp_array_equal(result, expected) + assert result.sp_values.dtype == np.dtype("int32") + + def test_constructor_object_dtype(self): + # GH#11856 + arr = SparseArray(["A", "A", np.nan, "B"], dtype=object) + assert arr.dtype == SparseDtype(object) + assert np.isnan(arr.fill_value) + + arr = SparseArray(["A", "A", np.nan, "B"], dtype=object, fill_value="A") + assert arr.dtype == SparseDtype(object, "A") + assert arr.fill_value == "A" + + # GH#17574 + data = [False, 0, 100.0, 0.0] + arr = SparseArray(data, dtype=object, fill_value=False) + assert arr.dtype == SparseDtype(object, False) + assert arr.fill_value is False + arr_expected = np.array(data, dtype=object) + it = (type(x) == type(y) and x == y for x, y in zip(arr, arr_expected)) + assert np.fromiter(it, dtype=np.bool_).all() + + @pytest.mark.parametrize("dtype", [SparseDtype(int, 0), int]) + def test_constructor_na_dtype(self, dtype): + with pytest.raises(ValueError, match="Cannot convert"): + SparseArray([0, 1, np.nan], dtype=dtype) + + def test_constructor_warns_when_losing_timezone(self): + # GH#32501 warn when losing timezone information + dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific") + + expected = SparseArray(np.asarray(dti, dtype="datetime64[ns]")) + + with tm.assert_produces_warning(UserWarning): + result = SparseArray(dti) + + tm.assert_sp_array_equal(result, expected) + + with tm.assert_produces_warning(UserWarning): + result = SparseArray(pd.Series(dti)) + + tm.assert_sp_array_equal(result, expected) + + def test_constructor_spindex_dtype(self): + arr = SparseArray(data=[1, 2], sparse_index=IntIndex(4, [1, 2])) + # TODO: actionable? + # XXX: Behavior change: specifying SparseIndex no longer changes the + # fill_value + expected = SparseArray([0, 1, 2, 0], kind="integer") + tm.assert_sp_array_equal(arr, expected) + assert arr.dtype == SparseDtype(np.int64) + assert arr.fill_value == 0 + + arr = SparseArray( + data=[1, 2, 3], + sparse_index=IntIndex(4, [1, 2, 3]), + dtype=np.int64, + fill_value=0, + ) + exp = SparseArray([0, 1, 2, 3], dtype=np.int64, fill_value=0) + tm.assert_sp_array_equal(arr, exp) + assert arr.dtype == SparseDtype(np.int64) + assert arr.fill_value == 0 + + arr = SparseArray( + data=[1, 2], sparse_index=IntIndex(4, [1, 2]), fill_value=0, dtype=np.int64 + ) + exp = SparseArray([0, 1, 2, 0], fill_value=0, dtype=np.int64) + tm.assert_sp_array_equal(arr, exp) + assert arr.dtype == SparseDtype(np.int64) + assert arr.fill_value == 0 + + arr = SparseArray( + data=[1, 2, 3], + sparse_index=IntIndex(4, [1, 2, 3]), + dtype=None, + fill_value=0, + ) + exp = SparseArray([0, 1, 2, 3], dtype=None) + tm.assert_sp_array_equal(arr, exp) + assert arr.dtype == SparseDtype(np.int64) + assert arr.fill_value == 0 + + @pytest.mark.parametrize("sparse_index", [None, IntIndex(1, [0])]) + def test_constructor_spindex_dtype_scalar(self, sparse_index): + # scalar input + arr = SparseArray(data=1, sparse_index=sparse_index, dtype=None) + exp = SparseArray([1], dtype=None) + tm.assert_sp_array_equal(arr, exp) + assert arr.dtype == SparseDtype(np.int64) + assert arr.fill_value == 0 + + arr = SparseArray(data=1, sparse_index=IntIndex(1, [0]), dtype=None) + exp = SparseArray([1], dtype=None) + tm.assert_sp_array_equal(arr, exp) + assert arr.dtype == SparseDtype(np.int64) + assert arr.fill_value == 0 + + def test_constructor_spindex_dtype_scalar_broadcasts(self): + arr = SparseArray( + data=[1, 2], sparse_index=IntIndex(4, [1, 2]), fill_value=0, dtype=None + ) + exp = SparseArray([0, 1, 2, 0], fill_value=0, dtype=None) + tm.assert_sp_array_equal(arr, exp) + assert arr.dtype == SparseDtype(np.int64) + assert arr.fill_value == 0 + + @pytest.mark.parametrize( + "data, fill_value", + [ + (np.array([1, 2]), 0), + (np.array([1.0, 2.0]), np.nan), + ([True, False], False), + ([pd.Timestamp("2017-01-01")], pd.NaT), + ], + ) + def test_constructor_inferred_fill_value(self, data, fill_value): + result = SparseArray(data).fill_value + + if isna(fill_value): + assert isna(result) + else: + assert result == fill_value + + @pytest.mark.parametrize("format", ["coo", "csc", "csr"]) + @pytest.mark.parametrize("size", [0, 10]) + @td.skip_if_no_scipy + def test_from_spmatrix(self, size, format): + import scipy.sparse + + mat = scipy.sparse.random(size, 1, density=0.5, format=format) + result = SparseArray.from_spmatrix(mat) + + result = np.asarray(result) + expected = mat.toarray().ravel() + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("format", ["coo", "csc", "csr"]) + @td.skip_if_no_scipy + def test_from_spmatrix_including_explicit_zero(self, format): + import scipy.sparse + + mat = scipy.sparse.random(10, 1, density=0.5, format=format) + mat.data[0] = 0 + result = SparseArray.from_spmatrix(mat) + + result = np.asarray(result) + expected = mat.toarray().ravel() + tm.assert_numpy_array_equal(result, expected) + + @td.skip_if_no_scipy + def test_from_spmatrix_raises(self): + import scipy.sparse + + mat = scipy.sparse.eye(5, 4, format="csc") + + with pytest.raises(ValueError, match="not '4'"): + SparseArray.from_spmatrix(mat) + + @pytest.mark.parametrize( + "scalar,dtype", + [ + (False, SparseDtype(bool, False)), + (0.0, SparseDtype("float64", 0)), + (1, SparseDtype("int64", 1)), + ("z", SparseDtype("object", "z")), + ], + ) + def test_scalar_with_index_infer_dtype(self, scalar, dtype): + # GH#19163 + with tm.assert_produces_warning( + FutureWarning, match="The index argument has been deprecated" + ): + arr = SparseArray(scalar, index=[1, 2, 3], fill_value=scalar) + exp = SparseArray([scalar, scalar, scalar], fill_value=scalar) + + tm.assert_sp_array_equal(arr, exp) + + assert arr.dtype == dtype + assert exp.dtype == dtype + + def test_constructor_from_too_large_array(self): + with pytest.raises(TypeError, match="expected dimension <= 1 data"): + SparseArray(np.arange(10).reshape((2, 5))) + + def test_constructor_from_sparse(self): + zarr = SparseArray([0, 0, 1, 2, 3, 0, 4, 5, 0, 6], fill_value=0) + res = SparseArray(zarr) + assert res.fill_value == 0 + tm.assert_almost_equal(res.sp_values, zarr.sp_values) + + def test_constructor_copy(self): + arr_data = np.array([np.nan, np.nan, 1, 2, 3, np.nan, 4, 5, np.nan, 6]) + arr = SparseArray(arr_data) + + cp = SparseArray(arr, copy=True) + cp.sp_values[:3] = 0 + assert not (arr.sp_values[:3] == 0).any() + + not_copy = SparseArray(arr) + not_copy.sp_values[:3] = 0 + assert (arr.sp_values[:3] == 0).all() + + def test_constructor_bool(self): + # GH#10648 + data = np.array([False, False, True, True, False, False]) + arr = SparseArray(data, fill_value=False, dtype=bool) + + assert arr.dtype == SparseDtype(bool) + tm.assert_numpy_array_equal(arr.sp_values, np.array([True, True])) + # Behavior change: np.asarray densifies. + # tm.assert_numpy_array_equal(arr.sp_values, np.asarray(arr)) + tm.assert_numpy_array_equal(arr.sp_index.indices, np.array([2, 3], np.int32)) + + dense = arr.to_dense() + assert dense.dtype == bool + tm.assert_numpy_array_equal(dense, data) + + def test_constructor_bool_fill_value(self): + arr = SparseArray([True, False, True], dtype=None) + assert arr.dtype == SparseDtype(np.bool_) + assert not arr.fill_value + + arr = SparseArray([True, False, True], dtype=np.bool_) + assert arr.dtype == SparseDtype(np.bool_) + assert not arr.fill_value + + arr = SparseArray([True, False, True], dtype=np.bool_, fill_value=True) + assert arr.dtype == SparseDtype(np.bool_, True) + assert arr.fill_value + + def test_constructor_float32(self): + # GH#10648 + data = np.array([1.0, np.nan, 3], dtype=np.float32) + arr = SparseArray(data, dtype=np.float32) + + assert arr.dtype == SparseDtype(np.float32) + tm.assert_numpy_array_equal(arr.sp_values, np.array([1, 3], dtype=np.float32)) + # Behavior change: np.asarray densifies. + # tm.assert_numpy_array_equal(arr.sp_values, np.asarray(arr)) + tm.assert_numpy_array_equal( + arr.sp_index.indices, np.array([0, 2], dtype=np.int32) + ) + + dense = arr.to_dense() + assert dense.dtype == np.float32 + tm.assert_numpy_array_equal(dense, data) diff --git a/pandas/tests/arrays/sparse/test_indexing.py b/pandas/tests/arrays/sparse/test_indexing.py new file mode 100644 index 0000000000000..2794fe33e53e5 --- /dev/null +++ b/pandas/tests/arrays/sparse/test_indexing.py @@ -0,0 +1,292 @@ +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays.sparse import ( + SparseArray, + SparseDtype, +) + +arr_data = np.array([np.nan, np.nan, 1, 2, 3, np.nan, 4, 5, np.nan, 6]) +arr = SparseArray(arr_data) + + +class TestGetitem: + def test_getitem(self): + def _checkit(i): + tm.assert_almost_equal(arr[i], arr.to_dense()[i]) + + for i in range(len(arr)): + _checkit(i) + _checkit(-i) + + def test_getitem_arraylike_mask(self): + arr = SparseArray([0, 1, 2]) + result = arr[[True, False, True]] + expected = SparseArray([0, 2]) + tm.assert_sp_array_equal(result, expected) + + @pytest.mark.parametrize( + "slc", + [ + np.s_[:], + np.s_[1:10], + np.s_[1:100], + np.s_[10:1], + np.s_[:-3], + np.s_[-5:-4], + np.s_[:-12], + np.s_[-12:], + np.s_[2:], + np.s_[2::3], + np.s_[::2], + np.s_[::-1], + np.s_[::-2], + np.s_[1:6:2], + np.s_[:-6:-2], + ], + ) + @pytest.mark.parametrize( + "as_dense", [[np.nan] * 10, [1] * 10, [np.nan] * 5 + [1] * 5, []] + ) + def test_getslice(self, slc, as_dense): + as_dense = np.array(as_dense) + arr = SparseArray(as_dense) + + result = arr[slc] + expected = SparseArray(as_dense[slc]) + + tm.assert_sp_array_equal(result, expected) + + def test_getslice_tuple(self): + dense = np.array([np.nan, 0, 3, 4, 0, 5, np.nan, np.nan, 0]) + + sparse = SparseArray(dense) + res = sparse[(slice(4, None),)] + exp = SparseArray(dense[4:]) + tm.assert_sp_array_equal(res, exp) + + sparse = SparseArray(dense, fill_value=0) + res = sparse[(slice(4, None),)] + exp = SparseArray(dense[4:], fill_value=0) + tm.assert_sp_array_equal(res, exp) + + msg = "too many indices for array" + with pytest.raises(IndexError, match=msg): + sparse[4:, :] + + with pytest.raises(IndexError, match=msg): + # check numpy compat + dense[4:, :] + + def test_boolean_slice_empty(self): + arr = SparseArray([0, 1, 2]) + res = arr[[False, False, False]] + assert res.dtype == arr.dtype + + def test_getitem_bool_sparse_array(self): + # GH 23122 + spar_bool = SparseArray([False, True] * 5, dtype=np.bool8, fill_value=True) + exp = SparseArray([np.nan, 2, np.nan, 5, 6]) + tm.assert_sp_array_equal(arr[spar_bool], exp) + + spar_bool = ~spar_bool + res = arr[spar_bool] + exp = SparseArray([np.nan, 1, 3, 4, np.nan]) + tm.assert_sp_array_equal(res, exp) + + spar_bool = SparseArray( + [False, True, np.nan] * 3, dtype=np.bool8, fill_value=np.nan + ) + res = arr[spar_bool] + exp = SparseArray([np.nan, 3, 5]) + tm.assert_sp_array_equal(res, exp) + + def test_getitem_bool_sparse_array_as_comparison(self): + # GH 45110 + arr = SparseArray([1, 2, 3, 4, np.nan, np.nan], fill_value=np.nan) + res = arr[arr > 2] + exp = SparseArray([3.0, 4.0], fill_value=np.nan) + tm.assert_sp_array_equal(res, exp) + + def test_get_item(self): + zarr = SparseArray([0, 0, 1, 2, 3, 0, 4, 5, 0, 6], fill_value=0) + + assert np.isnan(arr[1]) + assert arr[2] == 1 + assert arr[7] == 5 + + assert zarr[0] == 0 + assert zarr[2] == 1 + assert zarr[7] == 5 + + errmsg = "must be an integer between -10 and 10" + + with pytest.raises(IndexError, match=errmsg): + arr[11] + + with pytest.raises(IndexError, match=errmsg): + arr[-11] + + assert arr[-1] == arr[len(arr) - 1] + + +class TestSetitem: + def test_set_item(self): + arr = SparseArray(arr_data).copy() + + def setitem(): + arr[5] = 3 + + def setslice(): + arr[1:5] = 2 + + with pytest.raises(TypeError, match="assignment via setitem"): + setitem() + + with pytest.raises(TypeError, match="assignment via setitem"): + setslice() + + +class TestTake: + def test_take_scalar_raises(self): + msg = "'indices' must be an array, not a scalar '2'." + with pytest.raises(ValueError, match=msg): + arr.take(2) + + def test_take(self): + exp = SparseArray(np.take(arr_data, [2, 3])) + tm.assert_sp_array_equal(arr.take([2, 3]), exp) + + exp = SparseArray(np.take(arr_data, [0, 1, 2])) + tm.assert_sp_array_equal(arr.take([0, 1, 2]), exp) + + def test_take_all_empty(self): + a = pd.array([0, 0], dtype=SparseDtype("int64")) + result = a.take([0, 1], allow_fill=True, fill_value=np.nan) + tm.assert_sp_array_equal(a, result) + + def test_take_fill_value(self): + data = np.array([1, np.nan, 0, 3, 0]) + sparse = SparseArray(data, fill_value=0) + + exp = SparseArray(np.take(data, [0]), fill_value=0) + tm.assert_sp_array_equal(sparse.take([0]), exp) + + exp = SparseArray(np.take(data, [1, 3, 4]), fill_value=0) + tm.assert_sp_array_equal(sparse.take([1, 3, 4]), exp) + + def test_take_negative(self): + exp = SparseArray(np.take(arr_data, [-1])) + tm.assert_sp_array_equal(arr.take([-1]), exp) + + exp = SparseArray(np.take(arr_data, [-4, -3, -2])) + tm.assert_sp_array_equal(arr.take([-4, -3, -2]), exp) + + def test_bad_take(self): + with pytest.raises(IndexError, match="bounds"): + arr.take([11]) + + def test_take_filling(self): + # similar tests as GH 12631 + sparse = SparseArray([np.nan, np.nan, 1, np.nan, 4]) + result = sparse.take(np.array([1, 0, -1])) + expected = SparseArray([np.nan, np.nan, 4]) + tm.assert_sp_array_equal(result, expected) + + # TODO: actionable? + # XXX: test change: fill_value=True -> allow_fill=True + result = sparse.take(np.array([1, 0, -1]), allow_fill=True) + expected = SparseArray([np.nan, np.nan, np.nan]) + tm.assert_sp_array_equal(result, expected) + + # allow_fill=False + result = sparse.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) + expected = SparseArray([np.nan, np.nan, 4]) + tm.assert_sp_array_equal(result, expected) + + msg = "Invalid value in 'indices'" + with pytest.raises(ValueError, match=msg): + sparse.take(np.array([1, 0, -2]), allow_fill=True) + + with pytest.raises(ValueError, match=msg): + sparse.take(np.array([1, 0, -5]), allow_fill=True) + + msg = "out of bounds value in 'indices'" + with pytest.raises(IndexError, match=msg): + sparse.take(np.array([1, -6])) + with pytest.raises(IndexError, match=msg): + sparse.take(np.array([1, 5])) + with pytest.raises(IndexError, match=msg): + sparse.take(np.array([1, 5]), allow_fill=True) + + def test_take_filling_fill_value(self): + # same tests as GH#12631 + sparse = SparseArray([np.nan, 0, 1, 0, 4], fill_value=0) + result = sparse.take(np.array([1, 0, -1])) + expected = SparseArray([0, np.nan, 4], fill_value=0) + tm.assert_sp_array_equal(result, expected) + + # fill_value + result = sparse.take(np.array([1, 0, -1]), allow_fill=True) + # TODO: actionable? + # XXX: behavior change. + # the old way of filling self.fill_value doesn't follow EA rules. + # It's supposed to be self.dtype.na_value (nan in this case) + expected = SparseArray([0, np.nan, np.nan], fill_value=0) + tm.assert_sp_array_equal(result, expected) + + # allow_fill=False + result = sparse.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) + expected = SparseArray([0, np.nan, 4], fill_value=0) + tm.assert_sp_array_equal(result, expected) + + msg = "Invalid value in 'indices'." + with pytest.raises(ValueError, match=msg): + sparse.take(np.array([1, 0, -2]), allow_fill=True) + with pytest.raises(ValueError, match=msg): + sparse.take(np.array([1, 0, -5]), allow_fill=True) + + msg = "out of bounds value in 'indices'" + with pytest.raises(IndexError, match=msg): + sparse.take(np.array([1, -6])) + with pytest.raises(IndexError, match=msg): + sparse.take(np.array([1, 5])) + with pytest.raises(IndexError, match=msg): + sparse.take(np.array([1, 5]), fill_value=True) + + @pytest.mark.parametrize("kind", ["block", "integer"]) + def test_take_filling_all_nan(self, kind): + sparse = SparseArray([np.nan, np.nan, np.nan, np.nan, np.nan], kind=kind) + result = sparse.take(np.array([1, 0, -1])) + expected = SparseArray([np.nan, np.nan, np.nan], kind=kind) + tm.assert_sp_array_equal(result, expected) + + result = sparse.take(np.array([1, 0, -1]), fill_value=True) + expected = SparseArray([np.nan, np.nan, np.nan], kind=kind) + tm.assert_sp_array_equal(result, expected) + + msg = "out of bounds value in 'indices'" + with pytest.raises(IndexError, match=msg): + sparse.take(np.array([1, -6])) + with pytest.raises(IndexError, match=msg): + sparse.take(np.array([1, 5])) + with pytest.raises(IndexError, match=msg): + sparse.take(np.array([1, 5]), fill_value=True) + + +class TestWhere: + def test_where_retain_fill_value(self): + # GH#45691 don't lose fill_value on _where + arr = SparseArray([np.nan, 1.0], fill_value=0) + + mask = np.array([True, False]) + + res = arr._where(~mask, 1) + exp = SparseArray([1, 1.0], fill_value=0) + tm.assert_sp_array_equal(res, exp) + + ser = pd.Series(arr) + res = ser.where(~mask, 1) + tm.assert_series_equal(res, pd.Series(exp)) diff --git a/pandas/tests/arrays/sparse/test_reductions.py b/pandas/tests/arrays/sparse/test_reductions.py new file mode 100644 index 0000000000000..a33a282bb4869 --- /dev/null +++ b/pandas/tests/arrays/sparse/test_reductions.py @@ -0,0 +1,270 @@ +import numpy as np +import pytest + +from pandas import ( + NaT, + Timestamp, + isna, +) +from pandas.core.arrays.sparse import ( + SparseArray, + SparseDtype, +) + + +class TestReductions: + @pytest.mark.parametrize( + "data,pos,neg", + [ + ([True, True, True], True, False), + ([1, 2, 1], 1, 0), + ([1.0, 2.0, 1.0], 1.0, 0.0), + ], + ) + def test_all(self, data, pos, neg): + # GH#17570 + out = SparseArray(data).all() + assert out + + out = SparseArray(data, fill_value=pos).all() + assert out + + data[1] = neg + out = SparseArray(data).all() + assert not out + + out = SparseArray(data, fill_value=pos).all() + assert not out + + @pytest.mark.parametrize( + "data,pos,neg", + [ + ([True, True, True], True, False), + ([1, 2, 1], 1, 0), + ([1.0, 2.0, 1.0], 1.0, 0.0), + ], + ) + def test_numpy_all(self, data, pos, neg): + # GH#17570 + out = np.all(SparseArray(data)) + assert out + + out = np.all(SparseArray(data, fill_value=pos)) + assert out + + data[1] = neg + out = np.all(SparseArray(data)) + assert not out + + out = np.all(SparseArray(data, fill_value=pos)) + assert not out + + # raises with a different message on py2. + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.all(SparseArray(data), out=np.array([])) + + @pytest.mark.parametrize( + "data,pos,neg", + [ + ([False, True, False], True, False), + ([0, 2, 0], 2, 0), + ([0.0, 2.0, 0.0], 2.0, 0.0), + ], + ) + def test_any(self, data, pos, neg): + # GH#17570 + out = SparseArray(data).any() + assert out + + out = SparseArray(data, fill_value=pos).any() + assert out + + data[1] = neg + out = SparseArray(data).any() + assert not out + + out = SparseArray(data, fill_value=pos).any() + assert not out + + @pytest.mark.parametrize( + "data,pos,neg", + [ + ([False, True, False], True, False), + ([0, 2, 0], 2, 0), + ([0.0, 2.0, 0.0], 2.0, 0.0), + ], + ) + def test_numpy_any(self, data, pos, neg): + # GH#17570 + out = np.any(SparseArray(data)) + assert out + + out = np.any(SparseArray(data, fill_value=pos)) + assert out + + data[1] = neg + out = np.any(SparseArray(data)) + assert not out + + out = np.any(SparseArray(data, fill_value=pos)) + assert not out + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.any(SparseArray(data), out=out) + + def test_sum(self): + data = np.arange(10).astype(float) + out = SparseArray(data).sum() + assert out == 45.0 + + data[5] = np.nan + out = SparseArray(data, fill_value=2).sum() + assert out == 40.0 + + out = SparseArray(data, fill_value=np.nan).sum() + assert out == 40.0 + + @pytest.mark.parametrize( + "arr", + [np.array([0, 1, np.nan, 1]), np.array([0, 1, 1])], + ) + @pytest.mark.parametrize("fill_value", [0, 1, np.nan]) + @pytest.mark.parametrize("min_count, expected", [(3, 2), (4, np.nan)]) + def test_sum_min_count(self, arr, fill_value, min_count, expected): + # GH#25777 + sparray = SparseArray(arr, fill_value=fill_value) + result = sparray.sum(min_count=min_count) + if np.isnan(expected): + assert np.isnan(result) + else: + assert result == expected + + def test_bool_sum_min_count(self): + spar_bool = SparseArray([False, True] * 5, dtype=np.bool8, fill_value=True) + res = spar_bool.sum(min_count=1) + assert res == 5 + res = spar_bool.sum(min_count=11) + assert isna(res) + + def test_numpy_sum(self): + data = np.arange(10).astype(float) + out = np.sum(SparseArray(data)) + assert out == 45.0 + + data[5] = np.nan + out = np.sum(SparseArray(data, fill_value=2)) + assert out == 40.0 + + out = np.sum(SparseArray(data, fill_value=np.nan)) + assert out == 40.0 + + msg = "the 'dtype' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.sum(SparseArray(data), dtype=np.int64) + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.sum(SparseArray(data), out=out) + + def test_mean(self): + data = np.arange(10).astype(float) + out = SparseArray(data).mean() + assert out == 4.5 + + data[5] = np.nan + out = SparseArray(data).mean() + assert out == 40.0 / 9 + + def test_numpy_mean(self): + data = np.arange(10).astype(float) + out = np.mean(SparseArray(data)) + assert out == 4.5 + + data[5] = np.nan + out = np.mean(SparseArray(data)) + assert out == 40.0 / 9 + + msg = "the 'dtype' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.mean(SparseArray(data), dtype=np.int64) + + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + np.mean(SparseArray(data), out=out) + + +class TestMinMax: + @pytest.mark.parametrize( + "raw_data,max_expected,min_expected", + [ + (np.arange(5.0), [4], [0]), + (-np.arange(5.0), [0], [-4]), + (np.array([0, 1, 2, np.nan, 4]), [4], [0]), + (np.array([np.nan] * 5), [np.nan], [np.nan]), + (np.array([]), [np.nan], [np.nan]), + ], + ) + def test_nan_fill_value(self, raw_data, max_expected, min_expected): + arr = SparseArray(raw_data) + max_result = arr.max() + min_result = arr.min() + assert max_result in max_expected + assert min_result in min_expected + + max_result = arr.max(skipna=False) + min_result = arr.min(skipna=False) + if np.isnan(raw_data).any(): + assert np.isnan(max_result) + assert np.isnan(min_result) + else: + assert max_result in max_expected + assert min_result in min_expected + + @pytest.mark.parametrize( + "fill_value,max_expected,min_expected", + [ + (100, 100, 0), + (-100, 1, -100), + ], + ) + def test_fill_value(self, fill_value, max_expected, min_expected): + arr = SparseArray( + np.array([fill_value, 0, 1]), dtype=SparseDtype("int", fill_value) + ) + max_result = arr.max() + assert max_result == max_expected + + min_result = arr.min() + assert min_result == min_expected + + def test_only_fill_value(self): + fv = 100 + arr = SparseArray(np.array([fv, fv, fv]), dtype=SparseDtype("int", fv)) + assert len(arr._valid_sp_values) == 0 + + assert arr.max() == fv + assert arr.min() == fv + assert arr.max(skipna=False) == fv + assert arr.min(skipna=False) == fv + + @pytest.mark.parametrize("func", ["min", "max"]) + @pytest.mark.parametrize("data", [np.array([]), np.array([np.nan, np.nan])]) + @pytest.mark.parametrize( + "dtype,expected", + [ + (SparseDtype(np.float64, np.nan), np.nan), + (SparseDtype(np.float64, 5.0), np.nan), + (SparseDtype("datetime64[ns]", NaT), NaT), + (SparseDtype("datetime64[ns]", Timestamp("2018-05-05")), NaT), + ], + ) + def test_na_value_if_no_valid_values(self, func, data, dtype, expected): + arr = SparseArray(data, dtype=dtype) + result = getattr(arr, func)() + if expected is NaT: + # TODO: pin down whether we wrap datetime64("NaT") + assert result is NaT or np.isnat(result) + else: + assert np.isnan(result) diff --git a/pandas/tests/arrays/sparse/test_unary.py b/pandas/tests/arrays/sparse/test_unary.py new file mode 100644 index 0000000000000..a99dbb10a1433 --- /dev/null +++ b/pandas/tests/arrays/sparse/test_unary.py @@ -0,0 +1,72 @@ +import operator + +import numpy as np +import pytest + +import pandas as pd +import pandas._testing as tm +from pandas.core.arrays import SparseArray + + +@pytest.mark.parametrize("fill_value", [0, np.nan]) +@pytest.mark.parametrize("op", [operator.pos, operator.neg]) +def test_unary_op(op, fill_value): + arr = np.array([0, 1, np.nan, 2]) + sparray = SparseArray(arr, fill_value=fill_value) + result = op(sparray) + expected = SparseArray(op(arr), fill_value=op(fill_value)) + tm.assert_sp_array_equal(result, expected) + + +@pytest.mark.parametrize("fill_value", [True, False]) +def test_invert(fill_value): + arr = np.array([True, False, False, True]) + sparray = SparseArray(arr, fill_value=fill_value) + result = ~sparray + expected = SparseArray(~arr, fill_value=not fill_value) + tm.assert_sp_array_equal(result, expected) + + result = ~pd.Series(sparray) + expected = pd.Series(expected) + tm.assert_series_equal(result, expected) + + result = ~pd.DataFrame({"A": sparray}) + expected = pd.DataFrame({"A": expected}) + tm.assert_frame_equal(result, expected) + + +class TestUnaryMethods: + def test_neg_operator(self): + arr = SparseArray([-1, -2, np.nan, 3], fill_value=np.nan, dtype=np.int8) + res = -arr + exp = SparseArray([1, 2, np.nan, -3], fill_value=np.nan, dtype=np.int8) + tm.assert_sp_array_equal(exp, res) + + arr = SparseArray([-1, -2, 1, 3], fill_value=-1, dtype=np.int8) + res = -arr + exp = SparseArray([1, 2, -1, -3], fill_value=1, dtype=np.int8) + tm.assert_sp_array_equal(exp, res) + + def test_abs_operator(self): + arr = SparseArray([-1, -2, np.nan, 3], fill_value=np.nan, dtype=np.int8) + res = abs(arr) + exp = SparseArray([1, 2, np.nan, 3], fill_value=np.nan, dtype=np.int8) + tm.assert_sp_array_equal(exp, res) + + arr = SparseArray([-1, -2, 1, 3], fill_value=-1, dtype=np.int8) + res = abs(arr) + exp = SparseArray([1, 2, 1, 3], fill_value=1, dtype=np.int8) + tm.assert_sp_array_equal(exp, res) + + def test_invert_operator(self): + arr = SparseArray([False, True, False, True], fill_value=False, dtype=np.bool8) + res = ~arr + exp = SparseArray( + np.invert([False, True, False, True]), fill_value=True, dtype=np.bool8 + ) + res = ~arr + tm.assert_sp_array_equal(exp, res) + + arr = SparseArray([0, 1, 0, 2, 3, 0], fill_value=0, dtype=np.int32) + res = ~arr + exp = SparseArray([-1, -2, -1, -3, -4, -1], fill_value=-1, dtype=np.int32)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry Sits on top of #45691
https://api.github.com/repos/pandas-dev/pandas/pulls/45693
2022-01-29T03:54:46Z
2022-01-29T22:54:04Z
2022-01-29T22:54:04Z
2022-01-29T23:04:15Z
TST: Remove unused fixtures
diff --git a/pandas/tests/apply/test_str.py b/pandas/tests/apply/test_str.py index 82997328529cd..f215df4c24206 100644 --- a/pandas/tests/apply/test_str.py +++ b/pandas/tests/apply/test_str.py @@ -55,7 +55,7 @@ def test_with_string_args(datetime_series): @pytest.mark.parametrize("op", ["mean", "median", "std", "var"]) @pytest.mark.parametrize("how", ["agg", "apply"]) -def test_apply_np_reducer(float_frame, op, how): +def test_apply_np_reducer(op, how): # GH 39116 float_frame = DataFrame({"a": [1, 2], "b": [3, 4]}) result = getattr(float_frame, how)(op) diff --git a/pandas/tests/arrays/categorical/common.py b/pandas/tests/arrays/categorical/common.py index 4ef9390656979..86d80c5476195 100644 --- a/pandas/tests/arrays/categorical/common.py +++ b/pandas/tests/arrays/categorical/common.py @@ -2,7 +2,7 @@ class TestCategorical: - def setup_method(self, method): + def setup_method(self): self.factor = Categorical( ["a", "b", "b", "a", "a", "c", "c", "c"], ordered=True ) diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py index 617d1861fa65a..26366178050cc 100644 --- a/pandas/tests/arrays/categorical/test_indexing.py +++ b/pandas/tests/arrays/categorical/test_indexing.py @@ -370,7 +370,7 @@ def array(self, dtype=None): yield -def test_series_at(non_coercible_categorical): +def test_series_at(): arr = Categorical(["a", "b", "c"]) ser = Series(arr) result = ser.at[0] diff --git a/pandas/tests/arrays/masked/test_arithmetic.py b/pandas/tests/arrays/masked/test_arithmetic.py index 6f6fc957d1303..379c339e0eab8 100644 --- a/pandas/tests/arrays/masked/test_arithmetic.py +++ b/pandas/tests/arrays/masked/test_arithmetic.py @@ -173,7 +173,7 @@ def test_error_len_mismatch(data, all_arithmetic_operators): @pytest.mark.parametrize("op", ["__neg__", "__abs__", "__invert__"]) -def test_unary_op_does_not_propagate_mask(data, op, request): +def test_unary_op_does_not_propagate_mask(data, op): # https://github.com/pandas-dev/pandas/issues/39943 data, _ = data ser = pd.Series(data) diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index 5874e817477a9..0e734f0c1a1e8 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -17,7 +17,7 @@ class TestSparseArray: - def setup_method(self, method): + def setup_method(self): self.arr_data = np.array([np.nan, np.nan, 1, 2, 3, np.nan, 4, 5, np.nan, 6]) self.arr = SparseArray(self.arr_data) self.zarr = SparseArray([0, 0, 1, 2, 3, 0, 4, 5, 0, 6], fill_value=0) diff --git a/pandas/tests/arrays/string_/test_string.py b/pandas/tests/arrays/string_/test_string.py index afeeee3d02f9d..8b2aea5c2e2e1 100644 --- a/pandas/tests/arrays/string_/test_string.py +++ b/pandas/tests/arrays/string_/test_string.py @@ -554,7 +554,7 @@ def test_to_numpy_na_value(dtype, nulls_fixture): tm.assert_numpy_array_equal(result, expected) -def test_isin(dtype, request, fixed_now_ts): +def test_isin(dtype, fixed_now_ts): s = pd.Series(["a", "b", None], dtype=dtype) result = s.isin(["a", "c"]) diff --git a/pandas/tests/config/test_config.py b/pandas/tests/config/test_config.py index 761c8535e6b4a..cc394bbb23d00 100644 --- a/pandas/tests/config/test_config.py +++ b/pandas/tests/config/test_config.py @@ -18,7 +18,7 @@ def setup_class(cls): cls.do = deepcopy(getattr(cls.cf, "_deprecated_options")) cls.ro = deepcopy(getattr(cls.cf, "_registered_options")) - def setup_method(self, method): + def setup_method(self): setattr(self.cf, "_global_config", {}) setattr(self.cf, "options", self.cf.DictWrapper(self.cf._global_config)) setattr(self.cf, "_deprecated_options", {}) @@ -30,7 +30,7 @@ def setup_method(self, method): # "chained_assignment" option, so re-register it. self.cf.register_option("chained_assignment", "raise") - def teardown_method(self, method): + def teardown_method(self): setattr(self.cf, "_global_config", self.gc) setattr(self.cf, "_deprecated_options", self.do) setattr(self.cf, "_registered_options", self.ro) diff --git a/pandas/tests/dtypes/cast/test_promote.py b/pandas/tests/dtypes/cast/test_promote.py index a514a9ce9b0e4..02bd03f5ea266 100644 --- a/pandas/tests/dtypes/cast/test_promote.py +++ b/pandas/tests/dtypes/cast/test_promote.py @@ -348,7 +348,7 @@ def test_maybe_promote_bytes_with_any(bytes_dtype, any_numpy_dtype_reduced): _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar) -def test_maybe_promote_any_with_bytes(any_numpy_dtype_reduced, bytes_dtype): +def test_maybe_promote_any_with_bytes(any_numpy_dtype_reduced): dtype = np.dtype(any_numpy_dtype_reduced) # create array of given dtype @@ -391,9 +391,7 @@ def test_maybe_promote_datetime64_with_any(datetime64_dtype, any_numpy_dtype_red ], ids=["pd.Timestamp", "np.datetime64", "datetime.datetime", "datetime.date"], ) -def test_maybe_promote_any_with_datetime64( - any_numpy_dtype_reduced, datetime64_dtype, fill_value -): +def test_maybe_promote_any_with_datetime64(any_numpy_dtype_reduced, fill_value): dtype = np.dtype(any_numpy_dtype_reduced) # filling datetime with anything but datetime casts to object @@ -465,9 +463,7 @@ def test_maybe_promote_timedelta64_with_any(timedelta64_dtype, any_numpy_dtype_r [pd.Timedelta(days=1), np.timedelta64(24, "h"), datetime.timedelta(1)], ids=["pd.Timedelta", "np.timedelta64", "datetime.timedelta"], ) -def test_maybe_promote_any_with_timedelta64( - any_numpy_dtype_reduced, timedelta64_dtype, fill_value -): +def test_maybe_promote_any_with_timedelta64(any_numpy_dtype_reduced, fill_value): dtype = np.dtype(any_numpy_dtype_reduced) # filling anything but timedelta with timedelta casts to object @@ -496,7 +492,7 @@ def test_maybe_promote_string_with_any(string_dtype, any_numpy_dtype_reduced): _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar) -def test_maybe_promote_any_with_string(any_numpy_dtype_reduced, string_dtype): +def test_maybe_promote_any_with_string(any_numpy_dtype_reduced): dtype = np.dtype(any_numpy_dtype_reduced) # create array of given dtype @@ -523,7 +519,7 @@ def test_maybe_promote_object_with_any(object_dtype, any_numpy_dtype_reduced): _check_promote(dtype, fill_value, expected_dtype, exp_val_for_scalar) -def test_maybe_promote_any_with_object(any_numpy_dtype_reduced, object_dtype): +def test_maybe_promote_any_with_object(any_numpy_dtype_reduced): dtype = np.dtype(any_numpy_dtype_reduced) # create array of object dtype from a scalar value (i.e. passing diff --git a/pandas/tests/dtypes/test_dtypes.py b/pandas/tests/dtypes/test_dtypes.py index 30447de874aaa..f077317e7ebbe 100644 --- a/pandas/tests/dtypes/test_dtypes.py +++ b/pandas/tests/dtypes/test_dtypes.py @@ -848,7 +848,7 @@ def test_categories(self): tm.assert_index_equal(result.categories, pd.Index(["a", "b", "c"])) assert result.ordered is False - def test_equal_but_different(self, ordered): + def test_equal_but_different(self): c1 = CategoricalDtype([1, 2, 3]) c2 = CategoricalDtype([1.0, 2.0, 3.0]) assert c1 is not c2 diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py index 7a822bd3c607a..221710fbffca1 100644 --- a/pandas/tests/extension/base/setitem.py +++ b/pandas/tests/extension/base/setitem.py @@ -357,7 +357,7 @@ def test_setitem_series(self, data, full_indexer): ) self.assert_series_equal(result, expected) - def test_setitem_frame_2d_values(self, data, request): + def test_setitem_frame_2d_values(self, data): # GH#44514 df = pd.DataFrame({"A": data}) orig = df.copy() diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index 4f453986ad2c3..37acbb4e92dfb 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -54,7 +54,7 @@ def data(request): @pytest.fixture -def data_for_twos(request): +def data_for_twos(): return SparseArray(np.ones(100) * 2) diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index c8a22e48d16c1..f1e7b18a73173 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -397,7 +397,7 @@ def test_setitem_frame_length_0_str_key(self, indexer): expected["A"] = expected["A"].astype("object") tm.assert_frame_equal(df, expected) - def test_setitem_frame_duplicate_columns(self, using_array_manager, request): + def test_setitem_frame_duplicate_columns(self, using_array_manager): # GH#15695 cols = ["A", "B", "C"] * 2 df = DataFrame(index=range(3), columns=cols) @@ -1099,7 +1099,7 @@ def test_setitem_duplicate_columns_not_inplace(self): @pytest.mark.parametrize( "value", [1, np.array([[1], [1]], dtype="int64"), [[1], [1]]] ) - def test_setitem_same_dtype_not_inplace(self, value, using_array_manager, request): + def test_setitem_same_dtype_not_inplace(self, value, using_array_manager): # GH#39510 cols = ["A", "B"] df = DataFrame(0, index=[0, 1], columns=cols) diff --git a/pandas/tests/frame/methods/test_interpolate.py b/pandas/tests/frame/methods/test_interpolate.py index 37fb0754baffd..6566d426d9a6b 100644 --- a/pandas/tests/frame/methods/test_interpolate.py +++ b/pandas/tests/frame/methods/test_interpolate.py @@ -320,7 +320,7 @@ def test_interp_ignore_all_good(self): result = df[["B", "D"]].interpolate(downcast=None) tm.assert_frame_equal(result, df[["B", "D"]]) - def test_interp_time_inplace_axis(self, axis): + def test_interp_time_inplace_axis(self): # GH 9687 periods = 5 idx = date_range(start="2014-01-01", periods=periods) diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py index 76ef57391a7b3..040b981c41593 100644 --- a/pandas/tests/frame/methods/test_quantile.py +++ b/pandas/tests/frame/methods/test_quantile.py @@ -673,7 +673,7 @@ def test_quantile_ea_with_na(self, obj, index): # TODO(GH#39763): filtering can be removed after GH#39763 is fixed @pytest.mark.filterwarnings("ignore:Using .astype to convert:FutureWarning") - def test_quantile_ea_all_na(self, obj, index, frame_or_series, request): + def test_quantile_ea_all_na(self, obj, index): obj.iloc[:] = index._na_value # TODO(ArrayManager): this casting should be unnecessary after GH#39763 is fixed diff --git a/pandas/tests/frame/methods/test_tz_convert.py b/pandas/tests/frame/methods/test_tz_convert.py index bb9ea64d5f326..c5f6870769afc 100644 --- a/pandas/tests/frame/methods/test_tz_convert.py +++ b/pandas/tests/frame/methods/test_tz_convert.py @@ -104,17 +104,17 @@ def test_tz_convert_and_localize(self, fn): # Not DatetimeIndex / PeriodIndex with pytest.raises(TypeError, match="DatetimeIndex"): df = DataFrame(index=int_idx) - df = getattr(df, fn)("US/Pacific") + getattr(df, fn)("US/Pacific") # Not DatetimeIndex / PeriodIndex with pytest.raises(TypeError, match="DatetimeIndex"): df = DataFrame(np.ones(5), MultiIndex.from_arrays([int_idx, l0])) - df = getattr(df, fn)("US/Pacific", level=0) + getattr(df, fn)("US/Pacific", level=0) # Invalid level with pytest.raises(ValueError, match="not valid"): df = DataFrame(index=l0) - df = getattr(df, fn)("US/Pacific", level=1) + getattr(df, fn)("US/Pacific", level=1) @pytest.mark.parametrize("copy", [True, False]) def test_tz_convert_copy_inplace_mutate(self, copy, frame_or_series): diff --git a/pandas/tests/frame/test_query_eval.py b/pandas/tests/frame/test_query_eval.py index 558ba0424e481..842ff172c34c4 100644 --- a/pandas/tests/frame/test_query_eval.py +++ b/pandas/tests/frame/test_query_eval.py @@ -36,7 +36,7 @@ def skip_if_no_pandas_parser(parser): class TestCompat: - def setup_method(self, method): + def setup_method(self): self.df = DataFrame({"A": [1, 2, 3]}) self.expected1 = self.df[self.df.A > 0] self.expected2 = self.df.A + 1 @@ -1090,10 +1090,10 @@ def test_query_string_scalar_variable(self, parser, engine): class TestDataFrameEvalWithFrame: - def setup_method(self, method): + def setup_method(self): self.frame = DataFrame(np.random.randn(10, 3), columns=list("abc")) - def teardown_method(self, method): + def teardown_method(self): del self.frame def test_simple_expr(self, parser, engine): diff --git a/pandas/tests/frame/test_repr_info.py b/pandas/tests/frame/test_repr_info.py index f19edf5722ca1..765640c94673e 100644 --- a/pandas/tests/frame/test_repr_info.py +++ b/pandas/tests/frame/test_repr_info.py @@ -62,7 +62,7 @@ def test_assign_index_sequences(self): df.index = index repr(df) - def test_repr_with_mi_nat(self, float_string_frame): + def test_repr_with_mi_nat(self): df = DataFrame({"X": [1, 2]}, index=[[NaT, Timestamp("20130101")], ["a", "b"]]) result = repr(df) expected = " X\nNaT a 1\n2013-01-01 b 2" diff --git a/pandas/tests/frame/test_ufunc.py b/pandas/tests/frame/test_ufunc.py index 79e9b1f34978d..2a4b212d0acd7 100644 --- a/pandas/tests/frame/test_ufunc.py +++ b/pandas/tests/frame/test_ufunc.py @@ -81,7 +81,7 @@ def test_binary_input_dispatch_binop(dtype): ), ], ) -def test_ufunc_passes_args(func, arg, expected, request): +def test_ufunc_passes_args(func, arg, expected): # GH#40662 arr = np.array([[1, 2], [3, 4]]) df = pd.DataFrame(arr) diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index cfc4b8934622f..6c6812a25fcd9 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -241,7 +241,7 @@ def test_apply_with_mixed_dtype(): tm.assert_series_equal(result1, result2) -def test_groupby_as_index_apply(df): +def test_groupby_as_index_apply(): # GH #4648 and #3417 df = DataFrame( { diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 3d5016b058c07..a33e4efbe3b6d 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -1447,7 +1447,7 @@ def test_dataframe_groupby_on_2_categoricals_when_observed_is_true(reduction_fun @pytest.mark.parametrize("observed", [False, None]) def test_dataframe_groupby_on_2_categoricals_when_observed_is_false( - reduction_func, observed, request + reduction_func, observed ): # GH 23865 # GH 27075 diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 2da835737bad4..e5b794690da92 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -821,7 +821,7 @@ def test_groupby_as_index_corner(df, ts): df.groupby(lambda x: x.lower(), as_index=False, axis=1) -def test_groupby_multiple_key(df): +def test_groupby_multiple_key(): df = tm.makeTimeDataFrame() grouped = df.groupby([lambda x: x.year, lambda x: x.month, lambda x: x.day]) agged = grouped.sum() diff --git a/pandas/tests/groupby/test_size.py b/pandas/tests/groupby/test_size.py index f87e4117f57fd..06f79ef609db1 100644 --- a/pandas/tests/groupby/test_size.py +++ b/pandas/tests/groupby/test_size.py @@ -20,7 +20,7 @@ def test_size(df, by): @pytest.mark.parametrize("by", ["A", "B", ["A", "B"]]) @pytest.mark.parametrize("sort", [True, False]) -def test_size_sort(df, sort, by): +def test_size_sort(sort, by): df = DataFrame(np.random.choice(20, (1000, 3)), columns=list("ABC")) left = df.groupby(by=by, sort=sort).size() right = df.groupby(by=by, sort=sort)["C"].apply(lambda a: a.shape[0]) diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index 2ae6ce99b4ee8..e06388e5d21ec 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -25,7 +25,7 @@ def simple_index(self) -> CategoricalIndex: return self._index_cls(list("aabbca"), categories=list("cab"), ordered=False) @pytest.fixture - def index(self, request): + def index(self): return tm.makeCategoricalIndex(100) def create_index(self, *, categories=None, ordered=False): diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py index 7c2b3b7f4482d..4558fcccbb0e1 100644 --- a/pandas/tests/indexes/datetimes/test_setops.py +++ b/pandas/tests/indexes/datetimes/test_setops.py @@ -417,7 +417,7 @@ def test_intersection_non_tick_no_fastpath(self): class TestBusinessDatetimeIndex: - def setup_method(self, method): + def setup_method(self): self.rng = bdate_range(START, END) def test_union(self, sort): @@ -555,7 +555,7 @@ def test_intersection_duplicates(self, sort): class TestCustomDatetimeIndex: - def setup_method(self, method): + def setup_method(self): self.rng = bdate_range(START, END, freq="C") def test_union(self, sort): diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py index 9f12d62155692..ea33c1178957e 100644 --- a/pandas/tests/indexes/multi/test_setops.py +++ b/pandas/tests/indexes/multi/test_setops.py @@ -368,7 +368,7 @@ def test_union_sort_other_empty(slice_): @pytest.mark.xfail(reason="Not implemented.") -def test_union_sort_other_empty_sort(slice_): +def test_union_sort_other_empty_sort(): # TODO(GH#25151): decide on True behaviour # # sort=True idx = MultiIndex.from_product([[1, 0], ["a", "b"]]) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 1145de14ad3c4..51840be14d320 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -452,7 +452,7 @@ def test_empty_fancy_raises(self, index): with pytest.raises(IndexError, match=msg): index[empty_farr] - def test_union_dt_as_obj(self, sort, simple_index): + def test_union_dt_as_obj(self, simple_index): # TODO: Replace with fixturesult index = simple_index date_index = date_range("2019-01-01", periods=10) @@ -792,7 +792,7 @@ def test_isin(self, values, index, expected): result = index.isin(values) tm.assert_numpy_array_equal(result, expected) - def test_isin_nan_common_object(self, request, nulls_fixture, nulls_fixture2): + def test_isin_nan_common_object(self, nulls_fixture, nulls_fixture2): # Test cartesian product of null fixtures and ensure that we don't # mangle the various types (save a corner case with PyPy) @@ -820,7 +820,7 @@ def test_isin_nan_common_object(self, request, nulls_fixture, nulls_fixture2): np.array([False, False]), ) - def test_isin_nan_common_float64(self, request, nulls_fixture): + def test_isin_nan_common_float64(self, nulls_fixture): if nulls_fixture is pd.NaT or nulls_fixture is pd.NA: # Check 1) that we cannot construct a Float64Index with this value diff --git a/pandas/tests/indexes/test_numpy_compat.py b/pandas/tests/indexes/test_numpy_compat.py index 3ee83160c1106..8f3ecce223afa 100644 --- a/pandas/tests/indexes/test_numpy_compat.py +++ b/pandas/tests/indexes/test_numpy_compat.py @@ -96,7 +96,7 @@ def test_numpy_ufuncs_basic(index, func): @pytest.mark.parametrize( "func", [np.isfinite, np.isinf, np.isnan, np.signbit], ids=lambda x: x.__name__ ) -def test_numpy_ufuncs_other(index, func, request): +def test_numpy_ufuncs_other(index, func): # test ufuncs of numpy, see: # https://numpy.org/doc/stable/reference/ufuncs.html if isinstance(index, (DatetimeIndex, TimedeltaIndex)): diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py index a150a1f6d9494..bad75b7429efb 100644 --- a/pandas/tests/indexes/test_setops.py +++ b/pandas/tests/indexes/test_setops.py @@ -432,7 +432,7 @@ def test_difference_preserves_type_empty(self, index, sort): expected = index[:0] tm.assert_index_equal(result, expected, exact=True) - def test_difference_name_retention_equals(self, index, sort, names): + def test_difference_name_retention_equals(self, index, names): if isinstance(index, MultiIndex): names = [[x] * index.nlevels for x in names] index = index.rename(names[0]) diff --git a/pandas/tests/indexing/common.py b/pandas/tests/indexing/common.py index f8db005583bd8..ea9f2584196d3 100644 --- a/pandas/tests/indexing/common.py +++ b/pandas/tests/indexing/common.py @@ -43,7 +43,7 @@ class Base: "multi", } - def setup_method(self, method): + def setup_method(self): self.series_ints = Series(np.random.rand(4), index=np.arange(0, 8, 2)) self.frame_ints = DataFrame( diff --git a/pandas/tests/indexing/multiindex/test_sorted.py b/pandas/tests/indexing/multiindex/test_sorted.py index b6cdd0e19a94e..2214aaa9cfbdb 100644 --- a/pandas/tests/indexing/multiindex/test_sorted.py +++ b/pandas/tests/indexing/multiindex/test_sorted.py @@ -64,7 +64,7 @@ def test_frame_getitem_not_sorted2(self, key): assert result.index.is_monotonic_increasing tm.assert_frame_equal(result, expected) - def test_sort_values_key(self, multiindex_dataframe_random_data): + def test_sort_values_key(self): arrays = [ ["bar", "bar", "baz", "baz", "qux", "qux", "foo", "foo"], ["one", "two", "one", "two", "one", "two", "one", "two"], diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py index 870043897e8e2..eb38edd920082 100644 --- a/pandas/tests/indexing/test_categorical.py +++ b/pandas/tests/indexing/test_categorical.py @@ -21,7 +21,7 @@ class TestCategoricalIndex: - def setup_method(self, method): + def setup_method(self): self.df = DataFrame( { diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index 7705ec9050aed..5ef079270479f 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -265,7 +265,7 @@ def test_insert_index_float64(self, insert, coerced_val, coerced_dtype): "insert_value", [pd.Timestamp("2012-01-01"), pd.Timestamp("2012-01-01", tz="Asia/Tokyo"), 1], ) - def test_insert_index_datetimes(self, request, fill_val, exp_dtype, insert_value): + def test_insert_index_datetimes(self, fill_val, exp_dtype, insert_value): obj = pd.DatetimeIndex( ["2011-01-01", "2011-01-02", "2011-01-03", "2011-01-04"], tz=fill_val.tz diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 83df57f922c9c..84f4709f291b6 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -244,7 +244,7 @@ def create_mgr(descr, item_shape=None): class TestBlock: - def setup_method(self, method): + def setup_method(self): self.fblock = create_block("float", [0, 2, 4]) self.cblock = create_block("complex", [7]) self.oblock = create_block("object", [1, 3]) diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index 9f6e1ed9c08d9..7cd58be8a8237 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -307,7 +307,7 @@ def test_read_workbook(datapath, ext, read_only): # When read_only is None, use read_excel instead of a workbook @pytest.mark.parametrize("read_only", [True, False, None]) def test_read_with_bad_dimension( - datapath, ext, header, expected_data, filename, read_only, request + datapath, ext, header, expected_data, filename, read_only ): # GH 38956, 39001 - no/incorrect dimension information path = datapath("io", "data", "excel", f"{filename}{ext}") @@ -345,7 +345,7 @@ def test_append_mode_file(ext): # When read_only is None, use read_excel instead of a workbook @pytest.mark.parametrize("read_only", [True, False, None]) -def test_read_with_empty_trailing_rows(datapath, ext, read_only, request): +def test_read_with_empty_trailing_rows(datapath, ext, read_only): # GH 39181 path = datapath("io", "data", "excel", f"empty_trailing_rows{ext}") if read_only is None: diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index 589c98721f139..b52b0fa96ff33 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -721,7 +721,7 @@ def test_excel_read_buffer(self, read_ext): actual = pd.read_excel(f, sheet_name="Sheet1", index_col=0) tm.assert_frame_equal(expected, actual) - def test_bad_engine_raises(self, read_ext): + def test_bad_engine_raises(self): bad_engine = "foo" with pytest.raises(ValueError, match="Unknown engine: foo"): pd.read_excel("", engine=bad_engine) @@ -743,7 +743,7 @@ def test_missing_file_raises(self, read_ext): with pytest.raises(FileNotFoundError, match=match): pd.read_excel(bad_file) - def test_corrupt_bytes_raises(self, read_ext, engine): + def test_corrupt_bytes_raises(self, engine): bad_stream = b"foo" if engine is None: error = ValueError @@ -1287,7 +1287,7 @@ def test_ignore_chartsheets_by_int(self, request, engine, read_ext): ): pd.read_excel("chartsheet" + read_ext, sheet_name=1) - def test_euro_decimal_format(self, request, read_ext): + def test_euro_decimal_format(self, read_ext): # copied from read_csv result = pd.read_excel("test_decimal" + read_ext, decimal=",", skiprows=1) expected = DataFrame( @@ -1311,7 +1311,7 @@ def cd_and_set_engine(self, engine, datapath, monkeypatch): monkeypatch.chdir(datapath("io", "data", "excel")) monkeypatch.setattr(pd, "ExcelFile", func) - def test_engine_used(self, read_ext, engine, monkeypatch): + def test_engine_used(self, read_ext, engine): expected_defaults = { "xlsx": "openpyxl", "xlsm": "openpyxl", diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index 6f06ef9c09e52..e2236e5d2f01d 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -350,7 +350,7 @@ def test_excel_sheet_size(self, path): with pytest.raises(ValueError, match=msg): col_df.to_excel(path) - def test_excel_sheet_by_name_raise(self, path, engine): + def test_excel_sheet_by_name_raise(self, path): gt = DataFrame(np.random.randn(10, 2)) gt.to_excel(path) @@ -649,7 +649,7 @@ def test_excel_roundtrip_datetime(self, merge_cells, tsframe, path): tm.assert_frame_equal(tsframe, recons) - def test_excel_date_datetime_format(self, engine, ext, path): + def test_excel_date_datetime_format(self, ext, path): # see gh-4133 # # Excel output format strings @@ -866,7 +866,7 @@ def test_to_excel_output_encoding(self, ext): result = pd.read_excel(filename, sheet_name="TestSheet", index_col=0) tm.assert_frame_equal(result, df) - def test_to_excel_unicode_filename(self, ext, path): + def test_to_excel_unicode_filename(self, ext): with tm.ensure_clean("\u0192u." + ext) as filename: try: f = open(filename, "wb") @@ -1189,7 +1189,7 @@ def test_path_local_path(self, engine, ext): result = tm.round_trip_localpath(writer, reader, path=f"foo{ext}") tm.assert_frame_equal(result, df) - def test_merged_cell_custom_objects(self, merge_cells, path): + def test_merged_cell_custom_objects(self, path): # see GH-27006 mi = MultiIndex.from_tuples( [ diff --git a/pandas/tests/io/formats/style/test_html.py b/pandas/tests/io/formats/style/test_html.py index fad289d5e0d2c..2010d06c9d22d 100644 --- a/pandas/tests/io/formats/style/test_html.py +++ b/pandas/tests/io/formats/style/test_html.py @@ -469,7 +469,7 @@ def test_maximums(styler_mi, rows, cols): assert (">2</td>" in result) is not cols # first trimmed horizontal element -def test_replaced_css_class_names(styler_mi): +def test_replaced_css_class_names(): css = { "row_heading": "ROWHEAD", # "col_heading": "COLHEAD", diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py index 915497e614b3a..1b2d2692eab03 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -441,7 +441,7 @@ def test_apply_map_header_raises(mi_styler): class TestStyler: - def setup_method(self, method): + def setup_method(self): np.random.seed(24) self.s = DataFrame({"A": np.random.permutation(range(6))}) self.df = DataFrame({"A": [0, 1], "B": np.random.randn(2)}) diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 99378654c6c11..adcaeba5cfd8d 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -2111,7 +2111,7 @@ def gen_series_formatting(): class TestSeriesFormatting: - def setup_method(self, method): + def setup_method(self): self.ts = tm.makeTimeSeries() def test_repr_unicode(self): diff --git a/pandas/tests/io/formats/test_to_markdown.py b/pandas/tests/io/formats/test_to_markdown.py index 2bd0d11888163..55ec9c83601f9 100644 --- a/pandas/tests/io/formats/test_to_markdown.py +++ b/pandas/tests/io/formats/test_to_markdown.py @@ -59,7 +59,7 @@ def test_series(): ) -def test_no_buf(capsys): +def test_no_buf(): df = pd.DataFrame([1, 2, 3]) result = df.to_markdown() assert ( diff --git a/pandas/tests/io/json/test_json_table_schema_ext_dtype.py b/pandas/tests/io/json/test_json_table_schema_ext_dtype.py index cd760854cb01e..f6aa16ff0ce38 100644 --- a/pandas/tests/io/json/test_json_table_schema_ext_dtype.py +++ b/pandas/tests/io/json/test_json_table_schema_ext_dtype.py @@ -30,7 +30,7 @@ class TestBuildSchema: - def setup_method(self, method): + def setup_method(self): self.da = DateArray([dt.date(2021, 10, 10)]) self.dc = DecimalArray([decimal.Decimal(10)]) self.sa = array(["pandas"], dtype="string") @@ -117,7 +117,7 @@ def test_as_json_table_type_ext_integer_dtype(self): class TestTableOrient: - def setup_method(self, method): + def setup_method(self): self.da = DateArray([dt.date(2021, 10, 10)]) self.dc = DecimalArray([decimal.Decimal(10)]) self.sa = array(["pandas"], dtype="string") diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 3717952a2183e..5714ab72bf3f3 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -364,7 +364,7 @@ def test_frame_from_json_missing_data(self, orient, convert_axes, numpy, dtype): assert np.isnan(result.iloc[0, 2]) @pytest.mark.parametrize("dtype", [True, False]) - def test_frame_read_json_dtype_missing_value(self, orient, dtype): + def test_frame_read_json_dtype_missing_value(self, dtype): # GH28501 Parse missing values using read_json with dtype=False # to NaN instead of None result = read_json("[null]", dtype=dtype) @@ -374,7 +374,7 @@ def test_frame_read_json_dtype_missing_value(self, orient, dtype): @pytest.mark.parametrize("inf", [np.inf, np.NINF]) @pytest.mark.parametrize("dtype", [True, False]) - def test_frame_infinity(self, orient, inf, dtype): + def test_frame_infinity(self, inf, dtype): # infinities get mapped to nulls which get mapped to NaNs during # deserialisation df = DataFrame([[1, 2], [4, 5, 6]]) diff --git a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py index cdf9c0a1784a4..e0b1b31c9cefc 100644 --- a/pandas/tests/io/parser/dtypes/test_dtypes_basic.py +++ b/pandas/tests/io/parser/dtypes/test_dtypes_basic.py @@ -193,7 +193,7 @@ def test_delimiter_with_usecols_and_parse_dates(all_parsers): @pytest.mark.parametrize("thousands", ["_", None]) def test_decimal_and_exponential(python_parser_only, numeric_decimal, thousands): # GH#31920 - decimal_number_check(python_parser_only, numeric_decimal, thousands, None) + decimal_number_check(python_parser_only, numeric_decimal, thousands) @pytest.mark.parametrize("thousands", ["_", None]) @@ -203,15 +203,15 @@ def test_1000_sep_decimal_float_precision( ): # test decimal and thousand sep handling in across 'float_precision' # parsers - decimal_number_check(c_parser_only, numeric_decimal, thousands, float_precision) + decimal_number_check(c_parser_only, numeric_decimal, thousands) text, value = numeric_decimal text = " " + text + " " if isinstance(value, str): # the negative cases (parse as text) value = " " + value + " " - decimal_number_check(c_parser_only, (text, value), thousands, float_precision) + decimal_number_check(c_parser_only, (text, value), thousands) -def decimal_number_check(parser, numeric_decimal, thousands, float_precision): +def decimal_number_check(parser, numeric_decimal, thousands): # GH#31920 value = numeric_decimal[0] if thousands is None and "_" in value: diff --git a/pandas/tests/io/parser/test_encoding.py b/pandas/tests/io/parser/test_encoding.py index 2b27332c7e85b..a70c3ee44edb6 100644 --- a/pandas/tests/io/parser/test_encoding.py +++ b/pandas/tests/io/parser/test_encoding.py @@ -153,9 +153,7 @@ def test_read_csv_utf_aliases(all_parsers, utf_value, encoding_fmt): (("io", "parser", "data", "sauron.SHIFT_JIS.csv"), "shiftjis"), ], ) -def test_binary_mode_file_buffers( - all_parsers, csv_dir_path, file_path, encoding, datapath -): +def test_binary_mode_file_buffers(all_parsers, file_path, encoding, datapath): # gh-23779: Python csv engine shouldn't error on files opened in binary. # gh-31575: Python csv engine shouldn't error on files opened in raw binary. parser = all_parsers diff --git a/pandas/tests/io/pytables/test_read.py b/pandas/tests/io/pytables/test_read.py index 1c9e63c66aadb..5b8911bcb0141 100644 --- a/pandas/tests/io/pytables/test_read.py +++ b/pandas/tests/io/pytables/test_read.py @@ -137,7 +137,7 @@ def test_read_column(setup_path): tm.assert_series_equal(result, expected) -def test_pytables_native_read(datapath, setup_path): +def test_pytables_native_read(datapath): with ensure_clean_store( datapath("io", "data", "legacy_hdf/pytables_native.h5"), mode="r" ) as store: @@ -146,7 +146,7 @@ def test_pytables_native_read(datapath, setup_path): @pytest.mark.skipif(is_platform_windows(), reason="native2 read fails oddly on windows") -def test_pytables_native2_read(datapath, setup_path): +def test_pytables_native2_read(datapath): with ensure_clean_store( datapath("io", "data", "legacy_hdf", "pytables_native2.h5"), mode="r" ) as store: @@ -155,7 +155,7 @@ def test_pytables_native2_read(datapath, setup_path): assert isinstance(d1, DataFrame) -def test_legacy_table_fixed_format_read_py2(datapath, setup_path): +def test_legacy_table_fixed_format_read_py2(datapath): # GH 24510 # legacy table with fixed format written in Python 2 with ensure_clean_store( @@ -170,7 +170,7 @@ def test_legacy_table_fixed_format_read_py2(datapath, setup_path): tm.assert_frame_equal(expected, result) -def test_legacy_table_fixed_format_read_datetime_py2(datapath, setup_path): +def test_legacy_table_fixed_format_read_datetime_py2(datapath): # GH 31750 # legacy table with fixed format and datetime64 column written in Python 2 with ensure_clean_store( @@ -186,7 +186,7 @@ def test_legacy_table_fixed_format_read_datetime_py2(datapath, setup_path): tm.assert_frame_equal(expected, result) -def test_legacy_table_read_py2(datapath, setup_path): +def test_legacy_table_read_py2(datapath): # issue: 24925 # legacy table written in Python 2 with ensure_clean_store( diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 73e10adb0c2c3..f20757b09fb36 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -223,7 +223,7 @@ def test_versioning(setup_path): ), ], ) -def test_walk(where, expected, setup_path): +def test_walk(where, expected): # GH10143 objs = { "df1": DataFrame([1, 2, 3]), @@ -809,7 +809,7 @@ def test_select_filter_corner(setup_path): tm.assert_frame_equal(result, df.loc[:, df.columns[:75:2]]) -def test_path_pathlib(setup_path): +def test_path_pathlib(): df = tm.makeDataFrame() result = tm.round_trip_pathlib( @@ -835,7 +835,7 @@ def test_contiguous_mixed_data_table(start, stop, setup_path): tm.assert_frame_equal(df[start:stop], result) -def test_path_pathlib_hdfstore(setup_path): +def test_path_pathlib_hdfstore(): df = tm.makeDataFrame() def writer(path): @@ -850,7 +850,7 @@ def reader(path): tm.assert_frame_equal(df, result) -def test_pickle_path_localpath(setup_path): +def test_pickle_path_localpath(): df = tm.makeDataFrame() result = tm.round_trip_pathlib( lambda p: df.to_hdf(p, "df"), lambda p: read_hdf(p, "df") @@ -858,7 +858,7 @@ def test_pickle_path_localpath(setup_path): tm.assert_frame_equal(df, result) -def test_path_localpath_hdfstore(setup_path): +def test_path_localpath_hdfstore(): df = tm.makeDataFrame() def writer(path): @@ -873,7 +873,7 @@ def reader(path): tm.assert_frame_equal(df, result) -def test_copy(setup_path): +def test_copy(): with catch_warnings(record=True): diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py index 36fa79d0bb7e3..e235c73123eaa 100644 --- a/pandas/tests/io/pytables/test_timezones.py +++ b/pandas/tests/io/pytables/test_timezones.py @@ -304,7 +304,7 @@ def test_store_timezone(setup_path): tm.assert_frame_equal(result, df) -def test_legacy_datetimetz_object(datapath, setup_path): +def test_legacy_datetimetz_object(datapath): # legacy from < 0.17.0 # 8260 expected = DataFrame( @@ -356,7 +356,7 @@ def test_read_with_where_tz_aware_index(setup_path): tm.assert_frame_equal(result, expected) -def test_py2_created_with_datetimez(datapath, setup_path): +def test_py2_created_with_datetimez(datapath): # The test HDF5 file was created in Python 2, but could not be read in # Python 3. # diff --git a/pandas/tests/io/xml/test_to_xml.py b/pandas/tests/io/xml/test_to_xml.py index 0666dcacecf39..7b2c2b11dbc27 100644 --- a/pandas/tests/io/xml/test_to_xml.py +++ b/pandas/tests/io/xml/test_to_xml.py @@ -363,21 +363,21 @@ def test_index_false_with_offset_input_index(parser, offset_index): </data>""" -def test_na_elem_output(datapath, parser): +def test_na_elem_output(parser): output = geom_df.to_xml(parser=parser) output = equalize_decl(output) assert output == na_expected -def test_na_empty_str_elem_option(datapath, parser): +def test_na_empty_str_elem_option(parser): output = geom_df.to_xml(na_rep="", parser=parser) output = equalize_decl(output) assert output == na_expected -def test_na_empty_elem_option(datapath, parser): +def test_na_empty_elem_option(parser): expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -410,7 +410,7 @@ def test_na_empty_elem_option(datapath, parser): # ATTR_COLS -def test_attrs_cols_nan_output(datapath, parser): +def test_attrs_cols_nan_output(parser): expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -425,7 +425,7 @@ def test_attrs_cols_nan_output(datapath, parser): assert output == expected -def test_attrs_cols_prefix(datapath, parser): +def test_attrs_cols_prefix(parser): expected = """\ <?xml version='1.0' encoding='utf-8'?> <doc:data xmlns:doc="http://example.xom"> @@ -461,7 +461,7 @@ def test_attrs_wrong_type(parser): # ELEM_COLS -def test_elems_cols_nan_output(datapath, parser): +def test_elems_cols_nan_output(parser): elems_cols_expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -500,7 +500,7 @@ def test_elems_wrong_type(parser): geom_df.to_xml(elem_cols='"shape", "degree", "sides"', parser=parser) -def test_elems_and_attrs_cols(datapath, parser): +def test_elems_and_attrs_cols(parser): elems_cols_expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -532,7 +532,7 @@ def test_elems_and_attrs_cols(datapath, parser): # HIERARCHICAL COLUMNS -def test_hierarchical_columns(datapath, parser): +def test_hierarchical_columns(parser): expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -579,7 +579,7 @@ def test_hierarchical_columns(datapath, parser): assert output == expected -def test_hierarchical_attrs_columns(datapath, parser): +def test_hierarchical_attrs_columns(parser): expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -609,7 +609,7 @@ def test_hierarchical_attrs_columns(datapath, parser): # MULTIINDEX -def test_multi_index(datapath, parser): +def test_multi_index(parser): expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -648,7 +648,7 @@ def test_multi_index(datapath, parser): assert output == expected -def test_multi_index_attrs_cols(datapath, parser): +def test_multi_index_attrs_cols(parser): expected = """\ <?xml version='1.0' encoding='utf-8'?> <data> @@ -1020,7 +1020,7 @@ def test_stylesheet_buffered_reader(datapath, mode): @td.skip_if_no("lxml") -def test_stylesheet_wrong_path(datapath): +def test_stylesheet_wrong_path(): from lxml.etree import XMLSyntaxError xsl = os.path.join("data", "xml", "row_field_output.xslt") @@ -1102,7 +1102,7 @@ def test_incorrect_xsl_eval(): @td.skip_if_no("lxml") -def test_incorrect_xsl_apply(parser): +def test_incorrect_xsl_apply(): from lxml.etree import XSLTApplyError xsl = """\ @@ -1122,7 +1122,7 @@ def test_incorrect_xsl_apply(parser): geom_df.to_xml(path, stylesheet=xsl) -def test_stylesheet_with_etree(datapath): +def test_stylesheet_with_etree(): xsl = """\ <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" encoding="utf-8" indent="yes" /> @@ -1322,7 +1322,7 @@ def test_ea_dtypes(any_numeric_ea_dtype, parser): assert equalize_decl(result).strip() == expected -def test_unsuported_compression(datapath, parser): +def test_unsuported_compression(parser): with pytest.raises(ValueError, match="Unrecognized compression type"): with tm.ensure_clean() as path: geom_df.to_xml(path, parser=parser, compression="7z") diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py index aef94af60c3dd..03c176fd7bc8b 100644 --- a/pandas/tests/io/xml/test_xml.py +++ b/pandas/tests/io/xml/test_xml.py @@ -257,7 +257,7 @@ def test_parser_consistency_file(datapath): @tm.network @pytest.mark.slow @td.skip_if_no("lxml") -def test_parser_consistency_url(datapath): +def test_parser_consistency_url(): url = ( "https://data.cityofchicago.org/api/views/" "8pix-ypme/rows.xml?accessType=DOWNLOAD" @@ -993,7 +993,7 @@ def test_stylesheet_file_close(datapath, mode): @td.skip_if_no("lxml") -def test_stylesheet_with_etree(datapath): +def test_stylesheet_with_etree(): kml = os.path.join("data", "xml", "cta_rail_lines.kml") xsl = os.path.join("data", "xml", "flatten_doc.xsl") @@ -1090,7 +1090,7 @@ def test_wrong_compression(parser, compression, compression_only): read_xml(path, parser=parser, compression=attempted_compression) -def test_unsuported_compression(datapath, parser): +def test_unsuported_compression(parser): with pytest.raises(ValueError, match="Unrecognized compression type"): with tm.ensure_clean() as path: read_xml(path, parser=parser, compression="7z") diff --git a/pandas/tests/plotting/frame/test_frame.py b/pandas/tests/plotting/frame/test_frame.py index ff247349ff4d5..5cbfb5286bb10 100644 --- a/pandas/tests/plotting/frame/test_frame.py +++ b/pandas/tests/plotting/frame/test_frame.py @@ -746,7 +746,7 @@ def test_plot_scatter_with_categorical_data(self, x, y): _check_plot_works(df.plot.scatter, x=x, y=y) - def test_plot_scatter_with_c(self, request): + def test_plot_scatter_with_c(self): from pandas.plotting._matplotlib.compat import mpl_ge_3_4_0 df = DataFrame( diff --git a/pandas/tests/plotting/test_converter.py b/pandas/tests/plotting/test_converter.py index fe8620ef76c4b..1125975287469 100644 --- a/pandas/tests/plotting/test_converter.py +++ b/pandas/tests/plotting/test_converter.py @@ -157,7 +157,7 @@ def test_registry_resets(self): class TestDateTimeConverter: - def setup_method(self, method): + def setup_method(self): self.dtc = converter.DatetimeConverter() self.tc = converter.TimeFormatter(None) @@ -292,7 +292,7 @@ def test_convert_nested(self): class TestPeriodConverter: - def setup_method(self, method): + def setup_method(self): self.pc = converter.PeriodConverter() class Axis: diff --git a/pandas/tests/resample/test_time_grouper.py b/pandas/tests/resample/test_time_grouper.py index 1557eab5df31a..8a94609900e1d 100644 --- a/pandas/tests/resample/test_time_grouper.py +++ b/pandas/tests/resample/test_time_grouper.py @@ -147,7 +147,7 @@ def test_aggregate_normal(resample_method): @pytest.mark.xfail(reason="if TimeGrouper is used included, 'nth' doesn't work yet") -def test_aggregate_nth(resample_method): +def test_aggregate_nth(): """Check TimeGrouper's aggregation is identical as normal groupby.""" data = np.random.randn(20, 4) diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index 7ca3ac325d788..7b932a3bb80c0 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -23,7 +23,7 @@ class TestJoin: - def setup_method(self, method): + def setup_method(self): # aggregate multiple columns self.df = DataFrame( { diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 1249194d3a36d..1f19b464b761b 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -118,7 +118,7 @@ def dfs_for_indicator(): class TestMerge: - def setup_method(self, method): + def setup_method(self): # aggregate multiple columns self.df = DataFrame( { diff --git a/pandas/tests/reshape/merge/test_merge_ordered.py b/pandas/tests/reshape/merge/test_merge_ordered.py index 0268801c66e1d..4d3dc05571d1d 100644 --- a/pandas/tests/reshape/merge/test_merge_ordered.py +++ b/pandas/tests/reshape/merge/test_merge_ordered.py @@ -10,7 +10,7 @@ class TestMergeOrdered: - def setup_method(self, method): + def setup_method(self): self.left = DataFrame({"key": ["a", "c", "e"], "lvalue": [1, 2.0, 3]}) self.right = DataFrame({"key": ["b", "c", "d", "f"], "rvalue": [1, 2, 3.0, 4]}) diff --git a/pandas/tests/reshape/merge/test_multi.py b/pandas/tests/reshape/merge/test_multi.py index b5945f7542077..0dbe45eeb1e82 100644 --- a/pandas/tests/reshape/merge/test_multi.py +++ b/pandas/tests/reshape/merge/test_multi.py @@ -93,7 +93,7 @@ def test_merge_on_multikey(self, left, right, join_type): tm.assert_frame_equal(result, expected) @pytest.mark.parametrize("sort", [False, True]) - def test_left_join_multi_index(self, left, right, sort): + def test_left_join_multi_index(self, sort): icols = ["1st", "2nd", "3rd"] def bind_cols(df): diff --git a/pandas/tests/reshape/test_crosstab.py b/pandas/tests/reshape/test_crosstab.py index cc6eec671ac3a..65b126c0fd98f 100644 --- a/pandas/tests/reshape/test_crosstab.py +++ b/pandas/tests/reshape/test_crosstab.py @@ -16,7 +16,7 @@ class TestCrosstab: - def setup_method(self, method): + def setup_method(self): df = DataFrame( { "A": [ diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py index ff8e5d56cdc93..cbe33642786da 100644 --- a/pandas/tests/reshape/test_melt.py +++ b/pandas/tests/reshape/test_melt.py @@ -12,7 +12,7 @@ class TestMelt: - def setup_method(self, method): + def setup_method(self): self.df = tm.makeTimeDataFrame()[:10] self.df["id1"] = (self.df["A"] > 0).astype(np.int64) self.df["id2"] = (self.df["B"] > 0).astype(np.int64) diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index f4719ba0bda9a..a5ae9902e07b8 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -39,7 +39,7 @@ def interval_values(request, closed): class TestPivotTable: - def setup_method(self, method): + def setup_method(self): self.data = DataFrame( { "A": [ @@ -1758,7 +1758,7 @@ def test_categorical_margins_category(self, observed, request): table = df.pivot_table("x", "y", "z", dropna=observed, margins=True) tm.assert_frame_equal(table, expected) - def test_margins_casted_to_float(self, observed): + def test_margins_casted_to_float(self): # GH 24893 df = DataFrame( { diff --git a/pandas/tests/scalar/timestamp/test_comparisons.py b/pandas/tests/scalar/timestamp/test_comparisons.py index 7ed0a6aedebc1..b5084e7a8925e 100644 --- a/pandas/tests/scalar/timestamp/test_comparisons.py +++ b/pandas/tests/scalar/timestamp/test_comparisons.py @@ -12,7 +12,7 @@ class TestTimestampComparison: - def test_comparison_dt64_ndarray(self, fixed_now_ts): + def test_comparison_dt64_ndarray(self): ts = Timestamp("2021-01-01") ts2 = Timestamp("2019-04-05") arr = np.array([[ts.asm8, ts2.asm8]], dtype="M8[ns]") diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index b82fa1b7f23c1..3c83ac4e1f623 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -165,7 +165,7 @@ def test_setitem_ambiguous_keyerror(indexer_sl): tm.assert_series_equal(s2, expected) -def test_setitem(datetime_series, string_series): +def test_setitem(datetime_series): datetime_series[datetime_series.index[5]] = np.NaN datetime_series[[1, 2, 17]] = np.NaN datetime_series[6] = np.NaN diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 9d1ee70c265e8..667dae55ef9df 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -715,7 +715,7 @@ def test_series_where(self, obj, key, expected, val, is_inplace): self._check_inplace(is_inplace, orig, arr, obj) - def test_index_where(self, obj, key, expected, val, request): + def test_index_where(self, obj, key, expected, val): if obj.dtype == bool or obj.dtype.kind == "c" or expected.dtype.kind == "c": # TODO(GH#45061): Should become unreachable (at least the bool part) pytest.skip("test not applicable for this dtype") diff --git a/pandas/tests/series/indexing/test_where.py b/pandas/tests/series/indexing/test_where.py index 9ed04885bd9e1..eabaf23bd36f8 100644 --- a/pandas/tests/series/indexing/test_where.py +++ b/pandas/tests/series/indexing/test_where.py @@ -438,7 +438,7 @@ def test_where_categorical(frame_or_series): tm.assert_equal(exp, res) -def test_where_datetimelike_categorical(request, tz_naive_fixture): +def test_where_datetimelike_categorical(tz_naive_fixture): # GH#37682 tz = tz_naive_fixture diff --git a/pandas/tests/series/methods/test_interpolate.py b/pandas/tests/series/methods/test_interpolate.py index 8ca2d37016691..304bfc308fd70 100644 --- a/pandas/tests/series/methods/test_interpolate.py +++ b/pandas/tests/series/methods/test_interpolate.py @@ -78,7 +78,7 @@ def interp_methods_ind(request): class TestSeriesInterpolateData: - def test_interpolate(self, datetime_series, string_series): + def test_interpolate(self, datetime_series): ts = Series(np.arange(len(datetime_series), dtype=float), datetime_series.index) ts_copy = ts.copy() diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index 5fbb42789d746..f2b561c77d246 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -722,9 +722,7 @@ def test_align_date_objects_with_datetimeindex(self): class TestNamePreservation: @pytest.mark.parametrize("box", [list, tuple, np.array, Index, Series, pd.array]) @pytest.mark.parametrize("flex", [True, False]) - def test_series_ops_name_retention( - self, request, flex, box, names, all_binary_operators - ): + def test_series_ops_name_retention(self, flex, box, names, all_binary_operators): # GH#33930 consistent name renteiton op = all_binary_operators diff --git a/pandas/tests/series/test_ufunc.py b/pandas/tests/series/test_ufunc.py index ed07a31c24768..b0201db798789 100644 --- a/pandas/tests/series/test_ufunc.py +++ b/pandas/tests/series/test_ufunc.py @@ -176,9 +176,7 @@ def test_binary_ufunc_scalar(ufunc, sparse, flip, arrays_for_binary_ufunc): @pytest.mark.parametrize("sparse", SPARSE, ids=SPARSE_IDS) @pytest.mark.parametrize("shuffle", SHUFFLE) @pytest.mark.filterwarnings("ignore:divide by zero:RuntimeWarning") -def test_multiple_output_binary_ufuncs( - ufunc, sparse, shuffle, arrays_for_binary_ufunc, request -): +def test_multiple_output_binary_ufuncs(ufunc, sparse, shuffle, arrays_for_binary_ufunc): # Test that # the same conditions from binary_ufunc_scalar apply to # ufuncs with multiple outputs. diff --git a/pandas/tests/strings/test_strings.py b/pandas/tests/strings/test_strings.py index b72dd111f3b25..9a82110f65f83 100644 --- a/pandas/tests/strings/test_strings.py +++ b/pandas/tests/strings/test_strings.py @@ -360,9 +360,7 @@ def test_len_mixed(): ("rindex", "E", 0, 5, [4, 3, 1, 4]), ], ) -def test_index( - method, sub, start, end, index_or_series, any_string_dtype, expected, request -): +def test_index(method, sub, start, end, index_or_series, any_string_dtype, expected): obj = index_or_series( ["ABCDEFG", "BCDEFEF", "DEFGHIJEF", "EFGHEF"], dtype=any_string_dtype diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index b843a92850250..f64c7fa27201a 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -149,7 +149,7 @@ def test_statsmodels(): # Cython import warning @pytest.mark.filterwarnings("ignore:can't:ImportWarning") -def test_scikit_learn(df): +def test_scikit_learn(): sklearn = import_module("sklearn") # noqa:F841 from sklearn import ( @@ -173,7 +173,7 @@ def test_seaborn(): seaborn.stripplot(x="day", y="total_bill", data=tips) -def test_pandas_gbq(df): +def test_pandas_gbq(): pandas_gbq = import_module("pandas_gbq") # noqa:F841 diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py index 495fd637d01fe..a0066ace17bc4 100644 --- a/pandas/tests/test_expressions.py +++ b/pandas/tests/test_expressions.py @@ -47,10 +47,10 @@ @pytest.mark.skipif(not expr.USE_NUMEXPR, reason="not using numexpr") class TestExpressions: - def setup_method(self, method): + def setup_method(self): self._MIN_ELEMENTS = expr._MIN_ELEMENTS - def teardown_method(self, method): + def teardown_method(self): expr._MIN_ELEMENTS = self._MIN_ELEMENTS @staticmethod diff --git a/pandas/tests/test_nanops.py b/pandas/tests/test_nanops.py index fa95ff86cb6b9..c58cb0db00113 100644 --- a/pandas/tests/test_nanops.py +++ b/pandas/tests/test_nanops.py @@ -31,7 +31,7 @@ def skipna(request): class TestnanopsDataFrame: - def setup_method(self, method): + def setup_method(self): np.random.seed(11235) nanops._USE_BOTTLENECK = False @@ -95,7 +95,7 @@ def setup_method(self, method): self.arr_float1_nan_1d = self.arr_float1_nan[:, 0] self.arr_nan_float1_1d = self.arr_nan_float1[:, 0] - def teardown_method(self, method): + def teardown_method(self): nanops._USE_BOTTLENECK = use_bn def check_results(self, targ, res, axis, check_dtype=True): @@ -786,7 +786,7 @@ class TestNanvarFixedValues: # xref GH10242 - def setup_method(self, method): + def setup_method(self): # Samples from a normal distribution. self.variance = variance = 3.0 self.samples = self.prng.normal(scale=variance ** 0.5, size=100000) @@ -903,7 +903,7 @@ class TestNanskewFixedValues: # xref GH 11974 - def setup_method(self, method): + def setup_method(self): # Test data + skewness value (computed with scipy.stats.skew) self.samples = np.sin(np.linspace(0, 1, 200)) self.actual_skew = -0.1875895205961754 @@ -952,7 +952,7 @@ class TestNankurtFixedValues: # xref GH 11974 - def setup_method(self, method): + def setup_method(self): # Test data + kurtosis value (computed with scipy.stats.kurtosis) self.samples = np.sin(np.linspace(0, 1, 200)) self.actual_kurt = -1.2058303433799713 diff --git a/pandas/tests/tseries/offsets/test_business_day.py b/pandas/tests/tseries/offsets/test_business_day.py index 482d697b15e98..58d3985913994 100644 --- a/pandas/tests/tseries/offsets/test_business_day.py +++ b/pandas/tests/tseries/offsets/test_business_day.py @@ -34,7 +34,7 @@ class TestBusinessDay(Base): _offset = BDay - def setup_method(self, method): + def setup_method(self): self.d = datetime(2008, 1, 1) self.nd = np.datetime64("2008-01-01 00:00:00") diff --git a/pandas/tests/tseries/offsets/test_business_hour.py b/pandas/tests/tseries/offsets/test_business_hour.py index 401bfe664a3a2..314308c7e06f0 100644 --- a/pandas/tests/tseries/offsets/test_business_hour.py +++ b/pandas/tests/tseries/offsets/test_business_hour.py @@ -32,7 +32,7 @@ class TestBusinessHour(Base): _offset = BusinessHour - def setup_method(self, method): + def setup_method(self): self.d = datetime(2014, 7, 1, 10, 00) self.offset1 = BusinessHour() diff --git a/pandas/tests/tseries/offsets/test_custom_business_hour.py b/pandas/tests/tseries/offsets/test_custom_business_hour.py index dbc0ff4371fd9..3fc20df2d930b 100644 --- a/pandas/tests/tseries/offsets/test_custom_business_hour.py +++ b/pandas/tests/tseries/offsets/test_custom_business_hour.py @@ -26,7 +26,7 @@ class TestCustomBusinessHour(Base): _offset = CustomBusinessHour holidays = ["2014-06-27", datetime(2014, 6, 30), np.datetime64("2014-07-02")] - def setup_method(self, method): + def setup_method(self): # 2014 Calendar to check custom holidays # Sun Mon Tue Wed Thu Fri Sat # 6/22 23 24 25 26 27 28 diff --git a/pandas/tests/tseries/offsets/test_custom_business_month.py b/pandas/tests/tseries/offsets/test_custom_business_month.py index fb0f331fa3ad3..935213229a65a 100644 --- a/pandas/tests/tseries/offsets/test_custom_business_month.py +++ b/pandas/tests/tseries/offsets/test_custom_business_month.py @@ -35,7 +35,7 @@ class CustomBusinessMonthBase: - def setup_method(self, method): + def setup_method(self): self.d = datetime(2008, 1, 1) self.offset = self._offset() self.offset1 = self.offset diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 5dcfd0019e93f..3a9dde59dcef3 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -537,7 +537,7 @@ def test_offsets_hashable(self, offset_types): class TestDateOffset(Base): - def setup_method(self, method): + def setup_method(self): self.d = Timestamp(datetime(2008, 1, 2)) _offset_map.clear() @@ -622,7 +622,7 @@ def test_get_offset_legacy(): class TestOffsetAliases: - def setup_method(self, method): + def setup_method(self): _offset_map.clear() def test_alias_equality(self):
- [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/45692
2022-01-29T03:24:32Z
2022-01-30T18:08:40Z
2022-01-30T18:08:40Z
2022-01-30T18:12:13Z
BUG: Series[sparse].where losing fill_value
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 1d4054d5ea0f1..59185690677dc 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -316,7 +316,7 @@ Reshaping Sparse ^^^^^^ -- +- Bug in :meth:`Series.where` and :meth:`DataFrame.where` with ``SparseDtype`` failing to retain the array's ``fill_value`` (:issue:`45691`) - ExtensionArray diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 18621fa9fb68a..bedde2dbf2558 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -1355,7 +1355,8 @@ def _where(self, mask, value): # NB: may not preserve dtype, e.g. result may be Sparse[float64] # while self is Sparse[int64] naive_implementation = np.where(mask, self, value) - result = type(self)._from_sequence(naive_implementation) + dtype = SparseDtype(naive_implementation.dtype, fill_value=self.fill_value) + result = type(self)._from_sequence(naive_implementation, dtype=dtype) return result # ------------------------------------------------------------------------ diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index a8517535e7833..baa7537e3cc2f 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -880,6 +880,20 @@ def test_generator_warnings(self): pass assert len(w) == 0 + def test_where_retain_fill_value(self): + # GH#45691 don't lose fill_value on _where + arr = SparseArray([np.nan, 1.0], fill_value=0) + + mask = np.array([True, False]) + + res = arr._where(~mask, 1) + exp = SparseArray([1, 1.0], fill_value=0) + tm.assert_sp_array_equal(res, exp) + + ser = pd.Series(arr) + res = ser.where(~mask, 1) + tm.assert_series_equal(res, pd.Series(exp)) + def test_fillna(self): s = SparseArray([1, np.nan, np.nan, 3, np.nan]) res = s.fillna(-1)
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45691
2022-01-29T00:07:10Z
2022-01-29T20:47:09Z
2022-01-29T20:47:09Z
2022-01-29T21:09:37Z
REF: make Block.delete return a new Block
diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index f9657953045c6..88f3315fe0ab8 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -380,9 +380,9 @@ def set_inplace(self, locs, values: ArrayLike) -> None: """ self.values[locs] = values - def delete(self, loc) -> None: + def delete(self, loc) -> Block: """ - Delete given loc(-s) from block in-place. + Return a new Block with the given loc(s) deleted. """ # Argument 1 to "delete" has incompatible type "Union[ndarray[Any, Any], # ExtensionArray]"; expected "Union[_SupportsArray[dtype[Any]], @@ -390,13 +390,9 @@ def delete(self, loc) -> None: # [_SupportsArray[dtype[Any]]]], Sequence[Sequence[Sequence[ # _SupportsArray[dtype[Any]]]]], Sequence[Sequence[Sequence[Sequence[ # _SupportsArray[dtype[Any]]]]]]]" [arg-type] - self.values = np.delete(self.values, loc, 0) # type: ignore[arg-type] - self.mgr_locs = self._mgr_locs.delete(loc) - try: - self._cache.clear() - except AttributeError: - # _cache not yet initialized - pass + values = np.delete(self.values, loc, 0) # type: ignore[arg-type] + mgr_locs = self._mgr_locs.delete(loc) + return type(self)(values, placement=mgr_locs, ndim=self.ndim) @final def apply(self, func, **kwargs) -> list[Block]: @@ -1504,18 +1500,11 @@ def fillna( return [self.make_block_same_class(values=new_values)] - def delete(self, loc) -> None: - """ - Delete given loc(-s) from block in-place. - """ + def delete(self, loc) -> Block: # This will be unnecessary if/when __array_function__ is implemented - self.values = self.values.delete(loc) - self.mgr_locs = self._mgr_locs.delete(loc) - try: - self._cache.clear() - except AttributeError: - # _cache not yet initialized - pass + values = self.values.delete(loc) + mgr_locs = self._mgr_locs.delete(loc) + return type(self)(values, placement=mgr_locs, ndim=self.ndim) @cache_readonly def array_values(self) -> ExtensionArray: diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 8599a1281a976..d2fca9f741b4c 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1133,8 +1133,12 @@ def value_getitem(placement): if len(val_locs) == len(blk.mgr_locs): removed_blknos.append(blkno_l) else: - blk.delete(blk_locs) - self._blklocs[blk.mgr_locs.indexer] = np.arange(len(blk)) + nb = blk.delete(blk_locs) + blocks_tup = ( + self.blocks[:blkno_l] + (nb,) + self.blocks[blkno_l + 1 :] + ) + self.blocks = blocks_tup + self._blklocs[nb.mgr_locs.indexer] = np.arange(len(nb)) if len(removed_blknos): # Remove blocks & update blknos accordingly @@ -1869,8 +1873,10 @@ def idelete(self, indexer) -> SingleBlockManager: Ensures that self.blocks doesn't become empty. """ - self._block.delete(indexer) + nb = self._block.delete(indexer) + self.blocks = (nb,) self.axes[0] = self.axes[0].delete(indexer) + self._cache.clear() return self def fast_xs(self, loc): diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 83df57f922c9c..3be82a071b7f1 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -285,27 +285,36 @@ def test_copy(self): def test_delete(self): newb = self.fblock.copy() - newb.delete(0) - assert isinstance(newb.mgr_locs, BlockPlacement) + locs = newb.mgr_locs + nb = newb.delete(0) + assert newb.mgr_locs is locs + + assert nb is not newb + tm.assert_numpy_array_equal( - newb.mgr_locs.as_array, np.array([2, 4], dtype=np.intp) + nb.mgr_locs.as_array, np.array([2, 4], dtype=np.intp) ) - assert (newb.values[0] == 1).all() + assert not (newb.values[0] == 1).all() + assert (nb.values[0] == 1).all() newb = self.fblock.copy() - newb.delete(1) - assert isinstance(newb.mgr_locs, BlockPlacement) + locs = newb.mgr_locs + nb = newb.delete(1) + assert newb.mgr_locs is locs + tm.assert_numpy_array_equal( - newb.mgr_locs.as_array, np.array([0, 4], dtype=np.intp) + nb.mgr_locs.as_array, np.array([0, 4], dtype=np.intp) ) - assert (newb.values[1] == 2).all() + assert not (newb.values[1] == 2).all() + assert (nb.values[1] == 2).all() newb = self.fblock.copy() - newb.delete(2) + locs = newb.mgr_locs + nb = newb.delete(2) tm.assert_numpy_array_equal( - newb.mgr_locs.as_array, np.array([0, 2], dtype=np.intp) + nb.mgr_locs.as_array, np.array([0, 2], dtype=np.intp) ) - assert (newb.values[1] == 1).all() + assert (nb.values[1] == 1).all() newb = self.fblock.copy() @@ -319,15 +328,15 @@ def test_delete_datetimelike(self): blk = df._mgr.blocks[0] assert isinstance(blk.values, TimedeltaArray) - blk.delete(1) - assert isinstance(blk.values, TimedeltaArray) + nb = blk.delete(1) + assert isinstance(nb.values, TimedeltaArray) df = DataFrame(arr.view("M8[ns]")) blk = df._mgr.blocks[0] assert isinstance(blk.values, DatetimeArray) - blk.delete([1, 3]) - assert isinstance(blk.values, DatetimeArray) + nb = blk.delete([1, 3]) + assert isinstance(nb.values, DatetimeArray) def test_split(self): # GH#37799
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry I lost track of the original use case that motivated this, but in general i think we're better off keeping block.values fixed.
https://api.github.com/repos/pandas-dev/pandas/pulls/45689
2022-01-28T23:13:17Z
2022-01-30T18:50:27Z
2022-01-30T18:50:27Z
2022-01-30T18:52:40Z
TST: Use less autouse=True when unecessary
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index d76af1ce42546..2a34c71412789 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1365,8 +1365,6 @@ def itertuples( ----- The column names will be renamed to positional names if they are invalid Python identifiers, repeated, or start with an underscore. - On python versions < 3.7 regular tuples are returned for DataFrames - with a large number of columns (>254). Examples -------- diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index f3a6f1f80359c..3717952a2183e 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -25,16 +25,6 @@ ) 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": @@ -49,11 +39,17 @@ 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() + @pytest.fixture + def categorical_frame(self): + _seriesd = tm.getSeriesData() + + _cat_frame = DataFrame(_seriesd) - yield + cat = ["bah"] * 5 + ["bar"] * 5 + ["baz"] * 5 + ["foo"] * (len(_cat_frame) - 15) + _cat_frame.index = pd.CategoricalIndex(cat, name="E") + _cat_frame["E"] = list(reversed(cat)) + _cat_frame["sort"] = np.arange(len(_cat_frame), dtype="int64") + return _cat_frame @pytest.fixture def datetime_series(self): @@ -215,7 +211,9 @@ def test_roundtrip_str_axes(self, request, orient, convert_axes, numpy, dtype): @pytest.mark.parametrize("convert_axes", [True, False]) @pytest.mark.parametrize("numpy", [True, False]) - def test_roundtrip_categorical(self, request, orient, convert_axes, numpy): + def test_roundtrip_categorical( + self, request, orient, categorical_frame, convert_axes, numpy + ): # TODO: create a better frame to test with and improve coverage if orient in ("index", "columns"): request.node.add_marker( @@ -224,7 +222,7 @@ def test_roundtrip_categorical(self, request, orient, convert_axes, numpy): ) ) - data = self.categorical.to_json(orient=orient) + data = categorical_frame.to_json(orient=orient) if numpy and orient in ("records", "values"): request.node.add_marker( pytest.mark.xfail(reason=f"Orient {orient} is broken with numpy=True") @@ -232,7 +230,7 @@ def test_roundtrip_categorical(self, request, orient, convert_axes, numpy): result = read_json(data, orient=orient, convert_axes=convert_axes, numpy=numpy) - expected = self.categorical.copy() + expected = categorical_frame.copy() expected.index = expected.index.astype(str) # Categorical not preserved expected.index.name = None # index names aren't preserved in JSON diff --git a/pandas/tests/io/parser/test_textreader.py b/pandas/tests/io/parser/test_textreader.py index d594bf8a75d49..a58ed02d30ef9 100644 --- a/pandas/tests/io/parser/test_textreader.py +++ b/pandas/tests/io/parser/test_textreader.py @@ -6,7 +6,6 @@ BytesIO, StringIO, ) -import os import numpy as np import pytest @@ -25,27 +24,23 @@ class TestTextReader: - @pytest.fixture(autouse=True) - def setup_method(self, datapath): - self.dirpath = datapath("io", "parser", "data") - csv1_dirpath = datapath("io", "data", "csv") - self.csv1 = os.path.join(csv1_dirpath, "test1.csv") - self.csv2 = os.path.join(self.dirpath, "test2.csv") - self.xls1 = os.path.join(self.dirpath, "test.xls") - - def test_file_handle(self): - with open(self.csv1, "rb") as f: + @pytest.fixture + def csv_path(self, datapath): + return datapath("io", "data", "csv", "test1.csv") + + def test_file_handle(self, csv_path): + with open(csv_path, "rb") as f: reader = TextReader(f) reader.read() - def test_file_handle_mmap(self): + def test_file_handle_mmap(self, csv_path): # this was never using memory_map=True - with open(self.csv1, "rb") as f: + with open(csv_path, "rb") as f: reader = TextReader(f, header=None) reader.read() - def test_StringIO(self): - with open(self.csv1, "rb") as f: + def test_StringIO(self, csv_path): + with open(csv_path, "rb") as f: text = f.read() src = BytesIO(text) reader = TextReader(src, header=None) diff --git a/pandas/tests/io/sas/test_xport.py b/pandas/tests/io/sas/test_xport.py index 9232ea8a25e4d..2046427deeaf0 100644 --- a/pandas/tests/io/sas/test_xport.py +++ b/pandas/tests/io/sas/test_xport.py @@ -1,5 +1,3 @@ -import os - import numpy as np import pytest @@ -24,113 +22,122 @@ def numeric_as_float(data): class TestXport: @pytest.fixture(autouse=True) - def setup_method(self, datapath): - self.dirpath = datapath("io", "sas", "data") - self.file01 = os.path.join(self.dirpath, "DEMO_G.xpt") - self.file02 = os.path.join(self.dirpath, "SSHSV1_A.xpt") - self.file03 = os.path.join(self.dirpath, "DRXFCD_G.xpt") - self.file04 = os.path.join(self.dirpath, "paxraw_d_short.xpt") - self.file05 = os.path.join(self.dirpath, "DEMO_PUF.cpt") - + def setup_method(self): with td.file_leak_context(): yield + @pytest.fixture + def file01(self, datapath): + return datapath("io", "sas", "data", "DEMO_G.xpt") + + @pytest.fixture + def file02(self, datapath): + return datapath("io", "sas", "data", "SSHSV1_A.xpt") + + @pytest.fixture + def file03(self, datapath): + return datapath("io", "sas", "data", "DRXFCD_G.xpt") + + @pytest.fixture + def file04(self, datapath): + return datapath("io", "sas", "data", "paxraw_d_short.xpt") + + @pytest.fixture + def file05(self, datapath): + return datapath("io", "sas", "data", "DEMO_PUF.cpt") + @pytest.mark.slow - def test1_basic(self): + def test1_basic(self, file01): # Tests with DEMO_G.xpt (all numeric file) # Compare to this - data_csv = pd.read_csv(self.file01.replace(".xpt", ".csv")) + data_csv = pd.read_csv(file01.replace(".xpt", ".csv")) numeric_as_float(data_csv) # Read full file - data = read_sas(self.file01, format="xport") + data = read_sas(file01, format="xport") tm.assert_frame_equal(data, data_csv) num_rows = data.shape[0] # Test reading beyond end of file - with read_sas(self.file01, format="xport", iterator=True) as reader: + with read_sas(file01, format="xport", iterator=True) as reader: data = reader.read(num_rows + 100) assert data.shape[0] == num_rows # Test incremental read with `read` method. - with read_sas(self.file01, format="xport", iterator=True) as reader: + with read_sas(file01, format="xport", iterator=True) as reader: data = reader.read(10) tm.assert_frame_equal(data, data_csv.iloc[0:10, :]) # Test incremental read with `get_chunk` method. - with read_sas(self.file01, format="xport", chunksize=10) as reader: + with read_sas(file01, format="xport", chunksize=10) as reader: data = reader.get_chunk() tm.assert_frame_equal(data, data_csv.iloc[0:10, :]) # Test read in loop m = 0 - with read_sas(self.file01, format="xport", chunksize=100) as reader: + with read_sas(file01, format="xport", chunksize=100) as reader: for x in reader: m += x.shape[0] assert m == num_rows # Read full file with `read_sas` method - data = read_sas(self.file01) + data = read_sas(file01) tm.assert_frame_equal(data, data_csv) - def test1_index(self): + def test1_index(self, file01): # Tests with DEMO_G.xpt using index (all numeric file) # Compare to this - data_csv = pd.read_csv(self.file01.replace(".xpt", ".csv")) + data_csv = pd.read_csv(file01.replace(".xpt", ".csv")) data_csv = data_csv.set_index("SEQN") numeric_as_float(data_csv) # Read full file - data = read_sas(self.file01, index="SEQN", format="xport") + data = read_sas(file01, index="SEQN", format="xport") tm.assert_frame_equal(data, data_csv, check_index_type=False) # Test incremental read with `read` method. - with read_sas( - self.file01, index="SEQN", format="xport", iterator=True - ) as reader: + with read_sas(file01, index="SEQN", format="xport", iterator=True) as reader: data = reader.read(10) tm.assert_frame_equal(data, data_csv.iloc[0:10, :], check_index_type=False) # Test incremental read with `get_chunk` method. - with read_sas( - self.file01, index="SEQN", format="xport", chunksize=10 - ) as reader: + with read_sas(file01, index="SEQN", format="xport", chunksize=10) as reader: data = reader.get_chunk() tm.assert_frame_equal(data, data_csv.iloc[0:10, :], check_index_type=False) - def test1_incremental(self): + def test1_incremental(self, file01): # Test with DEMO_G.xpt, reading full file incrementally - data_csv = pd.read_csv(self.file01.replace(".xpt", ".csv")) + data_csv = pd.read_csv(file01.replace(".xpt", ".csv")) data_csv = data_csv.set_index("SEQN") numeric_as_float(data_csv) - with read_sas(self.file01, index="SEQN", chunksize=1000) as reader: + with read_sas(file01, index="SEQN", chunksize=1000) as reader: all_data = list(reader) data = pd.concat(all_data, axis=0) tm.assert_frame_equal(data, data_csv, check_index_type=False) - def test2(self): + def test2(self, file02): # Test with SSHSV1_A.xpt # Compare to this - data_csv = pd.read_csv(self.file02.replace(".xpt", ".csv")) + data_csv = pd.read_csv(file02.replace(".xpt", ".csv")) numeric_as_float(data_csv) - data = read_sas(self.file02) + data = read_sas(file02) tm.assert_frame_equal(data, data_csv) - def test2_binary(self): + def test2_binary(self, file02): # Test with SSHSV1_A.xpt, read as a binary file # Compare to this - data_csv = pd.read_csv(self.file02.replace(".xpt", ".csv")) + data_csv = pd.read_csv(file02.replace(".xpt", ".csv")) numeric_as_float(data_csv) - with open(self.file02, "rb") as fd: + with open(file02, "rb") as fd: with td.file_leak_context(): # GH#35693 ensure that if we pass an open file, we # dont incorrectly close it in read_sas @@ -138,31 +145,31 @@ def test2_binary(self): tm.assert_frame_equal(data, data_csv) - def test_multiple_types(self): + def test_multiple_types(self, file03): # Test with DRXFCD_G.xpt (contains text and numeric variables) # Compare to this - data_csv = pd.read_csv(self.file03.replace(".xpt", ".csv")) + data_csv = pd.read_csv(file03.replace(".xpt", ".csv")) - data = read_sas(self.file03, encoding="utf-8") + data = read_sas(file03, encoding="utf-8") tm.assert_frame_equal(data, data_csv) - def test_truncated_float_support(self): + def test_truncated_float_support(self, file04): # Test with paxraw_d_short.xpt, a shortened version of: # http://wwwn.cdc.gov/Nchs/Nhanes/2005-2006/PAXRAW_D.ZIP # This file has truncated floats (5 bytes in this case). # GH 11713 - data_csv = pd.read_csv(self.file04.replace(".xpt", ".csv")) + data_csv = pd.read_csv(file04.replace(".xpt", ".csv")) - data = read_sas(self.file04, format="xport") + data = read_sas(file04, format="xport") tm.assert_frame_equal(data.astype("int64"), data_csv) - def test_cport_header_found_raises(self): + def test_cport_header_found_raises(self, file05): # Test with DEMO_PUF.cpt, the beginning of puf2019_1_fall.xpt # from https://www.cms.gov/files/zip/puf2019.zip # (despite the extension, it's a cpt file) msg = "Header record indicates a CPORT file, which is not readable." with pytest.raises(ValueError, match=msg): - read_sas(self.file05, format="xport") + read_sas(file05, format="xport") diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index 9c978623d4fb6..9427e389c40da 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -105,15 +105,16 @@ def test_same_ordering(datapath): scope="class", ) class TestReadHtml: - @pytest.fixture(autouse=True) - def set_files(self, datapath): - self.spam_data = datapath("io", "data", "html", "spam.html") - self.spam_data_kwargs = {} - self.spam_data_kwargs["encoding"] = "UTF-8" - self.banklist_data = datapath("io", "data", "html", "banklist.html") + @pytest.fixture + def spam_data(self, datapath): + return datapath("io", "data", "html", "spam.html") + + @pytest.fixture + def banklist_data(self, datapath): + return datapath("io", "data", "html", "banklist.html") @pytest.fixture(autouse=True, scope="function") - def set_defaults(self, flavor, request): + def set_defaults(self, flavor): self.read_html = partial(read_html, flavor=flavor) yield @@ -180,126 +181,122 @@ def test_spam_url(self): assert_framelist_equal(df1, df2) @pytest.mark.slow - def test_banklist(self): - df1 = self.read_html( - self.banklist_data, match=".*Florida.*", attrs={"id": "table"} - ) - df2 = self.read_html( - self.banklist_data, match="Metcalf Bank", attrs={"id": "table"} - ) + def test_banklist(self, banklist_data): + df1 = self.read_html(banklist_data, match=".*Florida.*", attrs={"id": "table"}) + df2 = self.read_html(banklist_data, match="Metcalf Bank", attrs={"id": "table"}) assert_framelist_equal(df1, df2) - def test_spam(self): - df1 = self.read_html(self.spam_data, match=".*Water.*") - df2 = self.read_html(self.spam_data, match="Unit") + def test_spam(self, spam_data): + df1 = self.read_html(spam_data, match=".*Water.*") + df2 = self.read_html(spam_data, match="Unit") assert_framelist_equal(df1, df2) assert df1[0].iloc[0, 0] == "Proximates" assert df1[0].columns[0] == "Nutrient" - def test_spam_no_match(self): - dfs = self.read_html(self.spam_data) + def test_spam_no_match(self, spam_data): + dfs = self.read_html(spam_data) for df in dfs: assert isinstance(df, DataFrame) - def test_banklist_no_match(self): - dfs = self.read_html(self.banklist_data, attrs={"id": "table"}) + def test_banklist_no_match(self, banklist_data): + dfs = self.read_html(banklist_data, attrs={"id": "table"}) for df in dfs: assert isinstance(df, DataFrame) - def test_spam_header(self): - df = self.read_html(self.spam_data, match=".*Water.*", header=2)[0] + def test_spam_header(self, spam_data): + df = self.read_html(spam_data, match=".*Water.*", header=2)[0] assert df.columns[0] == "Proximates" assert not df.empty - def test_skiprows_int(self): - df1 = self.read_html(self.spam_data, match=".*Water.*", skiprows=1) - df2 = self.read_html(self.spam_data, match="Unit", skiprows=1) + def test_skiprows_int(self, spam_data): + df1 = self.read_html(spam_data, match=".*Water.*", skiprows=1) + df2 = self.read_html(spam_data, match="Unit", skiprows=1) assert_framelist_equal(df1, df2) - def test_skiprows_range(self): - df1 = self.read_html(self.spam_data, match=".*Water.*", skiprows=range(2)) - df2 = self.read_html(self.spam_data, match="Unit", skiprows=range(2)) + def test_skiprows_range(self, spam_data): + df1 = self.read_html(spam_data, match=".*Water.*", skiprows=range(2)) + df2 = self.read_html(spam_data, match="Unit", skiprows=range(2)) assert_framelist_equal(df1, df2) - def test_skiprows_list(self): - df1 = self.read_html(self.spam_data, match=".*Water.*", skiprows=[1, 2]) - df2 = self.read_html(self.spam_data, match="Unit", skiprows=[2, 1]) + def test_skiprows_list(self, spam_data): + df1 = self.read_html(spam_data, match=".*Water.*", skiprows=[1, 2]) + df2 = self.read_html(spam_data, match="Unit", skiprows=[2, 1]) assert_framelist_equal(df1, df2) - def test_skiprows_set(self): - df1 = self.read_html(self.spam_data, match=".*Water.*", skiprows={1, 2}) - df2 = self.read_html(self.spam_data, match="Unit", skiprows={2, 1}) + def test_skiprows_set(self, spam_data): + df1 = self.read_html(spam_data, match=".*Water.*", skiprows={1, 2}) + df2 = self.read_html(spam_data, match="Unit", skiprows={2, 1}) assert_framelist_equal(df1, df2) - def test_skiprows_slice(self): - df1 = self.read_html(self.spam_data, match=".*Water.*", skiprows=1) - df2 = self.read_html(self.spam_data, match="Unit", skiprows=1) + def test_skiprows_slice(self, spam_data): + df1 = self.read_html(spam_data, match=".*Water.*", skiprows=1) + df2 = self.read_html(spam_data, match="Unit", skiprows=1) assert_framelist_equal(df1, df2) - def test_skiprows_slice_short(self): - df1 = self.read_html(self.spam_data, match=".*Water.*", skiprows=slice(2)) - df2 = self.read_html(self.spam_data, match="Unit", skiprows=slice(2)) + def test_skiprows_slice_short(self, spam_data): + df1 = self.read_html(spam_data, match=".*Water.*", skiprows=slice(2)) + df2 = self.read_html(spam_data, match="Unit", skiprows=slice(2)) assert_framelist_equal(df1, df2) - def test_skiprows_slice_long(self): - df1 = self.read_html(self.spam_data, match=".*Water.*", skiprows=slice(2, 5)) - df2 = self.read_html(self.spam_data, match="Unit", skiprows=slice(4, 1, -1)) + def test_skiprows_slice_long(self, spam_data): + df1 = self.read_html(spam_data, match=".*Water.*", skiprows=slice(2, 5)) + df2 = self.read_html(spam_data, match="Unit", skiprows=slice(4, 1, -1)) assert_framelist_equal(df1, df2) - def test_skiprows_ndarray(self): - df1 = self.read_html(self.spam_data, match=".*Water.*", skiprows=np.arange(2)) - df2 = self.read_html(self.spam_data, match="Unit", skiprows=np.arange(2)) + def test_skiprows_ndarray(self, spam_data): + df1 = self.read_html(spam_data, match=".*Water.*", skiprows=np.arange(2)) + df2 = self.read_html(spam_data, match="Unit", skiprows=np.arange(2)) assert_framelist_equal(df1, df2) - def test_skiprows_invalid(self): + def test_skiprows_invalid(self, spam_data): with pytest.raises(TypeError, match=("is not a valid type for skipping rows")): - self.read_html(self.spam_data, match=".*Water.*", skiprows="asdf") + self.read_html(spam_data, match=".*Water.*", skiprows="asdf") - def test_index(self): - df1 = self.read_html(self.spam_data, match=".*Water.*", index_col=0) - df2 = self.read_html(self.spam_data, match="Unit", index_col=0) + def test_index(self, spam_data): + df1 = self.read_html(spam_data, match=".*Water.*", index_col=0) + df2 = self.read_html(spam_data, match="Unit", index_col=0) assert_framelist_equal(df1, df2) - def test_header_and_index_no_types(self): - df1 = self.read_html(self.spam_data, match=".*Water.*", header=1, index_col=0) - df2 = self.read_html(self.spam_data, match="Unit", header=1, index_col=0) + def test_header_and_index_no_types(self, spam_data): + df1 = self.read_html(spam_data, match=".*Water.*", header=1, index_col=0) + df2 = self.read_html(spam_data, match="Unit", header=1, index_col=0) assert_framelist_equal(df1, df2) - def test_header_and_index_with_types(self): - df1 = self.read_html(self.spam_data, match=".*Water.*", header=1, index_col=0) - df2 = self.read_html(self.spam_data, match="Unit", header=1, index_col=0) + def test_header_and_index_with_types(self, spam_data): + df1 = self.read_html(spam_data, match=".*Water.*", header=1, index_col=0) + df2 = self.read_html(spam_data, match="Unit", header=1, index_col=0) assert_framelist_equal(df1, df2) - def test_infer_types(self): + def test_infer_types(self, spam_data): # 10892 infer_types removed - df1 = self.read_html(self.spam_data, match=".*Water.*", index_col=0) - df2 = self.read_html(self.spam_data, match="Unit", index_col=0) + df1 = self.read_html(spam_data, match=".*Water.*", index_col=0) + df2 = self.read_html(spam_data, match="Unit", index_col=0) assert_framelist_equal(df1, df2) - def test_string_io(self): - with open(self.spam_data, **self.spam_data_kwargs) as f: + def test_string_io(self, spam_data): + with open(spam_data, encoding="UTF-8") as f: data1 = StringIO(f.read()) - with open(self.spam_data, **self.spam_data_kwargs) as f: + with open(spam_data, encoding="UTF-8") as f: data2 = StringIO(f.read()) df1 = self.read_html(data1, match=".*Water.*") df2 = self.read_html(data2, match="Unit") assert_framelist_equal(df1, df2) - def test_string(self): - with open(self.spam_data, **self.spam_data_kwargs) as f: + def test_string(self, spam_data): + with open(spam_data, encoding="UTF-8") as f: data = f.read() df1 = self.read_html(data, match=".*Water.*") @@ -307,11 +304,11 @@ def test_string(self): assert_framelist_equal(df1, df2) - def test_file_like(self): - with open(self.spam_data, **self.spam_data_kwargs) as f: + def test_file_like(self, spam_data): + with open(spam_data, encoding="UTF-8") as f: df1 = self.read_html(f, match=".*Water.*") - with open(self.spam_data, **self.spam_data_kwargs) as f: + with open(spam_data, encoding="UTF-8") as f: df2 = self.read_html(f, match="Unit") assert_framelist_equal(df1, df2) @@ -332,8 +329,8 @@ def test_invalid_url(self): self.read_html("http://www.a23950sdfa908sd.com", match=".*Water.*") @pytest.mark.slow - def test_file_url(self): - url = self.banklist_data + def test_file_url(self, banklist_data): + url = banklist_data dfs = self.read_html( file_path_to_url(os.path.abspath(url)), match="First", attrs={"id": "table"} ) @@ -342,53 +339,55 @@ def test_file_url(self): assert isinstance(df, DataFrame) @pytest.mark.slow - def test_invalid_table_attrs(self): - url = self.banklist_data + def test_invalid_table_attrs(self, banklist_data): + url = banklist_data with pytest.raises(ValueError, match="No tables found"): self.read_html( url, match="First Federal Bank of Florida", attrs={"id": "tasdfable"} ) - def _bank_data(self, *args, **kwargs): + def _bank_data(self, path, *args, **kwargs): return self.read_html( - self.banklist_data, match="Metcalf", attrs={"id": "table"}, *args, **kwargs + path, match="Metcalf", attrs={"id": "table"}, *args, **kwargs ) @pytest.mark.slow - def test_multiindex_header(self): - df = self._bank_data(header=[0, 1])[0] + def test_multiindex_header(self, banklist_data): + df = self._bank_data(banklist_data, header=[0, 1])[0] assert isinstance(df.columns, MultiIndex) @pytest.mark.slow - def test_multiindex_index(self): - df = self._bank_data(index_col=[0, 1])[0] + def test_multiindex_index(self, banklist_data): + df = self._bank_data(banklist_data, index_col=[0, 1])[0] assert isinstance(df.index, MultiIndex) @pytest.mark.slow - def test_multiindex_header_index(self): - df = self._bank_data(header=[0, 1], index_col=[0, 1])[0] + def test_multiindex_header_index(self, banklist_data): + df = self._bank_data(banklist_data, header=[0, 1], index_col=[0, 1])[0] assert isinstance(df.columns, MultiIndex) assert isinstance(df.index, MultiIndex) @pytest.mark.slow - def test_multiindex_header_skiprows_tuples(self): - df = self._bank_data(header=[0, 1], skiprows=1)[0] + def test_multiindex_header_skiprows_tuples(self, banklist_data): + df = self._bank_data(banklist_data, header=[0, 1], skiprows=1)[0] assert isinstance(df.columns, MultiIndex) @pytest.mark.slow - def test_multiindex_header_skiprows(self): - df = self._bank_data(header=[0, 1], skiprows=1)[0] + def test_multiindex_header_skiprows(self, banklist_data): + df = self._bank_data(banklist_data, header=[0, 1], skiprows=1)[0] assert isinstance(df.columns, MultiIndex) @pytest.mark.slow - def test_multiindex_header_index_skiprows(self): - df = self._bank_data(header=[0, 1], index_col=[0, 1], skiprows=1)[0] + def test_multiindex_header_index_skiprows(self, banklist_data): + df = self._bank_data( + banklist_data, header=[0, 1], index_col=[0, 1], skiprows=1 + )[0] assert isinstance(df.index, MultiIndex) assert isinstance(df.columns, MultiIndex) @pytest.mark.slow - def test_regex_idempotency(self): - url = self.banklist_data + def test_regex_idempotency(self, banklist_data): + url = banklist_data dfs = self.read_html( file_path_to_url(os.path.abspath(url)), match=re.compile(re.compile("Florida")), @@ -398,10 +397,10 @@ def test_regex_idempotency(self): for df in dfs: assert isinstance(df, DataFrame) - def test_negative_skiprows(self): + def test_negative_skiprows(self, spam_data): msg = r"\(you passed a negative value\)" with pytest.raises(ValueError, match=msg): - self.read_html(self.spam_data, match="Water", skiprows=-1) + self.read_html(spam_data, match="Water", skiprows=-1) @tm.network def test_multiple_matches(self): @@ -589,7 +588,7 @@ def test_parse_header_of_non_string_column(self): tm.assert_frame_equal(result, expected) @pytest.mark.slow - def test_banklist_header(self, datapath): + def test_banklist_header(self, banklist_data, datapath): from pandas.io.html import _remove_whitespace def try_remove_ws(x): @@ -598,9 +597,7 @@ def try_remove_ws(x): except AttributeError: return x - df = self.read_html(self.banklist_data, match="Metcalf", attrs={"id": "table"})[ - 0 - ] + df = self.read_html(banklist_data, match="Metcalf", attrs={"id": "table"})[0] ground_truth = read_csv( datapath("io", "data", "csv", "banklist.csv"), converters={"Updated Date": Timestamp, "Closing Date": Timestamp}, @@ -639,15 +636,15 @@ def try_remove_ws(x): tm.assert_frame_equal(converted, gtnew) @pytest.mark.slow - def test_gold_canyon(self): + def test_gold_canyon(self, banklist_data): gc = "Gold Canyon" - with open(self.banklist_data) as f: + with open(banklist_data) as f: raw_text = f.read() assert gc in raw_text - df = self.read_html( - self.banklist_data, match="Gold Canyon", attrs={"id": "table"} - )[0] + df = self.read_html(banklist_data, match="Gold Canyon", attrs={"id": "table"})[ + 0 + ] assert gc in df.to_string() def test_different_number_of_cols(self): @@ -966,16 +963,16 @@ def test_decimal_rows(self): assert result["Header"].dtype == np.dtype("float64") tm.assert_frame_equal(result, expected) - def test_bool_header_arg(self): + @pytest.mark.parametrize("arg", [True, False]) + def test_bool_header_arg(self, spam_data, arg): # GH 6114 msg = re.escape( "Passing a bool to header is invalid. Use header=None for no header or " "header=int or list-like of ints to specify the row(s) making up the " "column names" ) - for arg in [True, False]: - with pytest.raises(TypeError, match=msg): - self.read_html(self.spam_data, header=arg) + with pytest.raises(TypeError, match=msg): + self.read_html(spam_data, header=arg) def test_converters(self): # GH 13461 diff --git a/pandas/tests/reshape/merge/test_merge_asof.py b/pandas/tests/reshape/merge/test_merge_asof.py index ea2f16eae6411..ebf67b0518c65 100644 --- a/pandas/tests/reshape/merge/test_merge_asof.py +++ b/pandas/tests/reshape/merge/test_merge_asof.py @@ -27,17 +27,29 @@ def read_data(self, datapath, name, dedupe=False): x.time = to_datetime(x.time) return x - @pytest.fixture(autouse=True) - def setup_method(self, datapath): + @pytest.fixture + def trades(self, datapath): + return self.read_data(datapath, "trades.csv") - self.trades = self.read_data(datapath, "trades.csv") - self.quotes = self.read_data(datapath, "quotes.csv", dedupe=True) - self.asof = self.read_data(datapath, "asof.csv") - self.tolerance = self.read_data(datapath, "tolerance.csv") - self.allow_exact_matches = self.read_data(datapath, "allow_exact_matches.csv") - self.allow_exact_matches_and_tolerance = self.read_data( - datapath, "allow_exact_matches_and_tolerance.csv" - ) + @pytest.fixture + def quotes(self, datapath): + return self.read_data(datapath, "quotes.csv", dedupe=True) + + @pytest.fixture + def asof(self, datapath): + return self.read_data(datapath, "asof.csv") + + @pytest.fixture + def tolerance(self, datapath): + return self.read_data(datapath, "tolerance.csv") + + @pytest.fixture + def allow_exact_matches(self, datapath): + return self.read_data(datapath, "allow_exact_matches.csv") + + @pytest.fixture + def allow_exact_matches_and_tolerance(self, datapath): + return self.read_data(datapath, "allow_exact_matches_and_tolerance.csv") def test_examples1(self): """doc-string examples""" @@ -163,33 +175,28 @@ def test_examples4(self): result = merge_asof(left, right, on="a", direction="nearest") tm.assert_frame_equal(result, expected) - def test_basic(self): + def test_basic(self, trades, asof, quotes): - expected = self.asof - trades = self.trades - quotes = self.quotes + expected = asof result = merge_asof(trades, quotes, on="time", by="ticker") tm.assert_frame_equal(result, expected) - def test_basic_categorical(self): + def test_basic_categorical(self, trades, asof, quotes): - expected = self.asof - trades = self.trades.copy() + expected = asof trades.ticker = trades.ticker.astype("category") - quotes = self.quotes.copy() quotes.ticker = quotes.ticker.astype("category") expected.ticker = expected.ticker.astype("category") result = merge_asof(trades, quotes, on="time", by="ticker") tm.assert_frame_equal(result, expected) - def test_basic_left_index(self): + def test_basic_left_index(self, trades, asof, quotes): # GH14253 - expected = self.asof - trades = self.trades.set_index("time") - quotes = self.quotes + expected = asof + trades = trades.set_index("time") result = merge_asof( trades, quotes, left_index=True, right_on="time", by="ticker" @@ -200,77 +207,77 @@ def test_basic_left_index(self): expected = expected[result.columns] tm.assert_frame_equal(result, expected) - def test_basic_right_index(self): + def test_basic_right_index(self, trades, asof, quotes): - expected = self.asof - trades = self.trades - quotes = self.quotes.set_index("time") + expected = asof + trades = trades + quotes = quotes.set_index("time") result = merge_asof( trades, quotes, left_on="time", right_index=True, by="ticker" ) tm.assert_frame_equal(result, expected) - def test_basic_left_index_right_index(self): + def test_basic_left_index_right_index(self, trades, asof, quotes): - expected = self.asof.set_index("time") - trades = self.trades.set_index("time") - quotes = self.quotes.set_index("time") + expected = asof.set_index("time") + trades = trades.set_index("time") + quotes = quotes.set_index("time") result = merge_asof( trades, quotes, left_index=True, right_index=True, by="ticker" ) tm.assert_frame_equal(result, expected) - def test_multi_index(self): + def test_multi_index_left(self, trades, quotes): # MultiIndex is prohibited - trades = self.trades.set_index(["time", "price"]) - quotes = self.quotes.set_index("time") + trades = trades.set_index(["time", "price"]) + quotes = quotes.set_index("time") with pytest.raises(MergeError, match="left can only have one index"): merge_asof(trades, quotes, left_index=True, right_index=True) - trades = self.trades.set_index("time") - quotes = self.quotes.set_index(["time", "bid"]) + def test_multi_index_right(self, trades, quotes): + + # MultiIndex is prohibited + trades = trades.set_index("time") + quotes = quotes.set_index(["time", "bid"]) with pytest.raises(MergeError, match="right can only have one index"): merge_asof(trades, quotes, left_index=True, right_index=True) - def test_on_and_index(self): + def test_on_and_index_left_on(self, trades, quotes): # "on" parameter and index together is prohibited - trades = self.trades.set_index("time") - quotes = self.quotes.set_index("time") + trades = trades.set_index("time") + quotes = quotes.set_index("time") msg = 'Can only pass argument "left_on" OR "left_index" not both.' with pytest.raises(MergeError, match=msg): merge_asof( trades, quotes, left_on="price", left_index=True, right_index=True ) - trades = self.trades.set_index("time") - quotes = self.quotes.set_index("time") + def test_on_and_index_right_on(self, trades, quotes): + trades = trades.set_index("time") + quotes = quotes.set_index("time") msg = 'Can only pass argument "right_on" OR "right_index" not both.' with pytest.raises(MergeError, match=msg): merge_asof( trades, quotes, right_on="bid", left_index=True, right_index=True ) - def test_basic_left_by_right_by(self): + def test_basic_left_by_right_by(self, trades, asof, quotes): # GH14253 - expected = self.asof - trades = self.trades - quotes = self.quotes + expected = asof result = merge_asof( trades, quotes, on="time", left_by="ticker", right_by="ticker" ) tm.assert_frame_equal(result, expected) - def test_missing_right_by(self): + def test_missing_right_by(self, trades, asof, quotes): - expected = self.asof - trades = self.trades - quotes = self.quotes + expected = asof q = quotes[quotes.ticker != "MSFT"] result = merge_asof(trades, q, on="time", by="ticker") @@ -466,7 +473,7 @@ def test_basic2(self, datapath): result = merge_asof(trades, quotes, on="time", by="ticker") tm.assert_frame_equal(result, expected) - def test_basic_no_by(self): + def test_basic_no_by(self, trades, asof, quotes): f = ( lambda x: x[x.ticker == "MSFT"] .drop("ticker", axis=1) @@ -474,17 +481,14 @@ def test_basic_no_by(self): ) # just use a single ticker - expected = f(self.asof) - trades = f(self.trades) - quotes = f(self.quotes) + expected = f(asof) + trades = f(trades) + quotes = f(quotes) result = merge_asof(trades, quotes, on="time") tm.assert_frame_equal(result, expected) - def test_valid_join_keys(self): - - trades = self.trades - quotes = self.quotes + def test_valid_join_keys(self, trades, quotes): msg = r"incompatible merge keys \[1\] .* must be the same type" @@ -497,14 +501,14 @@ def test_valid_join_keys(self): with pytest.raises(MergeError, match="can only asof on a key for left"): merge_asof(trades, quotes, by="ticker") - def test_with_duplicates(self, datapath): + def test_with_duplicates(self, datapath, trades, quotes): q = ( - pd.concat([self.quotes, self.quotes]) + pd.concat([quotes, quotes]) .sort_values(["time", "ticker"]) .reset_index(drop=True) ) - result = merge_asof(self.trades, q, on="time", by="ticker") + result = merge_asof(trades, q, on="time", by="ticker") expected = self.read_data(datapath, "asof.csv") tm.assert_frame_equal(result, expected) @@ -518,10 +522,7 @@ def test_with_duplicates_no_on(self): ) tm.assert_frame_equal(result, expected) - def test_valid_allow_exact_matches(self): - - trades = self.trades - quotes = self.quotes + def test_valid_allow_exact_matches(self, trades, quotes): msg = "allow_exact_matches must be boolean, passed foo" @@ -530,10 +531,7 @@ def test_valid_allow_exact_matches(self): trades, quotes, on="time", by="ticker", allow_exact_matches="foo" ) - def test_valid_tolerance(self): - - trades = self.trades - quotes = self.quotes + def test_valid_tolerance(self, trades, quotes): # dti merge_asof(trades, quotes, on="time", by="ticker", tolerance=Timedelta("1s")) @@ -580,10 +578,10 @@ def test_valid_tolerance(self): tolerance=-1, ) - def test_non_sorted(self): + def test_non_sorted(self, trades, quotes): - trades = self.trades.sort_values("time", ascending=False) - quotes = self.quotes.sort_values("time", ascending=False) + trades = trades.sort_values("time", ascending=False) + quotes = quotes.sort_values("time", ascending=False) # we require that we are already sorted on time & quotes assert not trades.time.is_monotonic_increasing @@ -591,31 +589,29 @@ def test_non_sorted(self): with pytest.raises(ValueError, match="left keys must be sorted"): merge_asof(trades, quotes, on="time", by="ticker") - trades = self.trades.sort_values("time") + trades = trades.sort_values("time") assert trades.time.is_monotonic_increasing assert not quotes.time.is_monotonic_increasing with pytest.raises(ValueError, match="right keys must be sorted"): merge_asof(trades, quotes, on="time", by="ticker") - quotes = self.quotes.sort_values("time") + quotes = quotes.sort_values("time") assert trades.time.is_monotonic_increasing assert quotes.time.is_monotonic_increasing # ok, though has dupes - merge_asof(trades, self.quotes, on="time", by="ticker") + merge_asof(trades, quotes, on="time", by="ticker") @pytest.mark.parametrize( - "tolerance", + "tolerance_ts", [Timedelta("1day"), datetime.timedelta(days=1)], ids=["Timedelta", "datetime.timedelta"], ) - def test_tolerance(self, tolerance): - - trades = self.trades - quotes = self.quotes - - result = merge_asof(trades, quotes, on="time", by="ticker", tolerance=tolerance) - expected = self.tolerance + def test_tolerance(self, tolerance_ts, trades, quotes, tolerance): + result = merge_asof( + trades, quotes, on="time", by="ticker", tolerance=tolerance_ts + ) + expected = tolerance tm.assert_frame_equal(result, expected) def test_tolerance_forward(self): @@ -702,11 +698,11 @@ def test_tolerance_float(self): result = merge_asof(left, right, on="a", direction="nearest", tolerance=0.5) tm.assert_frame_equal(result, expected) - def test_index_tolerance(self): + def test_index_tolerance(self, trades, quotes, tolerance): # GH 15135 - expected = self.tolerance.set_index("time") - trades = self.trades.set_index("time") - quotes = self.quotes.set_index("time") + expected = tolerance.set_index("time") + trades = trades.set_index("time") + quotes = quotes.set_index("time") result = merge_asof( trades, @@ -718,12 +714,12 @@ def test_index_tolerance(self): ) tm.assert_frame_equal(result, expected) - def test_allow_exact_matches(self): + def test_allow_exact_matches(self, trades, quotes, allow_exact_matches): result = merge_asof( - self.trades, self.quotes, on="time", by="ticker", allow_exact_matches=False + trades, quotes, on="time", by="ticker", allow_exact_matches=False ) - expected = self.allow_exact_matches + expected = allow_exact_matches tm.assert_frame_equal(result, expected) def test_allow_exact_matches_forward(self): @@ -756,17 +752,19 @@ def test_allow_exact_matches_nearest(self): ) tm.assert_frame_equal(result, expected) - def test_allow_exact_matches_and_tolerance(self): + def test_allow_exact_matches_and_tolerance( + self, trades, quotes, allow_exact_matches_and_tolerance + ): result = merge_asof( - self.trades, - self.quotes, + trades, + quotes, on="time", by="ticker", tolerance=Timedelta("100ms"), allow_exact_matches=False, ) - expected = self.allow_exact_matches_and_tolerance + expected = allow_exact_matches_and_tolerance tm.assert_frame_equal(result, expected) def test_allow_exact_matches_and_tolerance2(self):
- [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/45688
2022-01-28T22:30:58Z
2022-01-29T19:55:55Z
2022-01-29T19:55:55Z
2022-01-29T22:33:49Z
ENH: Allow safe access to `.book` in ExcelWriter
diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 3e1df9325713b..b33955737a111 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -1048,6 +1048,12 @@ def engine(self) -> str: """Name of engine.""" pass + @property + @abc.abstractmethod + def sheets(self) -> dict[str, Any]: + """Mapping of sheet names to sheet objects.""" + pass + @abc.abstractmethod def write_cells( self, @@ -1112,7 +1118,6 @@ def __init__( self.handles = get_handle( path, mode, storage_options=storage_options, is_text=False ) - self.sheets: dict[str, Any] = {} self.cur_sheet = None if date_format is None: diff --git a/pandas/io/excel/_odswriter.py b/pandas/io/excel/_odswriter.py index 0f31991ee29e9..9069a37ccb5af 100644 --- a/pandas/io/excel/_odswriter.py +++ b/pandas/io/excel/_odswriter.py @@ -58,6 +58,17 @@ def __init__( self.book = OpenDocumentSpreadsheet(**engine_kwargs) self._style_dict: dict[str, str] = {} + @property + def sheets(self) -> dict[str, Any]: + """Mapping of sheet names to sheet objects.""" + from odf.table import Table + + result = { + sheet.getAttribute("name"): sheet + for sheet in self.book.getElementsByType(Table) + } + return result + def save(self) -> None: """ Save workbook to disk. @@ -91,7 +102,7 @@ def write_cells( wks = self.sheets[sheet_name] else: wks = Table(name=sheet_name) - self.sheets[sheet_name] = wks + self.book.spreadsheet.addElement(wks) if validate_freeze_panes(freeze_panes): freeze_panes = cast(Tuple[int, int], freeze_panes) diff --git a/pandas/io/excel/_openpyxl.py b/pandas/io/excel/_openpyxl.py index 88a25d1c1e6ef..4b03c2536b31b 100644 --- a/pandas/io/excel/_openpyxl.py +++ b/pandas/io/excel/_openpyxl.py @@ -68,8 +68,6 @@ def __init__( self.book = load_workbook(self.handles.handle, **engine_kwargs) self.handles.handle.seek(0) - self.sheets = {name: self.book[name] for name in self.book.sheetnames} - else: # Create workbook object with default optimized_write=True. self.book = Workbook(**engine_kwargs) @@ -77,6 +75,12 @@ def __init__( if self.book.worksheets: self.book.remove(self.book.worksheets[0]) + @property + def sheets(self) -> dict[str, Any]: + """Mapping of sheet names to sheet objects.""" + result = {name: self.book[name] for name in self.book.sheetnames} + return result + def save(self) -> None: """ Save workbook to disk. @@ -440,7 +444,6 @@ def write_cells( target_index = self.book.index(old_wks) del self.book[sheet_name] wks = self.book.create_sheet(sheet_name, target_index) - self.sheets[sheet_name] = wks elif self.if_sheet_exists == "error": raise ValueError( f"Sheet '{sheet_name}' already exists and " @@ -458,7 +461,6 @@ def write_cells( else: wks = self.book.create_sheet() wks.title = sheet_name - self.sheets[sheet_name] = wks if validate_freeze_panes(freeze_panes): freeze_panes = cast(Tuple[int, int], freeze_panes) diff --git a/pandas/io/excel/_xlsxwriter.py b/pandas/io/excel/_xlsxwriter.py index 49c87732f1429..dbd6264827591 100644 --- a/pandas/io/excel/_xlsxwriter.py +++ b/pandas/io/excel/_xlsxwriter.py @@ -205,6 +205,11 @@ def __init__( self.book = Workbook(self.handles.handle, **engine_kwargs) + @property + def sheets(self) -> dict[str, Any]: + result = self.book.sheetnames + return result + def save(self) -> None: """ Save workbook to disk. @@ -222,11 +227,9 @@ def write_cells( # Write the frame cells using xlsxwriter. sheet_name = self._get_sheet_name(sheet_name) - if sheet_name in self.sheets: - wks = self.sheets[sheet_name] - else: + wks = self.book.get_worksheet_by_name(sheet_name) + if wks is None: wks = self.book.add_worksheet(sheet_name) - self.sheets[sheet_name] = wks style_dict = {"null": None} diff --git a/pandas/io/excel/_xlwt.py b/pandas/io/excel/_xlwt.py index 1ada0eb25f81c..fe2addc890c22 100644 --- a/pandas/io/excel/_xlwt.py +++ b/pandas/io/excel/_xlwt.py @@ -63,6 +63,12 @@ def __init__( self.fm_datetime = xlwt.easyxf(num_format_str=self.datetime_format) self.fm_date = xlwt.easyxf(num_format_str=self.date_format) + @property + def sheets(self) -> dict[str, Any]: + """Mapping of sheet names to sheet objects.""" + result = {sheet.name: sheet for sheet in self.book._Workbook__worksheets} + return result + def save(self) -> None: """ Save workbook to disk. diff --git a/pandas/tests/io/excel/test_odswriter.py b/pandas/tests/io/excel/test_odswriter.py index 0e6d1dac55506..e9dad0c7fedc9 100644 --- a/pandas/tests/io/excel/test_odswriter.py +++ b/pandas/tests/io/excel/test_odswriter.py @@ -56,3 +56,13 @@ def test_engine_kwargs(ext, engine_kwargs): else: with ExcelWriter(f, engine="odf", engine_kwargs=engine_kwargs) as _: pass + + +def test_book_and_sheets_consistent(ext): + # GH#45687 - Ensure sheets is updated if user modifies book + with tm.ensure_clean(ext) as f: + with ExcelWriter(f) as writer: + assert writer.sheets == {} + table = odf.table.Table(name="test_name") + writer.book.spreadsheet.addElement(table) + assert writer.sheets == {"test_name": table} diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index 7cd58be8a8237..0387591a248c1 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -379,3 +379,12 @@ def test_read_empty_with_blank_row(datapath, ext, read_only): result = pd.read_excel(wb, engine="openpyxl") expected = DataFrame() tm.assert_frame_equal(result, expected) + + +def test_book_and_sheets_consistent(ext): + # GH#45687 - Ensure sheets is updated if user modifies book + with tm.ensure_clean(ext) as f: + with ExcelWriter(f, engine="openpyxl") as writer: + assert writer.sheets == {} + sheet = writer.book.create_sheet("test_name", 0) + assert writer.sheets == {"test_name": sheet} diff --git a/pandas/tests/io/excel/test_writers.py b/pandas/tests/io/excel/test_writers.py index e2236e5d2f01d..c3715b19af7d5 100644 --- a/pandas/tests/io/excel/test_writers.py +++ b/pandas/tests/io/excel/test_writers.py @@ -1271,10 +1271,12 @@ def test_register_writer(self): # some awkward mocking to test out dispatch and such actually works called_save = [] called_write_cells = [] + called_sheets = [] class DummyClass(ExcelWriter): called_save = False called_write_cells = False + called_sheets = False supported_extensions = ["xlsx", "xls"] engine = "dummy" @@ -1284,12 +1286,18 @@ def save(self): def write_cells(self, *args, **kwargs): called_write_cells.append(True) + @property + def sheets(self): + called_sheets.append(True) + def check_called(func): func() assert len(called_save) >= 1 assert len(called_write_cells) >= 1 + assert len(called_sheets) == 0 del called_save[:] del called_write_cells[:] + del called_sheets[:] with option_context("io.excel.xlsx.writer", "dummy"): path = "something.xlsx" diff --git a/pandas/tests/io/excel/test_xlsxwriter.py b/pandas/tests/io/excel/test_xlsxwriter.py index b5c1b47775089..82d47a13aefbc 100644 --- a/pandas/tests/io/excel/test_xlsxwriter.py +++ b/pandas/tests/io/excel/test_xlsxwriter.py @@ -83,3 +83,12 @@ def test_engine_kwargs(ext, nan_inf_to_errors): with tm.ensure_clean(ext) as f: with ExcelWriter(f, engine="xlsxwriter", engine_kwargs=engine_kwargs) as writer: assert writer.book.nan_inf_to_errors == nan_inf_to_errors + + +def test_book_and_sheets_consistent(ext): + # GH#45687 - Ensure sheets is updated if user modifies book + with tm.ensure_clean(ext) as f: + with ExcelWriter(f, engine="xlsxwriter") as writer: + assert writer.sheets == {} + sheet = writer.book.add_worksheet("test_name") + assert writer.sheets == {"test_name": sheet} diff --git a/pandas/tests/io/excel/test_xlwt.py b/pandas/tests/io/excel/test_xlwt.py index ec333defd85ac..2d5386d6c616d 100644 --- a/pandas/tests/io/excel/test_xlwt.py +++ b/pandas/tests/io/excel/test_xlwt.py @@ -125,3 +125,12 @@ def test_engine_kwargs(ext, style_compression): assert writer.book._Workbook__styles.style_compression == style_compression # xlwt won't allow us to close without writing something DataFrame().to_excel(writer) + + +def test_book_and_sheets_consistent(ext): + # GH#45687 - Ensure sheets is updated if user modifies book + with tm.ensure_clean(ext) as f: + with ExcelWriter(f) as writer: + assert writer.sheets == {} + sheet = writer.book.add_sheet("test_name") + assert writer.sheets == {"test_name": sheet}
Towards #45572 - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them The plan to expose both `sheets` and `book` as public attributes of `ExcelWriter`. We need to make sure that `sheets` is correct if the user modifies the state via accessing `book`. This accesses a protected attribute for xlwt; I looked at the xlwt code and there is no public access to determine the sheets. The xlwt repository is read-only, we only support the most recent version, and xlwt will be removed in pandas 2.0. So I think this is okay.
https://api.github.com/repos/pandas-dev/pandas/pulls/45687
2022-01-28T22:26:46Z
2022-02-01T00:34:16Z
2022-02-01T00:34:16Z
2022-02-05T20:45:44Z
Backport PR #45667 on branch 1.4.x (TST: Dynamically use doctest_namespace only if running the doctest)
diff --git a/pandas/conftest.py b/pandas/conftest.py index 9009484f8d386..04f460902c11a 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -115,6 +115,12 @@ def pytest_collection_modifyitems(items, config): ] for item in items: + if config.getoption("--doctest-modules") or config.getoption( + "--doctest-cython", default=False + ): + # autouse=True for the add_doctest_imports can lead to expensive teardowns + # since doctest_namespace is a session fixture + item.add_marker(pytest.mark.usefixtures("add_doctest_imports")) # mark all tests in the pandas/tests/frame directory with "arraymanager" if "/frame/" in item.nodeid: item.add_marker(pytest.mark.arraymanager) @@ -187,6 +193,15 @@ def pytest_collection_modifyitems(items, config): ) +@pytest.fixture +def add_doctest_imports(doctest_namespace): + """ + Make `np` and `pd` names available for doctests. + """ + doctest_namespace["np"] = np + doctest_namespace["pd"] = pd + + # ---------------------------------------------------------------- # Autouse fixtures # ---------------------------------------------------------------- @@ -198,15 +213,6 @@ def configure_tests(): pd.set_option("chained_assignment", "raise") -@pytest.fixture(autouse=True) -def add_imports(doctest_namespace): - """ - Make `np` and `pd` names available for doctests. - """ - doctest_namespace["np"] = np - doctest_namespace["pd"] = pd - - # ---------------------------------------------------------------- # Common arguments # ----------------------------------------------------------------
Backport PR #45667: TST: Dynamically use doctest_namespace only if running the doctest
https://api.github.com/repos/pandas-dev/pandas/pulls/45685
2022-01-28T22:09:45Z
2022-01-29T00:12:11Z
2022-01-29T00:12:11Z
2022-01-29T00:12:11Z
Backport PR #45655 on branch 1.4.x (BUG: Fix window aggregations to skip over unused elements (GH-45647))
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index d0a58a19df92f..c73ec34d4733b 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -27,6 +27,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ - Fixed segfault in :meth:``DataFrame.to_json`` when dumping tz-aware datetimes in Python 3.10 (:issue:`42130`) +- Fixed window aggregations in :meth:`DataFrame.rolling` and :meth:`Series.rolling` to skip over unused elements (:issue:`45647`) - .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx index 5ebb60dc7e41b..ff53a577af33f 100644 --- a/pandas/_libs/window/aggregations.pyx +++ b/pandas/_libs/window/aggregations.pyx @@ -122,9 +122,9 @@ def roll_sum(const float64_t[:] values, ndarray[int64_t] start, ndarray[int64_t] end, int64_t minp) -> np.ndarray: cdef: Py_ssize_t i, j - float64_t sum_x = 0, compensation_add = 0, compensation_remove = 0 + float64_t sum_x, compensation_add, compensation_remove int64_t s, e - int64_t nobs = 0, N = len(values) + int64_t nobs = 0, N = len(start) ndarray[float64_t] output bint is_monotonic_increasing_bounds @@ -139,10 +139,12 @@ def roll_sum(const float64_t[:] values, ndarray[int64_t] start, s = start[i] e = end[i] - if i == 0 or not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: # setup + sum_x = compensation_add = compensation_remove = 0 + nobs = 0 for j in range(s, e): add_sum(values[j], &nobs, &sum_x, &compensation_add) @@ -226,9 +228,9 @@ cdef inline void remove_mean(float64_t val, Py_ssize_t *nobs, float64_t *sum_x, def roll_mean(const float64_t[:] values, ndarray[int64_t] start, ndarray[int64_t] end, int64_t minp) -> np.ndarray: cdef: - float64_t val, compensation_add = 0, compensation_remove = 0, sum_x = 0 + float64_t val, compensation_add, compensation_remove, sum_x int64_t s, e - Py_ssize_t nobs = 0, i, j, neg_ct = 0, N = len(values) + Py_ssize_t nobs, i, j, neg_ct, N = len(start) ndarray[float64_t] output bint is_monotonic_increasing_bounds @@ -243,8 +245,10 @@ def roll_mean(const float64_t[:] values, ndarray[int64_t] start, s = start[i] e = end[i] - if i == 0 or not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + compensation_add = compensation_remove = sum_x = 0 + nobs = neg_ct = 0 # setup for j in range(s, e): val = values[j] @@ -349,11 +353,11 @@ def roll_var(const float64_t[:] values, ndarray[int64_t] start, Numerically stable implementation using Welford's method. """ cdef: - float64_t mean_x = 0, ssqdm_x = 0, nobs = 0, compensation_add = 0, - float64_t compensation_remove = 0, + float64_t mean_x, ssqdm_x, nobs, compensation_add, + float64_t compensation_remove, float64_t val, prev, delta, mean_x_old int64_t s, e - Py_ssize_t i, j, N = len(values) + Py_ssize_t i, j, N = len(start) ndarray[float64_t] output bint is_monotonic_increasing_bounds @@ -372,8 +376,9 @@ def roll_var(const float64_t[:] values, ndarray[int64_t] start, # Over the first window, observations can only be added # never removed - if i == 0 or not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + mean_x = ssqdm_x = nobs = compensation_add = compensation_remove = 0 for j in range(s, e): add_var(values[j], &nobs, &mean_x, &ssqdm_x, &compensation_add) @@ -500,11 +505,11 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, cdef: Py_ssize_t i, j float64_t val, prev, min_val, mean_val, sum_val = 0 - float64_t compensation_xxx_add = 0, compensation_xxx_remove = 0 - float64_t compensation_xx_add = 0, compensation_xx_remove = 0 - float64_t compensation_x_add = 0, compensation_x_remove = 0 - float64_t x = 0, xx = 0, xxx = 0 - int64_t nobs = 0, N = len(values), nobs_mean = 0 + float64_t compensation_xxx_add, compensation_xxx_remove + float64_t compensation_xx_add, compensation_xx_remove + float64_t compensation_x_add, compensation_x_remove + float64_t x, xx, xxx + int64_t nobs = 0, N = len(start), V = len(values), nobs_mean = 0 int64_t s, e ndarray[float64_t] output, mean_array, values_copy bint is_monotonic_increasing_bounds @@ -518,7 +523,7 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, values_copy = np.copy(values) with nogil: - for i in range(0, N): + for i in range(0, V): val = values_copy[i] if notnan(val): nobs_mean += 1 @@ -527,7 +532,7 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, # Other cases would lead to imprecision for smallest values if min_val - mean_val > -1e5: mean_val = round(mean_val) - for i in range(0, N): + for i in range(0, V): values_copy[i] = values_copy[i] - mean_val for i in range(0, N): @@ -537,8 +542,13 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, # Over the first window, observations can only be added # never removed - if i == 0 or not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + compensation_xxx_add = compensation_xxx_remove = 0 + compensation_xx_add = compensation_xx_remove = 0 + compensation_x_add = compensation_x_remove = 0 + x = xx = xxx = 0 + nobs = 0 for j in range(s, e): val = values_copy[j] add_skew(val, &nobs, &x, &xx, &xxx, &compensation_x_add, @@ -682,12 +692,12 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, cdef: Py_ssize_t i, j float64_t val, prev, mean_val, min_val, sum_val = 0 - float64_t compensation_xxxx_add = 0, compensation_xxxx_remove = 0 - float64_t compensation_xxx_remove = 0, compensation_xxx_add = 0 - float64_t compensation_xx_remove = 0, compensation_xx_add = 0 - float64_t compensation_x_remove = 0, compensation_x_add = 0 - float64_t x = 0, xx = 0, xxx = 0, xxxx = 0 - int64_t nobs = 0, s, e, N = len(values), nobs_mean = 0 + float64_t compensation_xxxx_add, compensation_xxxx_remove + float64_t compensation_xxx_remove, compensation_xxx_add + float64_t compensation_xx_remove, compensation_xx_add + float64_t compensation_x_remove, compensation_x_add + float64_t x, xx, xxx, xxxx + int64_t nobs, s, e, N = len(start), V = len(values), nobs_mean = 0 ndarray[float64_t] output, values_copy bint is_monotonic_increasing_bounds @@ -700,7 +710,7 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, min_val = np.nanmin(values) with nogil: - for i in range(0, N): + for i in range(0, V): val = values_copy[i] if notnan(val): nobs_mean += 1 @@ -709,7 +719,7 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, # Other cases would lead to imprecision for smallest values if min_val - mean_val > -1e4: mean_val = round(mean_val) - for i in range(0, N): + for i in range(0, V): values_copy[i] = values_copy[i] - mean_val for i in range(0, N): @@ -719,8 +729,14 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, # Over the first window, observations can only be added # never removed - if i == 0 or not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + compensation_xxxx_add = compensation_xxxx_remove = 0 + compensation_xxx_remove = compensation_xxx_add = 0 + compensation_xx_remove = compensation_xx_add = 0 + compensation_x_remove = compensation_x_add = 0 + x = xx = xxx = xxxx = 0 + nobs = 0 for j in range(s, e): add_kurt(values_copy[j], &nobs, &x, &xx, &xxx, &xxxx, &compensation_x_add, &compensation_xx_add, @@ -764,7 +780,7 @@ def roll_median_c(const float64_t[:] values, ndarray[int64_t] start, Py_ssize_t i, j bint err = False, is_monotonic_increasing_bounds int midpoint, ret = 0 - int64_t nobs = 0, N = len(values), s, e, win + int64_t nobs = 0, N = len(start), s, e, win float64_t val, res, prev skiplist_t *sl ndarray[float64_t] output @@ -791,8 +807,12 @@ def roll_median_c(const float64_t[:] values, ndarray[int64_t] start, s = start[i] e = end[i] - if i == 0 or not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + if i != 0: + skiplist_destroy(sl) + sl = skiplist_init(<int>win) + nobs = 0 # setup for j in range(s, e): val = values[j] @@ -948,7 +968,7 @@ cdef _roll_min_max(ndarray[numeric_t] values, cdef: numeric_t ai int64_t curr_win_size, start - Py_ssize_t i, k, nobs = 0, N = len(values) + Py_ssize_t i, k, nobs = 0, N = len(starti) deque Q[int64_t] # min/max always the front deque W[int64_t] # track the whole window for nobs compute ndarray[float64_t, ndim=1] output @@ -1031,7 +1051,7 @@ def roll_quantile(const float64_t[:] values, ndarray[int64_t] start, O(N log(window)) implementation using skip list """ cdef: - Py_ssize_t i, j, s, e, N = len(values), idx + Py_ssize_t i, j, s, e, N = len(start), idx int ret = 0 int64_t nobs = 0, win float64_t val, prev, midpoint, idx_with_fraction @@ -1068,8 +1088,8 @@ def roll_quantile(const float64_t[:] values, ndarray[int64_t] start, s = start[i] e = end[i] - if i == 0 or not is_monotonic_increasing_bounds: - if not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + if i != 0: nobs = 0 skiplist_destroy(skiplist) skiplist = skiplist_init(<int>win) @@ -1160,7 +1180,7 @@ def roll_rank(const float64_t[:] values, ndarray[int64_t] start, derived from roll_quantile """ cdef: - Py_ssize_t i, j, s, e, N = len(values), idx + Py_ssize_t i, j, s, e, N = len(start), idx float64_t rank_min = 0, rank = 0 int64_t nobs = 0, win float64_t val @@ -1193,8 +1213,8 @@ def roll_rank(const float64_t[:] values, ndarray[int64_t] start, s = start[i] e = end[i] - if i == 0 or not is_monotonic_increasing_bounds: - if not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + if i != 0: nobs = 0 skiplist_destroy(skiplist) skiplist = skiplist_init(<int>win) diff --git a/pandas/tests/window/test_cython_aggregations.py b/pandas/tests/window/test_cython_aggregations.py new file mode 100644 index 0000000000000..c60cb6ea74ec0 --- /dev/null +++ b/pandas/tests/window/test_cython_aggregations.py @@ -0,0 +1,111 @@ +from functools import partial +import sys + +import numpy as np +import pytest + +import pandas._libs.window.aggregations as window_aggregations + +from pandas import Series +import pandas._testing as tm + + +def _get_rolling_aggregations(): + # list pairs of name and function + # each function has this signature: + # (const float64_t[:] values, ndarray[int64_t] start, + # ndarray[int64_t] end, int64_t minp) -> np.ndarray + named_roll_aggs = ( + [ + ("roll_sum", window_aggregations.roll_sum), + ("roll_mean", window_aggregations.roll_mean), + ] + + [ + (f"roll_var({ddof})", partial(window_aggregations.roll_var, ddof=ddof)) + for ddof in [0, 1] + ] + + [ + ("roll_skew", window_aggregations.roll_skew), + ("roll_kurt", window_aggregations.roll_kurt), + ("roll_median_c", window_aggregations.roll_median_c), + ("roll_max", window_aggregations.roll_max), + ("roll_min", window_aggregations.roll_min), + ] + + [ + ( + f"roll_quantile({quantile},{interpolation})", + partial( + window_aggregations.roll_quantile, + quantile=quantile, + interpolation=interpolation, + ), + ) + for quantile in [0.0001, 0.5, 0.9999] + for interpolation in window_aggregations.interpolation_types + ] + + [ + ( + f"roll_rank({percentile},{method},{ascending})", + partial( + window_aggregations.roll_rank, + percentile=percentile, + method=method, + ascending=ascending, + ), + ) + for percentile in [True, False] + for method in window_aggregations.rolling_rank_tiebreakers.keys() + for ascending in [True, False] + ] + ) + # unzip to a list of 2 tuples, names and functions + unzipped = list(zip(*named_roll_aggs)) + return {"ids": unzipped[0], "params": unzipped[1]} + + +_rolling_aggregations = _get_rolling_aggregations() + + +@pytest.fixture( + params=_rolling_aggregations["params"], ids=_rolling_aggregations["ids"] +) +def rolling_aggregation(request): + """Make a rolling aggregation function as fixture.""" + return request.param + + +def test_rolling_aggregation_boundary_consistency(rolling_aggregation): + # GH-45647 + minp, step, width, size, selection = 0, 1, 3, 11, [2, 7] + values = np.arange(1, 1 + size, dtype=np.float64) + end = np.arange(width, size, step, dtype=np.int64) + start = end - width + selarr = np.array(selection, dtype=np.int32) + result = Series(rolling_aggregation(values, start[selarr], end[selarr], minp)) + expected = Series(rolling_aggregation(values, start, end, minp)[selarr]) + tm.assert_equal(expected, result) + + +def test_rolling_aggregation_with_unused_elements(rolling_aggregation): + # GH-45647 + minp, width = 0, 5 # width at least 4 for kurt + size = 2 * width + 5 + values = np.arange(1, size + 1, dtype=np.float64) + values[width : width + 2] = sys.float_info.min + values[width + 2] = np.nan + values[width + 3 : width + 5] = sys.float_info.max + start = np.array([0, size - width], dtype=np.int64) + end = np.array([width, size], dtype=np.int64) + loc = np.array( + [j for i in range(len(start)) for j in range(start[i], end[i])], + dtype=np.int32, + ) + result = Series(rolling_aggregation(values, start, end, minp)) + compact_values = np.array(values[loc], dtype=np.float64) + compact_start = np.arange(0, len(start) * width, width, dtype=np.int64) + compact_end = compact_start + width + expected = Series( + rolling_aggregation(compact_values, compact_start, compact_end, minp) + ) + assert np.isfinite(expected.values).all(), "Not all expected values are finite" + tm.assert_equal(expected, result)
Backport PR #45655: BUG: Fix window aggregations to skip over unused elements (GH-45647)
https://api.github.com/repos/pandas-dev/pandas/pulls/45683
2022-01-28T19:52:59Z
2022-01-28T22:09:07Z
2022-01-28T22:09:07Z
2022-01-28T22:09:07Z
Backport PR #45662 on branch 1.4.x (BUG: Fix joining overlapping IntervalIndex objects (GH-45661))
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index d0a58a19df92f..23aefb783456d 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -18,6 +18,7 @@ Fixed regressions - Regression in :func:`.assert_frame_equal` not respecting ``check_flags=False`` (:issue:`45554`) - Regression in :meth:`Series.fillna` with ``downcast=False`` incorrectly downcasting ``object`` dtype (:issue:`45603`) - Regression in :meth:`DataFrame.loc.__setitem__` losing :class:`Index` name if :class:`DataFrame` was empty before (:issue:`45621`) +- Regression in :func:`join` with overlapping :class:`IntervalIndex` raising an ``InvalidIndexError`` (:issue:`45661`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 480ec29c418b8..2abd649d00b78 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4453,11 +4453,11 @@ def _join_via_get_indexer( if join_index is self: lindexer = None else: - lindexer = self.get_indexer(join_index) + lindexer = self.get_indexer_for(join_index) if join_index is other: rindexer = None else: - rindexer = other.get_indexer(join_index) + rindexer = other.get_indexer_for(join_index) return join_index, lindexer, rindexer @final diff --git a/pandas/tests/indexes/interval/test_join.py b/pandas/tests/indexes/interval/test_join.py new file mode 100644 index 0000000000000..2f42c530a6686 --- /dev/null +++ b/pandas/tests/indexes/interval/test_join.py @@ -0,0 +1,44 @@ +import pytest + +from pandas import ( + IntervalIndex, + MultiIndex, + RangeIndex, +) +import pandas._testing as tm + + +@pytest.fixture +def range_index(): + return RangeIndex(3, name="range_index") + + +@pytest.fixture +def interval_index(): + return IntervalIndex.from_tuples( + [(0.0, 1.0), (1.0, 2.0), (1.5, 2.5)], name="interval_index" + ) + + +def test_join_overlapping_in_mi_to_same_intervalindex(range_index, interval_index): + # GH-45661 + multi_index = MultiIndex.from_product([interval_index, range_index]) + result = multi_index.join(interval_index) + + tm.assert_index_equal(result, multi_index) + + +def test_join_overlapping_to_multiindex_with_same_interval(range_index, interval_index): + # GH-45661 + multi_index = MultiIndex.from_product([interval_index, range_index]) + result = interval_index.join(multi_index) + + tm.assert_index_equal(result, multi_index) + + +def test_join_overlapping_interval_to_another_intervalindex(interval_index): + # GH-45661 + flipped_interval_index = interval_index[::-1] + result = interval_index.join(flipped_interval_index) + + tm.assert_index_equal(result, interval_index)
Backport PR #45662: BUG: Fix joining overlapping IntervalIndex objects (GH-45661)
https://api.github.com/repos/pandas-dev/pandas/pulls/45682
2022-01-28T19:00:43Z
2022-01-28T22:08:09Z
2022-01-28T22:08:09Z
2022-01-28T22:08:09Z
BUG: Do not error on other dbapi2 connections
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 9509b96055255..ec4a1b7348262 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -20,7 +20,8 @@ Fixed regressions - Regression in :meth:`DataFrame.iat` setting values leading to not propagating correctly in subsequent lookups (:issue:`45684`) - Regression in :meth:`DataFrame.loc.__setitem__` losing :class:`Index` name if :class:`DataFrame` was empty before (:issue:`45621`) - Regression in :func:`join` with overlapping :class:`IntervalIndex` raising an ``InvalidIndexError`` (:issue:`45661`) - +- Regression in :func:`read_sql` with a DBAPI2 connection that is not an instance of ``sqlite3.Connection`` incorrectly requiring SQLAlchemy be installed (:issue:`45660`) +- .. --------------------------------------------------------------------------- diff --git a/pandas/io/sql.py b/pandas/io/sql.py index fcb3f5177ae3f..ba18412856d6c 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -736,12 +736,15 @@ def pandasSQL_builder(con, schema: str | None = None): if isinstance(con, sqlite3.Connection) or con is None: return SQLiteDatabase(con) - sqlalchemy = import_optional_dependency("sqlalchemy") + sqlalchemy = import_optional_dependency("sqlalchemy", errors="ignore") if isinstance(con, str): - con = sqlalchemy.create_engine(con) + if sqlalchemy is None: + raise ImportError("Using URI string without sqlalchemy installed.") + else: + con = sqlalchemy.create_engine(con) - if isinstance(con, sqlalchemy.engine.Connectable): + if sqlalchemy is not None and isinstance(con, sqlalchemy.engine.Connectable): return SQLDatabase(con, schema=schema) warnings.warn( diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 584308db3bae8..e383617c020aa 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -1532,9 +1532,25 @@ def test_sql_open_close(self, test_frame3): @pytest.mark.skipif(SQLALCHEMY_INSTALLED, reason="SQLAlchemy is installed") def test_con_string_import_error(self): conn = "mysql://root@localhost/pandas" - with pytest.raises(ImportError, match="SQLAlchemy"): + msg = "Using URI string without sqlalchemy installed" + with pytest.raises(ImportError, match=msg): sql.read_sql("SELECT * FROM iris", conn) + @pytest.mark.skipif(SQLALCHEMY_INSTALLED, reason="SQLAlchemy is installed") + def test_con_unknown_dbapi2_class_does_not_error_without_sql_alchemy_installed( + self, + ): + class MockSqliteConnection: + def __init__(self, *args, **kwargs): + self.conn = sqlite3.Connection(*args, **kwargs) + + def __getattr__(self, name): + return getattr(self.conn, name) + + conn = MockSqliteConnection(":memory:") + with tm.assert_produces_warning(UserWarning): + sql.read_sql("SELECT 1", conn) + def test_read_sql_delegate(self): iris_frame1 = sql.read_sql_query("SELECT * FROM iris", self.conn) iris_frame2 = sql.read_sql("SELECT * FROM iris", self.conn)
Do not throw an error in `pandasSQL_builder` when the connection is a dbapi2 connection that is not `sqlite3` and `sqlalchemy` is not installed. Also restores the behaviour prior to #42546 when the connection is a string but `sqlalchemy` is not installed. This partially addresses #45660 (it removes the requirement for `sqlalchemy` to be installed to use another connection object, however it does not remove the warning that such behaviour is unsupported). Prior to #42546, other dbapi2 objects would work regardless of whether `sqlalchemy` was installed, without a warning - after this PR, they were not supported. Support was re-added (with a warning) in #45496 , but with an unnecessary requirement on `sqlalchemy` - [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45679
2022-01-28T12:36:09Z
2022-01-31T13:29:53Z
2022-01-31T13:29:53Z
2022-02-03T15:46:38Z
BUG: read csv not breaking lines for warn messages
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 9aebcad1d8cae..000353aee99a0 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -285,6 +285,7 @@ I/O ^^^ - Bug in :meth:`DataFrame.to_stata` where no error is raised if the :class:`DataFrame` contains ``-np.inf`` (:issue:`45350`) - Bug in :meth:`DataFrame.info` where a new line at the end of the output is omitted when called on an empty :class:`DataFrame` (:issue:`45494`) +- Bug in :func:`read_csv` not recognizing line break for ``on_bad_lines="warn"`` for ``engine="c"`` (:issue:`41710`) - Bug in :func:`read_parquet` when ``engine="pyarrow"`` which caused partial write to disk when column of unsupported datatype was passed (:issue:`44914`) - diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index 08c885fba172a..b4d2c60837a7e 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -1,5 +1,6 @@ # Copyright (c) 2012, Lambda Foundry, Inc. # See LICENSE for the license +from base64 import decode from csv import ( QUOTE_MINIMAL, QUOTE_NONE, @@ -839,7 +840,9 @@ cdef class TextReader: status = tokenize_nrows(self.parser, nrows, self.encoding_errors) if self.parser.warn_msg != NULL: - print(self.parser.warn_msg, file=sys.stderr) + print(PyUnicode_DecodeUTF8( + self.parser.warn_msg, strlen(self.parser.warn_msg), + self.encoding_errors), file=sys.stderr) free(self.parser.warn_msg) self.parser.warn_msg = NULL @@ -868,7 +871,9 @@ cdef class TextReader: status = tokenize_all_rows(self.parser, self.encoding_errors) if self.parser.warn_msg != NULL: - print(self.parser.warn_msg, file=sys.stderr) + print(PyUnicode_DecodeUTF8( + self.parser.warn_msg, strlen(self.parser.warn_msg), + self.encoding_errors), file=sys.stderr) free(self.parser.warn_msg) self.parser.warn_msg = NULL diff --git a/pandas/tests/io/parser/common/test_read_errors.py b/pandas/tests/io/parser/common/test_read_errors.py index fe00afb4fdc1d..2274646ae7c69 100644 --- a/pandas/tests/io/parser/common/test_read_errors.py +++ b/pandas/tests/io/parser/common/test_read_errors.py @@ -278,3 +278,30 @@ def test_conflict_on_bad_line(all_parsers, error_bad_lines, warn_bad_lines): "Please only set on_bad_lines.", ): parser.read_csv(StringIO(data), on_bad_lines="error", **kwds) + + +def test_on_bad_lines_warn_correct_formatting(all_parsers, capsys): + # see gh-15925 + parser = all_parsers + data = """1,2 +a,b +a,b,c +a,b,d +a,b +""" + expected = DataFrame({"1": "a", "2": ["b"] * 2}) + + result = parser.read_csv(StringIO(data), on_bad_lines="warn") + tm.assert_frame_equal(result, expected) + + captured = capsys.readouterr() + if parser.engine == "c": + warn = """Skipping line 3: expected 2 fields, saw 3 +Skipping line 4: expected 2 fields, saw 3 + +""" + else: + warn = """Skipping line 3: Expected 2 fields in line 3, saw 3 +Skipping line 4: Expected 2 fields in line 4, saw 3 +""" + assert captured.err == warn
- [x] closes #41710 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry We should probably unify the warning messages too
https://api.github.com/repos/pandas-dev/pandas/pulls/45677
2022-01-28T11:55:36Z
2022-01-28T18:52:40Z
2022-01-28T18:52:40Z
2022-01-28T19:45:45Z
TST: Move once-used fixtures to specific files
diff --git a/pandas/tests/window/conftest.py b/pandas/tests/window/conftest.py index 09233e3f31c89..f2832652ed58f 100644 --- a/pandas/tests/window/conftest.py +++ b/pandas/tests/window/conftest.py @@ -12,7 +12,6 @@ DataFrame, Series, bdate_range, - to_datetime, ) @@ -22,27 +21,6 @@ def raw(request): return request.param -@pytest.fixture( - params=[ - "triang", - "blackman", - "hamming", - "bartlett", - "bohman", - "blackmanharris", - "nuttall", - "barthann", - ] -) -def win_types(request): - return request.param - - -@pytest.fixture(params=["kaiser", "gaussian", "general_gaussian", "exponential"]) -def win_types_special(request): - return request.param - - @pytest.fixture( params=[ "sum", @@ -62,28 +40,6 @@ def arithmetic_win_operators(request): return request.param -@pytest.fixture( - params=[ - ["sum", {}], - ["mean", {}], - ["median", {}], - ["max", {}], - ["min", {}], - ["var", {}], - ["var", {"ddof": 0}], - ["std", {}], - ["std", {"ddof": 0}], - ] -) -def arithmetic_numba_supported_operators(request): - return request.param - - -@pytest.fixture(params=["right", "left", "both", "neither"]) -def closed(request): - return request.param - - @pytest.fixture(params=[True, False]) def center(request): return request.param @@ -94,12 +50,6 @@ def min_periods(request): return request.param -@pytest.fixture(params=["single", "table"]) -def method(request): - """method keyword in rolling/expanding/ewm constructor""" - return request.param - - @pytest.fixture(params=[True, False]) def parallel(request): """parallel keyword argument for numba.jit""" @@ -152,95 +102,12 @@ def engine_and_raw(request): return request.param -@pytest.fixture -def times_frame(): - """Frame for testing times argument in EWM groupby.""" - return DataFrame( - { - "A": ["a", "b", "c", "a", "b", "c", "a", "b", "c", "a"], - "B": [0, 0, 0, 1, 1, 1, 2, 2, 2, 3], - "C": to_datetime( - [ - "2020-01-01", - "2020-01-01", - "2020-01-01", - "2020-01-02", - "2020-01-10", - "2020-01-22", - "2020-01-03", - "2020-01-23", - "2020-01-23", - "2020-01-04", - ] - ), - } - ) - - @pytest.fixture(params=["1 day", timedelta(days=1)]) def halflife_with_times(request): """Halflife argument for EWM when times is specified.""" return request.param -@pytest.fixture( - params=[ - "object", - "category", - "int8", - "int16", - "int32", - "int64", - "uint8", - "uint16", - "uint32", - "uint64", - "float16", - "float32", - "float64", - "m8[ns]", - "M8[ns]", - "datetime64[ns, UTC]", - ] -) -def dtypes(request): - """Dtypes for window tests""" - return request.param - - -@pytest.fixture( - params=[ - DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[1, 0]), - DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[1, 1]), - DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=["C", "C"]), - DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[1.0, 0]), - DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[0.0, 1]), - DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=["C", 1]), - DataFrame([[2.0, 4.0], [1.0, 2.0], [5.0, 2.0], [8.0, 1.0]], columns=[1, 0.0]), - DataFrame([[2, 4.0], [1, 2.0], [5, 2.0], [8, 1.0]], columns=[0, 1.0]), - DataFrame([[2, 4], [1, 2], [5, 2], [8, 1.0]], columns=[1.0, "X"]), - ] -) -def pairwise_frames(request): - """Pairwise frames test_pairwise""" - return request.param - - -@pytest.fixture -def pairwise_target_frame(): - """Pairwise target frame for test_pairwise""" - return DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[0, 1]) - - -@pytest.fixture -def pairwise_other_frame(): - """Pairwise other frame for test_pairwise""" - return DataFrame( - [[None, 1, 1], [None, 1, 2], [None, 3, 2], [None, 8, 1]], - columns=["Y", "Z", "X"], - ) - - @pytest.fixture def series(): """Make mocked series as fixture.""" diff --git a/pandas/tests/window/moments/conftest.py b/pandas/tests/window/moments/conftest.py index 8f7c20fe03a02..fccf80c3c7a58 100644 --- a/pandas/tests/window/moments/conftest.py +++ b/pandas/tests/window/moments/conftest.py @@ -41,7 +41,6 @@ def is_constant(x): for obj in itertools.chain(create_series(), create_dataframes()) if is_constant(obj) ), - scope="module", ) def consistent_data(request): return request.param @@ -68,12 +67,6 @@ def all_data(request): return request.param -@pytest.fixture(params=[(1, 0), (5, 1)]) -def rolling_consistency_cases(request): - """window, min_periods""" - return request.param - - @pytest.fixture(params=[0, 2]) def min_periods(request): return request.param diff --git a/pandas/tests/window/moments/test_moments_consistency_rolling.py b/pandas/tests/window/moments/test_moments_consistency_rolling.py index daca19b0993bf..62bfc66b124f3 100644 --- a/pandas/tests/window/moments/test_moments_consistency_rolling.py +++ b/pandas/tests/window/moments/test_moments_consistency_rolling.py @@ -13,6 +13,12 @@ def all_na(x): return x.isnull().all().all() +@pytest.fixture(params=[(1, 0), (5, 1)]) +def rolling_consistency_cases(request): + """window, min_periods""" + return request.param + + @pytest.mark.parametrize("f", [lambda v: Series(v).sum(), np.nansum, np.sum]) def test_rolling_apply_consistency_sum( request, all_data, rolling_consistency_cases, center, f diff --git a/pandas/tests/window/test_dtypes.py b/pandas/tests/window/test_dtypes.py index 02b5f8a313825..80a96c3a8cee9 100644 --- a/pandas/tests/window/test_dtypes.py +++ b/pandas/tests/window/test_dtypes.py @@ -24,6 +24,31 @@ def get_dtype(dtype, coerce_int=None): return pandas_dtype(dtype) +@pytest.fixture( + params=[ + "object", + "category", + "int8", + "int16", + "int32", + "int64", + "uint8", + "uint16", + "uint32", + "uint64", + "float16", + "float32", + "float64", + "m8[ns]", + "M8[ns]", + "datetime64[ns, UTC]", + ] +) +def dtypes(request): + """Dtypes for window tests""" + return request.param + + @pytest.mark.parametrize( "method, data, expected_data, coerce_int, min_periods", [ diff --git a/pandas/tests/window/test_groupby.py b/pandas/tests/window/test_groupby.py index 6ec19e4899d53..5125587df9ea2 100644 --- a/pandas/tests/window/test_groupby.py +++ b/pandas/tests/window/test_groupby.py @@ -15,6 +15,31 @@ from pandas.core.groupby.groupby import get_groupby +@pytest.fixture +def times_frame(): + """Frame for testing times argument in EWM groupby.""" + return DataFrame( + { + "A": ["a", "b", "c", "a", "b", "c", "a", "b", "c", "a"], + "B": [0, 0, 0, 1, 1, 1, 2, 2, 2, 3], + "C": to_datetime( + [ + "2020-01-01", + "2020-01-01", + "2020-01-01", + "2020-01-02", + "2020-01-10", + "2020-01-22", + "2020-01-03", + "2020-01-23", + "2020-01-23", + "2020-01-04", + ] + ), + } + ) + + class TestRolling: def setup_method(self): self.frame = DataFrame({"A": [1] * 20 + [2] * 12 + [3] * 8, "B": np.arange(40)}) diff --git a/pandas/tests/window/test_numba.py b/pandas/tests/window/test_numba.py index a14515ca9c018..a9e38751c9a2f 100644 --- a/pandas/tests/window/test_numba.py +++ b/pandas/tests/window/test_numba.py @@ -14,6 +14,29 @@ from pandas.core.util.numba_ import NUMBA_FUNC_CACHE +@pytest.fixture(params=["single", "table"]) +def method(request): + """method keyword in rolling/expanding/ewm constructor""" + return request.param + + +@pytest.fixture( + params=[ + ["sum", {}], + ["mean", {}], + ["median", {}], + ["max", {}], + ["min", {}], + ["var", {}], + ["var", {"ddof": 0}], + ["std", {}], + ["std", {"ddof": 0}], + ] +) +def arithmetic_numba_supported_operators(request): + return request.param + + @td.skip_if_no("numba") @pytest.mark.filterwarnings("ignore:\n") # Filter warnings when parallel=True and the function can't be parallelized by Numba diff --git a/pandas/tests/window/test_pairwise.py b/pandas/tests/window/test_pairwise.py index 77ff6ae03d836..6c3f3f7075ce0 100644 --- a/pandas/tests/window/test_pairwise.py +++ b/pandas/tests/window/test_pairwise.py @@ -14,6 +14,39 @@ from pandas.core.algorithms import safe_sort +@pytest.fixture( + params=[ + DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[1, 0]), + DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[1, 1]), + DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=["C", "C"]), + DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[1.0, 0]), + DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[0.0, 1]), + DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=["C", 1]), + DataFrame([[2.0, 4.0], [1.0, 2.0], [5.0, 2.0], [8.0, 1.0]], columns=[1, 0.0]), + DataFrame([[2, 4.0], [1, 2.0], [5, 2.0], [8, 1.0]], columns=[0, 1.0]), + DataFrame([[2, 4], [1, 2], [5, 2], [8, 1.0]], columns=[1.0, "X"]), + ] +) +def pairwise_frames(request): + """Pairwise frames test_pairwise""" + return request.param + + +@pytest.fixture +def pairwise_target_frame(): + """Pairwise target frame for test_pairwise""" + return DataFrame([[2, 4], [1, 2], [5, 2], [8, 1]], columns=[0, 1]) + + +@pytest.fixture +def pairwise_other_frame(): + """Pairwise other frame for test_pairwise""" + return DataFrame( + [[None, 1, 1], [None, 1, 2], [None, 3, 2], [None, 8, 1]], + columns=["Y", "Z", "X"], + ) + + def test_rolling_cov(series): A = series B = A + np.random.randn(len(A)) diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index 31dbcdfce44e7..ced163178f73a 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -132,6 +132,7 @@ def test_numpy_compat(method): getattr(r, method)(dtype=np.float64) +@pytest.mark.parametrize("closed", ["right", "left", "both", "neither"]) def test_closed_fixed(closed, arithmetic_win_operators): # GH 34315 func_name = arithmetic_win_operators diff --git a/pandas/tests/window/test_timeseries_window.py b/pandas/tests/window/test_timeseries_window.py index c94c418c3d9a7..f51764e04715a 100644 --- a/pandas/tests/window/test_timeseries_window.py +++ b/pandas/tests/window/test_timeseries_window.py @@ -20,7 +20,7 @@ class TestRollingTS: # rolling time-series friendly # xref GH13327 - def setup_method(self, method): + def setup_method(self): self.regular = DataFrame( {"A": date_range("20130101", periods=5, freq="s"), "B": range(5)} diff --git a/pandas/tests/window/test_win_type.py b/pandas/tests/window/test_win_type.py index 6e0edc9e8500c..03ea745d9cb86 100644 --- a/pandas/tests/window/test_win_type.py +++ b/pandas/tests/window/test_win_type.py @@ -15,6 +15,27 @@ from pandas.api.indexers import BaseIndexer +@pytest.fixture( + params=[ + "triang", + "blackman", + "hamming", + "bartlett", + "bohman", + "blackmanharris", + "nuttall", + "barthann", + ] +) +def win_types(request): + return request.param + + +@pytest.fixture(params=["kaiser", "gaussian", "general_gaussian", "exponential"]) +def win_types_special(request): + return request.param + + @td.skip_if_no_scipy def test_constructor(frame_or_series): # GH 12669
- [x] tests added / passed
https://api.github.com/repos/pandas-dev/pandas/pulls/45674
2022-01-28T05:22:11Z
2022-01-28T16:40:32Z
2022-01-28T16:40:32Z
2022-01-28T17:24:32Z
BUG: consistent downcast on fillna no-ops
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 919ed926f8195..f274c5c4c665e 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -278,7 +278,7 @@ Indexing Missing ^^^^^^^ -- +- Bug in :meth:`Series.fillna` and :meth:`DataFrame.fillna` with ``downcast`` keyword not being respected in some cases where there are no NA values present (:issue:`45423`) - MultiIndex diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 80e1d0bede2cd..c7ec4f35e0ff1 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -15,6 +15,7 @@ from pandas._libs import ( NaT, + algos as libalgos, lib, ) from pandas._typing import ( @@ -382,6 +383,11 @@ def shift(self: T, periods: int, axis: int, fill_value) -> T: ) def fillna(self: T, value, limit, inplace: bool, downcast) -> T: + + if limit is not None: + # Do this validation even if we go through one of the no-op paths + limit = libalgos.validate_limit(None, limit=limit) + return self.apply_with_block( "fillna", value=value, limit=limit, inplace=inplace, downcast=downcast ) diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index d5bae63976e63..d0c7e69567169 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -17,7 +17,6 @@ from pandas._libs import ( Timestamp, - algos as libalgos, internals as libinternals, lib, writers, @@ -447,36 +446,42 @@ def _split_op_result(self, result: ArrayLike) -> list[Block]: return [nb] def fillna( - self, value, limit=None, inplace: bool = False, downcast=None + self, value, limit: int | None = None, inplace: bool = False, downcast=None ) -> list[Block]: """ fillna on the block with the value. If we fail, then convert to ObjectBlock and try again """ + # Caller is responsible for validating limit; if int it is strictly positive inplace = validate_bool_kwarg(inplace, "inplace") - mask = isna(self.values) - mask, noop = validate_putmask(self.values, mask) - - if limit is not None: - limit = libalgos.validate_limit(None, limit=limit) - mask[mask.cumsum(self.ndim - 1) > limit] = False - if not self._can_hold_na: + # can short-circuit the isna call + noop = True + else: + mask = isna(self.values) + mask, noop = validate_putmask(self.values, mask) + + if noop: + # we can't process the value, but nothing to do if inplace: + # Arbitrarily imposing the convention that we ignore downcast + # on no-op when inplace=True return [self] else: - return [self.copy()] + # GH#45423 consistent downcasting on no-ops. + nb = self.copy() + nbs = nb._maybe_downcast([nb], downcast=downcast) + return nbs + + if limit is not None: + mask[mask.cumsum(self.ndim - 1) > limit] = False if self._can_hold_element(value): nb = self if inplace else self.copy() putmask_inplace(nb.values, mask, value) return nb._maybe_downcast([nb], downcast) - if noop: - # we can't process the value, but nothing to do - return [self] if inplace else [self.copy()] - elif self.ndim == 1 or self.shape[0] == 1: blk = self.coerce_to_target_dtype(value) # bc we have already cast, inplace=True may avoid an extra copy @@ -1448,8 +1453,9 @@ def putmask(self, mask, new) -> list[Block]: return [self] def fillna( - self, value, limit=None, inplace: bool = False, downcast=None + self, value, limit: int | None = None, inplace: bool = False, downcast=None ) -> list[Block]: + # Caller is responsible for validating limit; if int it is strictly positive try: new_values = self.values.fillna(value=value, limit=limit) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 1d1d955c9024a..6297a7578ccd4 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -14,6 +14,7 @@ import numpy as np from pandas._libs import ( + algos as libalgos, internals as libinternals, lib, ) @@ -368,6 +369,11 @@ def shift(self: T, periods: int, axis: int, fill_value) -> T: return self.apply("shift", periods=periods, axis=axis, fill_value=fill_value) def fillna(self: T, value, limit, inplace: bool, downcast) -> T: + + if limit is not None: + # Do this validation even if we go through one of the no-op paths + limit = libalgos.validate_limit(None, limit=limit) + return self.apply( "fillna", value=value, limit=limit, inplace=inplace, downcast=downcast ) diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index 21a45d9ee1f20..77ae9fb4c7eff 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -250,6 +250,25 @@ def test_fillna_downcast_false(self, frame_or_series): result = obj.fillna("", downcast=False) tm.assert_equal(result, obj) + def test_fillna_downcast_noop(self, frame_or_series): + # GH#45423 + # Two relevant paths: + # 1) not _can_hold_na (e.g. integer) + # 2) _can_hold_na + noop + not can_hold_element + + obj = frame_or_series([1, 2, 3], dtype=np.int64) + res = obj.fillna("foo", downcast=np.dtype(np.int32)) + expected = obj.astype(np.int32) + tm.assert_equal(res, expected) + + obj2 = obj.astype(np.float64) + res2 = obj2.fillna("foo", downcast="infer") + expected2 = obj # get back int64 + tm.assert_equal(res2, expected2) + + res3 = obj2.fillna("foo", downcast=np.dtype(np.int32)) + tm.assert_equal(res3, expected) + @pytest.mark.parametrize("columns", [["A", "A", "B"], ["A", "A"]]) def test_fillna_dictlike_value_duplicate_colnames(self, columns): # GH#43476
- [x] xref #45423 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45673
2022-01-28T04:40:28Z
2022-02-01T00:03:48Z
2022-02-01T00:03:48Z
2022-02-01T00:17:44Z
REF: implement LossySetitemError
diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 33732bcaca733..d23910c37b52b 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -39,6 +39,7 @@ from pandas.errors import IntCastingNaNError from pandas.util._decorators import Appender +from pandas.core.dtypes.cast import LossySetitemError from pandas.core.dtypes.common import ( is_categorical_dtype, is_dtype_equal, @@ -1081,7 +1082,7 @@ def _validate_listlike(self, value): try: self.left._validate_fill_value(value_left) - except (ValueError, TypeError) as err: + except (LossySetitemError, TypeError) as err: msg = ( "'value' should be a compatible interval type, " f"got {type(value)} instead." diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 216dd1e65de3a..1645ee13724b3 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1924,6 +1924,8 @@ def can_hold_element(arr: ArrayLike, element: Any) -> bool: arr._validate_setitem_value(element) return True except (ValueError, TypeError): + # TODO(2.0): stop catching ValueError for tzaware, see + # _catch_deprecated_value_error return False # This is technically incorrect, but maintains the behavior of @@ -1933,7 +1935,7 @@ def can_hold_element(arr: ArrayLike, element: Any) -> bool: try: np_can_hold_element(dtype, element) return True - except (TypeError, ValueError): + except (TypeError, LossySetitemError): return False @@ -1963,7 +1965,7 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any: if isinstance(element, range): if _dtype_can_hold_range(element, dtype): return element - raise ValueError + raise LossySetitemError elif is_integer(element) or (is_float(element) and element.is_integer()): # e.g. test_setitem_series_int8 if we have a python int 1 @@ -1972,7 +1974,7 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any: info = np.iinfo(dtype) if info.min <= element <= info.max: return dtype.type(element) - raise ValueError + raise LossySetitemError if tipo is not None: if tipo.kind not in ["i", "u"]: @@ -1986,10 +1988,10 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any: # np.putmask, whereas the raw values cannot. # see TestSetitemFloatNDarrayIntoIntegerSeries return casted - raise ValueError + raise LossySetitemError # Anything other than integer we cannot hold - raise ValueError + raise LossySetitemError elif ( dtype.kind == "u" and isinstance(element, np.ndarray) @@ -2001,31 +2003,31 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any: # TODO: faster to check (element >=0).all()? potential # itemsize issues there? return casted - raise ValueError + raise LossySetitemError elif dtype.itemsize < tipo.itemsize: - raise ValueError + raise LossySetitemError elif not isinstance(tipo, np.dtype): # i.e. nullable IntegerDtype; we can put this into an ndarray # losslessly iff it has no NAs if element._hasna: - raise ValueError + raise LossySetitemError return element return element - raise ValueError + raise LossySetitemError elif dtype.kind == "f": if tipo is not None: # TODO: itemsize check? if tipo.kind not in ["f", "i", "u"]: # Anything other than float/integer we cannot hold - raise ValueError + raise LossySetitemError elif not isinstance(tipo, np.dtype): # i.e. nullable IntegerDtype or FloatingDtype; # we can put this into an ndarray losslessly iff it has no NAs if element._hasna: - raise ValueError + raise LossySetitemError return element elif tipo.itemsize > dtype.itemsize: if isinstance(element, np.ndarray): @@ -2034,13 +2036,13 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any: # TODO(np>=1.20): we can just use np.array_equal with equal_nan if array_equivalent(casted, element): return casted - raise ValueError + raise LossySetitemError return element if lib.is_integer(element) or lib.is_float(element): return element - raise ValueError + raise LossySetitemError elif dtype.kind == "c": if lib.is_integer(element) or lib.is_complex(element) or lib.is_float(element): @@ -2052,13 +2054,13 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any: if casted == element: return casted # otherwise e.g. overflow see test_32878_complex_itemsize - raise ValueError + raise LossySetitemError if tipo is not None: if tipo.kind in ["c", "f", "i", "u"]: return element - raise ValueError - raise ValueError + raise LossySetitemError + raise LossySetitemError elif dtype.kind == "b": if tipo is not None: @@ -2067,12 +2069,12 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any: # i.e. we have a BooleanArray if element._hasna: # i.e. there are pd.NA elements - raise ValueError + raise LossySetitemError return element - raise ValueError + raise LossySetitemError if lib.is_bool(element): return element - raise ValueError + raise LossySetitemError elif dtype.kind == "S": # TODO: test tests.frame.methods.test_replace tests get here, @@ -2080,10 +2082,10 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any: if tipo is not None: if tipo.kind == "S" and tipo.itemsize <= dtype.itemsize: return element - raise ValueError + raise LossySetitemError if isinstance(element, bytes) and len(element) <= dtype.itemsize: return element - raise ValueError + raise LossySetitemError raise NotImplementedError(dtype) @@ -2097,3 +2099,11 @@ def _dtype_can_hold_range(rng: range, dtype: np.dtype) -> bool: if not len(rng): return True return np.can_cast(rng[0], dtype) and np.can_cast(rng[-1], dtype) + + +class LossySetitemError(Exception): + """ + Raised when trying to do a __setitem__ on an np.ndarray that is not lossless. + """ + + pass diff --git a/pandas/core/frame.py b/pandas/core/frame.py index a68a2f40d02f7..5674c118f63d6 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -93,6 +93,7 @@ ) from pandas.core.dtypes.cast import ( + LossySetitemError, can_hold_element, construct_1d_arraylike_from_scalar, construct_2d_arraylike_from_scalar, @@ -3882,11 +3883,11 @@ def _set_value( series = self._get_item_cache(col) loc = self.index.get_loc(index) - # setitem_inplace will do validation that may raise TypeError - # or ValueError + # setitem_inplace will do validation that may raise TypeError, + # ValueError, or LossySetitemError series._mgr.setitem_inplace(loc, value) - except (KeyError, TypeError, ValueError): + except (KeyError, TypeError, ValueError, LossySetitemError): # set using a non-recursive method & reset the cache if takeable: self.iloc[index, col] = value diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 935d61447df7b..c57ee4fb7e79e 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -68,6 +68,7 @@ from pandas.core.dtypes.astype import astype_nansafe from pandas.core.dtypes.cast import ( + LossySetitemError, can_hold_element, common_dtype_categorical_compat, ensure_dtype_can_hold_na, @@ -5071,12 +5072,13 @@ def _validate_fill_value(self, value): """ dtype = self.dtype if isinstance(dtype, np.dtype) and dtype.kind not in ["m", "M"]: + # return np_can_hold_element(dtype, value) try: return np_can_hold_element(dtype, value) - except ValueError as err: + except LossySetitemError as err: # re-raise as TypeError for consistency raise TypeError from err - if not can_hold_element(self._values, value): + elif not can_hold_element(self._values, value): raise TypeError return value @@ -5294,7 +5296,7 @@ def putmask(self, mask, value) -> Index: value = self._na_value try: converted = self._validate_fill_value(value) - except (ValueError, TypeError) as err: + except (LossySetitemError, ValueError, TypeError) as err: if is_object_dtype(self): # pragma: no cover raise err @@ -6719,7 +6721,7 @@ def insert(self, loc: int, item) -> Index: return type(self)._simple_new(res_values, name=self.name) else: item = self._validate_fill_value(item) - except (TypeError, ValueError): + except (TypeError, ValueError, LossySetitemError): # e.g. trying to insert an integer into a DatetimeIndex # We cannot keep the same dtype, so cast to the (often object) # minimal shared dtype before doing the insert. diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index d5bae63976e63..2e6492b47cb08 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -36,6 +36,7 @@ from pandas.core.dtypes.astype import astype_array_safe from pandas.core.dtypes.cast import ( + LossySetitemError, can_hold_element, find_result_type, maybe_downcast_to_dtype, @@ -1191,7 +1192,7 @@ def where(self, other, cond) -> list[Block]: # but this gets us back 'casted' which we will re-use below; # without using 'casted', expressions.where may do unwanted upcasts. casted = np_can_hold_element(values.dtype, other) - except (ValueError, TypeError): + except (ValueError, TypeError, LossySetitemError): # we cannot coerce, return a compat dtype block = self.coerce_to_target_dtype(other) blocks = block.where(orig_other, cond) diff --git a/pandas/core/series.py b/pandas/core/series.py index a4fcc1e0b1b12..e4ba9ef2825e3 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -62,6 +62,7 @@ ) from pandas.core.dtypes.cast import ( + LossySetitemError, convert_dtypes, maybe_box_native, maybe_cast_pointwise_result, @@ -1102,7 +1103,7 @@ def __setitem__(self, key, value) -> None: # GH#12862 adding a new key to the Series self.loc[key] = value - except (TypeError, ValueError): + except (TypeError, ValueError, LossySetitemError): # The key was OK, but we cannot set the value losslessly indexer = self.index.get_loc(key) self._set_values(indexer, value)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry Catch this specifically instead of ValueError, which can have unrelated causes xref https://github.com/numpy/numpy/issues/20923
https://api.github.com/repos/pandas-dev/pandas/pulls/45672
2022-01-28T02:38:52Z
2022-02-01T00:02:13Z
2022-02-01T00:02:13Z
2022-02-01T01:34:30Z
Backport PR #45565 on branch 1.4.x (REGR: check_flags not respected in assert_frame_equal)
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 21aab5058d25b..d0a58a19df92f 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -15,6 +15,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Regression in :meth:`Series.mask` with ``inplace=True`` and ``PeriodDtype`` and an incompatible ``other`` coercing to a common dtype instead of raising (:issue:`45546`) +- Regression in :func:`.assert_frame_equal` not respecting ``check_flags=False`` (:issue:`45554`) - Regression in :meth:`Series.fillna` with ``downcast=False`` incorrectly downcasting ``object`` dtype (:issue:`45603`) - Regression in :meth:`DataFrame.loc.__setitem__` losing :class:`Index` name if :class:`DataFrame` was empty before (:issue:`45621`) - diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index ea75af20bb0b6..77e4065008804 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -1344,6 +1344,7 @@ def assert_frame_equal( rtol=rtol, atol=atol, check_index=False, + check_flags=False, ) diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py index faea0a54dc330..6ff1a1c17b179 100644 --- a/pandas/tests/util/test_assert_frame_equal.py +++ b/pandas/tests/util/test_assert_frame_equal.py @@ -323,9 +323,22 @@ def test_frame_equal_mixed_dtypes(frame_or_series, any_numeric_ea_dtype, indexer tm.assert_equal(obj1, obj2, check_exact=True, check_dtype=False) -def test_assert_series_equal_check_like_different_indexes(): +def test_assert_frame_equal_check_like_different_indexes(): # GH#39739 df1 = DataFrame(index=pd.Index([], dtype="object")) df2 = DataFrame(index=pd.RangeIndex(start=0, stop=0, step=1)) with pytest.raises(AssertionError, match="DataFrame.index are different"): tm.assert_frame_equal(df1, df2, check_like=True) + + +def test_assert_frame_equal_checking_allow_dups_flag(): + # GH#45554 + left = DataFrame([[1, 2], [3, 4]]) + left.flags.allows_duplicate_labels = False + + right = DataFrame([[1, 2], [3, 4]]) + right.flags.allows_duplicate_labels = True + tm.assert_frame_equal(left, right, check_flags=False) + + with pytest.raises(AssertionError, match="allows_duplicate_labels"): + tm.assert_frame_equal(left, right, check_flags=True)
Backport PR #45565: REGR: check_flags not respected in assert_frame_equal
https://api.github.com/repos/pandas-dev/pandas/pulls/45671
2022-01-28T02:00:00Z
2022-01-28T10:44:42Z
2022-01-28T10:44:42Z
2022-01-28T10:44:42Z
Backport PR #45612 on branch 1.4.x (DOC: Improve reshaping.rst)
diff --git a/doc/source/user_guide/reshaping.rst b/doc/source/user_guide/reshaping.rst index e74272c825e46..f9e68b1b39ddc 100644 --- a/doc/source/user_guide/reshaping.rst +++ b/doc/source/user_guide/reshaping.rst @@ -13,37 +13,12 @@ Reshaping by pivoting DataFrame objects .. image:: ../_static/reshaping_pivot.png -.. ipython:: python - :suppress: - - import pandas._testing as tm - - def unpivot(frame): - N, K = frame.shape - data = { - "value": frame.to_numpy().ravel("F"), - "variable": np.asarray(frame.columns).repeat(N), - "date": np.tile(np.asarray(frame.index), K), - } - columns = ["date", "variable", "value"] - return pd.DataFrame(data, columns=columns) - - df = unpivot(tm.makeTimeDataFrame(3)) - Data is often stored in so-called "stacked" or "record" format: .. ipython:: python - df - - -For the curious here is how the above ``DataFrame`` was created: - -.. code-block:: python - import pandas._testing as tm - def unpivot(frame): N, K = frame.shape data = { @@ -53,14 +28,15 @@ For the curious here is how the above ``DataFrame`` was created: } return pd.DataFrame(data, columns=["date", "variable", "value"]) - df = unpivot(tm.makeTimeDataFrame(3)) + df To select out everything for variable ``A`` we could do: .. ipython:: python - df[df["variable"] == "A"] + filtered = df[df["variable"] == "A"] + filtered But suppose we wish to do time series operations with the variables. A better representation would be where the ``columns`` are the unique variables and an @@ -70,11 +46,12 @@ top level function :func:`~pandas.pivot`): .. ipython:: python - df.pivot(index="date", columns="variable", values="value") + pivoted = df.pivot(index="date", columns="variable", values="value") + pivoted -If the ``values`` argument is omitted, and the input ``DataFrame`` has more than -one column of values which are not used as column or index inputs to ``pivot``, -then the resulting "pivoted" ``DataFrame`` will have :ref:`hierarchical columns +If the ``values`` argument is omitted, and the input :class:`DataFrame` has more than +one column of values which are not used as column or index inputs to :meth:`~DataFrame.pivot`, +then the resulting "pivoted" :class:`DataFrame` will have :ref:`hierarchical columns <advanced.hierarchical>` whose topmost level indicates the respective value column: @@ -84,7 +61,7 @@ column: pivoted = df.pivot(index="date", columns="variable") pivoted -You can then select subsets from the pivoted ``DataFrame``: +You can then select subsets from the pivoted :class:`DataFrame`: .. ipython:: python @@ -108,16 +85,16 @@ Reshaping by stacking and unstacking Closely related to the :meth:`~DataFrame.pivot` method are the related :meth:`~DataFrame.stack` and :meth:`~DataFrame.unstack` methods available on -``Series`` and ``DataFrame``. These methods are designed to work together with -``MultiIndex`` objects (see the section on :ref:`hierarchical indexing +:class:`Series` and :class:`DataFrame`. These methods are designed to work together with +:class:`MultiIndex` objects (see the section on :ref:`hierarchical indexing <advanced.hierarchical>`). Here are essentially what these methods do: -* ``stack``: "pivot" a level of the (possibly hierarchical) column labels, - returning a ``DataFrame`` with an index with a new inner-most level of row +* :meth:`~DataFrame.stack`: "pivot" a level of the (possibly hierarchical) column labels, + returning a :class:`DataFrame` with an index with a new inner-most level of row labels. -* ``unstack``: (inverse operation of ``stack``) "pivot" a level of the +* :meth:`~DataFrame.unstack`: (inverse operation of :meth:`~DataFrame.stack`) "pivot" a level of the (possibly hierarchical) row index to the column axis, producing a reshaped - ``DataFrame`` with a new inner-most level of column labels. + :class:`DataFrame` with a new inner-most level of column labels. .. image:: ../_static/reshaping_unstack.png @@ -139,22 +116,22 @@ from the hierarchical indexing section: df2 = df[:4] df2 -The ``stack`` function "compresses" a level in the ``DataFrame``'s columns to +The :meth:`~DataFrame.stack` function "compresses" a level in the :class:`DataFrame` columns to produce either: -* A ``Series``, in the case of a simple column Index. -* A ``DataFrame``, in the case of a ``MultiIndex`` in the columns. +* A :class:`Series`, in the case of a simple column Index. +* A :class:`DataFrame`, in the case of a :class:`MultiIndex` in the columns. -If the columns have a ``MultiIndex``, you can choose which level to stack. The -stacked level becomes the new lowest level in a ``MultiIndex`` on the columns: +If the columns have a :class:`MultiIndex`, you can choose which level to stack. The +stacked level becomes the new lowest level in a :class:`MultiIndex` on the columns: .. ipython:: python stacked = df2.stack() stacked -With a "stacked" ``DataFrame`` or ``Series`` (having a ``MultiIndex`` as the -``index``), the inverse operation of ``stack`` is ``unstack``, which by default +With a "stacked" :class:`DataFrame` or :class:`Series` (having a :class:`MultiIndex` as the +``index``), the inverse operation of :meth:`~DataFrame.stack` is :meth:`~DataFrame.unstack`, which by default unstacks the **last level**: .. ipython:: python @@ -177,9 +154,9 @@ the level numbers: .. image:: ../_static/reshaping_unstack_0.png -Notice that the ``stack`` and ``unstack`` methods implicitly sort the index -levels involved. Hence a call to ``stack`` and then ``unstack``, or vice versa, -will result in a **sorted** copy of the original ``DataFrame`` or ``Series``: +Notice that the :meth:`~DataFrame.stack` and :meth:`~DataFrame.unstack` methods implicitly sort the index +levels involved. Hence a call to :meth:`~DataFrame.stack` and then :meth:`~DataFrame.unstack`, or vice versa, +will result in a **sorted** copy of the original :class:`DataFrame` or :class:`Series`: .. ipython:: python @@ -188,7 +165,7 @@ will result in a **sorted** copy of the original ``DataFrame`` or ``Series``: df all(df.unstack().stack() == df.sort_index()) -The above code will raise a ``TypeError`` if the call to ``sort_index`` is +The above code will raise a ``TypeError`` if the call to :meth:`~DataFrame.sort_index` is removed. .. _reshaping.stack_multiple: @@ -231,7 +208,7 @@ Missing data These functions are intelligent about handling missing data and do not expect each subgroup within the hierarchical index to have the same set of labels. They also can handle the index being unsorted (but you can make it sorted by -calling ``sort_index``, of course). Here is a more complex example: +calling :meth:`~DataFrame.sort_index`, of course). Here is a more complex example: .. ipython:: python @@ -251,7 +228,7 @@ calling ``sort_index``, of course). Here is a more complex example: df2 = df.iloc[[0, 1, 2, 4, 5, 7]] df2 -As mentioned above, ``stack`` can be called with a ``level`` argument to select +As mentioned above, :meth:`~DataFrame.stack` can be called with a ``level`` argument to select which level in the columns to stack: .. ipython:: python @@ -281,7 +258,7 @@ the value of missing data. With a MultiIndex ~~~~~~~~~~~~~~~~~ -Unstacking when the columns are a ``MultiIndex`` is also careful about doing +Unstacking when the columns are a :class:`MultiIndex` is also careful about doing the right thing: .. ipython:: python @@ -297,7 +274,7 @@ Reshaping by melt .. image:: ../_static/reshaping_melt.png The top-level :func:`~pandas.melt` function and the corresponding :meth:`DataFrame.melt` -are useful to massage a ``DataFrame`` into a format where one or more columns +are useful to massage a :class:`DataFrame` into a format where one or more columns are *identifier variables*, while all other columns, considered *measured variables*, are "unpivoted" to the row axis, leaving just two non-identifier columns, "variable" and "value". The names of those columns can be customized @@ -363,7 +340,7 @@ user-friendly. Combining with stats and GroupBy -------------------------------- -It should be no shock that combining ``pivot`` / ``stack`` / ``unstack`` with +It should be no shock that combining :meth:`~DataFrame.pivot` / :meth:`~DataFrame.stack` / :meth:`~DataFrame.unstack` with GroupBy and the basic Series and DataFrame statistical functions can produce some very expressive and fast data manipulations. @@ -385,8 +362,6 @@ Pivot tables .. _reshaping.pivot: - - While :meth:`~DataFrame.pivot` provides general purpose pivoting with various data types (strings, numerics, etc.), pandas also provides :func:`~pandas.pivot_table` for pivoting with aggregation of numeric data. @@ -437,7 +412,7 @@ We can produce pivot tables from this data very easily: aggfunc=np.sum, ) -The result object is a ``DataFrame`` having potentially hierarchical indexes on the +The result object is a :class:`DataFrame` having potentially hierarchical indexes on the rows and columns. If the ``values`` column name is not given, the pivot table will include all of the data that can be aggregated in an additional level of hierarchy in the columns: @@ -446,21 +421,21 @@ hierarchy in the columns: pd.pivot_table(df, index=["A", "B"], columns=["C"]) -Also, you can use ``Grouper`` for ``index`` and ``columns`` keywords. For detail of ``Grouper``, see :ref:`Grouping with a Grouper specification <groupby.specify>`. +Also, you can use :class:`Grouper` for ``index`` and ``columns`` keywords. For detail of :class:`Grouper`, see :ref:`Grouping with a Grouper specification <groupby.specify>`. .. ipython:: python pd.pivot_table(df, values="D", index=pd.Grouper(freq="M", key="F"), columns="C") You can render a nice output of the table omitting the missing values by -calling ``to_string`` if you wish: +calling :meth:`~DataFrame.to_string` if you wish: .. ipython:: python table = pd.pivot_table(df, index=["A", "B"], columns=["C"]) print(table.to_string(na_rep="")) -Note that ``pivot_table`` is also available as an instance method on DataFrame, +Note that :meth:`~DataFrame.pivot_table` is also available as an instance method on DataFrame, i.e. :meth:`DataFrame.pivot_table`. .. _reshaping.pivot.margins: @@ -468,7 +443,7 @@ Note that ``pivot_table`` is also available as an instance method on DataFrame, Adding margins ~~~~~~~~~~~~~~ -If you pass ``margins=True`` to ``pivot_table``, special ``All`` columns and +If you pass ``margins=True`` to :meth:`~DataFrame.pivot_table`, special ``All`` columns and rows will be added with partial group aggregates across the categories on the rows and columns: @@ -490,7 +465,7 @@ Cross tabulations ----------------- Use :func:`~pandas.crosstab` to compute a cross-tabulation of two (or more) -factors. By default ``crosstab`` computes a frequency table of the factors +factors. By default :func:`~pandas.crosstab` computes a frequency table of the factors unless an array of values and an aggregation function are passed. It takes a number of arguments @@ -509,7 +484,7 @@ It takes a number of arguments Normalize by dividing all values by the sum of values. -Any ``Series`` passed will have their name attributes used unless row or column +Any :class:`Series` passed will have their name attributes used unless row or column names for the cross-tabulation are specified For example: @@ -523,7 +498,7 @@ For example: pd.crosstab(a, [b, c], rownames=["a"], colnames=["b", "c"]) -If ``crosstab`` receives only two Series, it will provide a frequency table. +If :func:`~pandas.crosstab` receives only two Series, it will provide a frequency table. .. ipython:: python @@ -534,8 +509,8 @@ If ``crosstab`` receives only two Series, it will provide a frequency table. pd.crosstab(df["A"], df["B"]) -``crosstab`` can also be implemented -to ``Categorical`` data. +:func:`~pandas.crosstab` can also be implemented +to :class:`Categorical` data. .. ipython:: python @@ -568,9 +543,9 @@ using the ``normalize`` argument: pd.crosstab(df["A"], df["B"], normalize="columns") -``crosstab`` can also be passed a third ``Series`` and an aggregation function -(``aggfunc``) that will be applied to the values of the third ``Series`` within -each group defined by the first two ``Series``: +:func:`~pandas.crosstab` can also be passed a third :class:`Series` and an aggregation function +(``aggfunc``) that will be applied to the values of the third :class:`Series` within +each group defined by the first two :class:`Series`: .. ipython:: python @@ -611,7 +586,7 @@ Alternatively we can specify custom bin-edges: c = pd.cut(ages, bins=[0, 18, 35, 70]) c -If the ``bins`` keyword is an ``IntervalIndex``, then these will be +If the ``bins`` keyword is an :class:`IntervalIndex`, then these will be used to bin the passed data.:: pd.cut([25, 20, 50], bins=c.categories) @@ -622,9 +597,9 @@ used to bin the passed data.:: Computing indicator / dummy variables ------------------------------------- -To convert a categorical variable into a "dummy" or "indicator" ``DataFrame``, -for example a column in a ``DataFrame`` (a ``Series``) which has ``k`` distinct -values, can derive a ``DataFrame`` containing ``k`` columns of 1s and 0s using +To convert a categorical variable into a "dummy" or "indicator" :class:`DataFrame`, +for example a column in a :class:`DataFrame` (a :class:`Series`) which has ``k`` distinct +values, can derive a :class:`DataFrame` containing ``k`` columns of 1s and 0s using :func:`~pandas.get_dummies`: .. ipython:: python @@ -634,7 +609,7 @@ values, can derive a ``DataFrame`` containing ``k`` columns of 1s and 0s using pd.get_dummies(df["key"]) Sometimes it's useful to prefix the column names, for example when merging the result -with the original ``DataFrame``: +with the original :class:`DataFrame`: .. ipython:: python @@ -643,7 +618,7 @@ with the original ``DataFrame``: df[["data1"]].join(dummies) -This function is often used along with discretization functions like ``cut``: +This function is often used along with discretization functions like :func:`~pandas.cut`: .. ipython:: python @@ -656,7 +631,7 @@ This function is often used along with discretization functions like ``cut``: See also :func:`Series.str.get_dummies <pandas.Series.str.get_dummies>`. -:func:`get_dummies` also accepts a ``DataFrame``. By default all categorical +:func:`get_dummies` also accepts a :class:`DataFrame`. By default all categorical variables (categorical in the statistical sense, those with ``object`` or ``categorical`` dtype) are encoded as dummy variables. @@ -677,8 +652,8 @@ Notice that the ``B`` column is still included in the output, it just hasn't been encoded. You can drop ``B`` before calling ``get_dummies`` if you don't want to include it in the output. -As with the ``Series`` version, you can pass values for the ``prefix`` and -``prefix_sep``. By default the column name is used as the prefix, and '_' as +As with the :class:`Series` version, you can pass values for the ``prefix`` and +``prefix_sep``. By default the column name is used as the prefix, and ``_`` as the prefix separator. You can specify ``prefix`` and ``prefix_sep`` in 3 ways: * string: Use the same value for ``prefix`` or ``prefix_sep`` for each column @@ -742,7 +717,7 @@ To encode 1-d values as an enumerated type use :func:`~pandas.factorize`: labels uniques -Note that ``factorize`` is similar to ``numpy.unique``, but differs in its +Note that :func:`~pandas.factorize` is similar to ``numpy.unique``, but differs in its handling of NaN: .. note:: @@ -750,16 +725,12 @@ handling of NaN: because of an ordering bug. See also `here <https://github.com/numpy/numpy/issues/641>`__. -.. code-block:: ipython - - In [1]: x = pd.Series(['A', 'A', np.nan, 'B', 3.14, np.inf]) - In [2]: pd.factorize(x, sort=True) - Out[2]: - (array([ 2, 2, -1, 3, 0, 1]), - Index([3.14, inf, 'A', 'B'], dtype='object')) +.. ipython:: python + :okexcept: - In [3]: np.unique(x, return_inverse=True)[::-1] - Out[3]: (array([3, 3, 0, 4, 1, 2]), array([nan, 3.14, inf, 'A', 'B'], dtype=object)) + ser = pd.Series(['A', 'A', np.nan, 'B', 3.14, np.inf]) + pd.factorize(ser, sort=True) + np.unique(ser, return_inverse=True)[::-1] .. note:: If you just want to handle one column as a categorical variable (like R's factor), @@ -907,13 +878,13 @@ We can 'explode' the ``values`` column, transforming each list-like to a separat df["values"].explode() -You can also explode the column in the ``DataFrame``. +You can also explode the column in the :class:`DataFrame`. .. ipython:: python df.explode("values") -:meth:`Series.explode` will replace empty lists with ``np.nan`` and preserve scalar entries. The dtype of the resulting ``Series`` is always ``object``. +:meth:`Series.explode` will replace empty lists with ``np.nan`` and preserve scalar entries. The dtype of the resulting :class:`Series` is always ``object``. .. ipython:: python diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 157404305c5d9..36eabe93dbd7e 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -631,6 +631,10 @@ def factorize( cut : Discretize continuous-valued array. unique : Find the unique value in an array. + Notes + ----- + Reference :ref:`the user guide <reshaping.factorize>` for more examples. + Examples -------- These examples all show factorize as a top-level method like diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 1f43f34d0e58a..512d85de333ad 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -7780,6 +7780,8 @@ def groupby( For finer-tuned control, see hierarchical indexing documentation along with the related stack/unstack methods. + Reference :ref:`the user guide <reshaping.pivot>` for more examples. + Examples -------- >>> df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two', @@ -7938,6 +7940,10 @@ def pivot(self, index=None, columns=None, values=None) -> DataFrame: wide_to_long : Wide panel to long format. Less flexible but more user-friendly than melt. + Notes + ----- + Reference :ref:`the user guide <reshaping.pivot>` for more examples. + Examples -------- >>> df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo", @@ -8094,6 +8100,8 @@ def stack(self, level: Level = -1, dropna: bool = True): vertically on top of each other (in the index of the dataframe). + Reference :ref:`the user guide <reshaping.stacking>` for more examples. + Examples -------- **Single level columns** @@ -8273,6 +8281,8 @@ def explode( result in a np.nan for that row. In addition, the ordering of rows in the output will be non-deterministic when exploding sets. + Reference :ref:`the user guide <reshaping.explode>` for more examples. + Examples -------- >>> df = pd.DataFrame({'A': [[0, 1, 2], 'foo', [], [3, 4]], @@ -8372,6 +8382,10 @@ def unstack(self, level: Level = -1, fill_value=None): DataFrame.stack : Pivot a level of the column labels (inverse operation from `unstack`). + Notes + ----- + Reference :ref:`the user guide <reshaping.stacking>` for more examples. + Examples -------- >>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'), diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 069f0e5003cdf..b428155e722ff 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -589,6 +589,8 @@ def crosstab( In the event that there aren't overlapping indexes an empty DataFrame will be returned. + Reference :ref:`the user guide <reshaping.crosstabulations>` for more examples. + Examples -------- >>> a = np.array(["foo", "foo", "foo", "foo", "bar", "bar", diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 75f005489785a..7f67d3408ae6c 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -857,6 +857,10 @@ def get_dummies( -------- Series.str.get_dummies : Convert Series to dummy codes. + Notes + ----- + Reference :ref:`the user guide <reshaping.dummies>` for more examples. + Examples -------- >>> s = pd.Series(list('abca')) diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index 8cf94e5e433a6..d8c4f3f3da765 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -145,6 +145,8 @@ def cut( Any NA values will be NA in the result. Out of bounds values will be NA in the resulting Series or Categorical object. + Reference :ref:`the user guide <reshaping.tile.cut>` for more examples. + Examples -------- Discretize into three equal-sized bins. diff --git a/pandas/core/series.py b/pandas/core/series.py index 765d4ab86dd6e..ac892573ae08b 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4078,6 +4078,8 @@ def explode(self, ignore_index: bool = False) -> Series: result in a np.nan for that row. In addition, the ordering of elements in the output will be non-deterministic when exploding sets. + Reference :ref:`the user guide <reshaping.explode>` for more examples. + Examples -------- >>> s = pd.Series([[1, 2, 3], 'foo', [], [3, 4]]) @@ -4127,6 +4129,10 @@ def unstack(self, level=-1, fill_value=None) -> DataFrame: DataFrame Unstacked Series. + Notes + ----- + Reference :ref:`the user guide <reshaping.stacking>` for more examples. + Examples -------- >>> s = pd.Series([1, 2, 3, 4], diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py index 3547b75eac807..35ee1c7a4ddbb 100644 --- a/pandas/core/shared_docs.py +++ b/pandas/core/shared_docs.py @@ -195,6 +195,10 @@ DataFrame.explode : Explode a DataFrame from list-like columns to long format. +Notes +----- +Reference :ref:`the user guide <reshaping.melt>` for more examples. + Examples -------- >>> df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'},
Backport PR #45612: DOC: Improve reshaping.rst
https://api.github.com/repos/pandas-dev/pandas/pulls/45669
2022-01-28T00:34:46Z
2022-01-28T03:00:50Z
2022-01-28T03:00:50Z
2022-01-28T03:00:50Z
BUG: unnecessary FutureWarning in sort_values
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 10b605f6ef43e..9e4b3479341b3 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -28,6 +28,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ - Fixed segfault in :meth:``DataFrame.to_json`` when dumping tz-aware datetimes in Python 3.10 (:issue:`42130`) +- Stopped emitting unnecessary ``FutureWarning`` in :meth:`DataFrame.sort_values` with sparse columns (:issue:`45618`) - Fixed window aggregations in :meth:`DataFrame.rolling` and :meth:`Series.rolling` to skip over unused elements (:issue:`45647`) - diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index ac306b1687381..7ab53ccf7cb8d 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -10,6 +10,7 @@ Iterable, Sequence, ) +import warnings import numpy as np @@ -320,7 +321,12 @@ def lexsort_indexer( keys = [ensure_key_mapped(k, key) for k in keys] for k, order in zip(keys, orders): - cat = Categorical(k, ordered=True) + with warnings.catch_warnings(): + # TODO(2.0): unnecessary once deprecation is enforced + # GH#45618 don't issue warning user can't do anything about + warnings.filterwarnings("ignore", ".*SparseArray.*", category=FutureWarning) + + cat = Categorical(k, ordered=True) if na_position not in ["last", "first"]: raise ValueError(f"invalid na_position: {na_position}") diff --git a/pandas/tests/extension/test_sparse.py b/pandas/tests/extension/test_sparse.py index 37acbb4e92dfb..14f50ecb5fb22 100644 --- a/pandas/tests/extension/test_sparse.py +++ b/pandas/tests/extension/test_sparse.py @@ -293,14 +293,6 @@ def test_fillna_frame(self, data_missing): class TestMethods(BaseSparseTests, base.BaseMethodsTests): - @pytest.mark.parametrize("ascending", [True, False]) - def test_sort_values_frame(self, data_for_sorting, ascending): - msg = "will store that array directly" - with tm.assert_produces_warning( - FutureWarning, match=msg, check_stacklevel=False - ): - super().test_sort_values_frame(data_for_sorting, ascending) - def test_combine_le(self, data_repeated): # We return a Series[SparseArray].__le__ returns a # Series[Sparse[bool]] diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py index 0a05712489147..9f3fcb1db546d 100644 --- a/pandas/tests/frame/methods/test_sort_values.py +++ b/pandas/tests/frame/methods/test_sort_values.py @@ -15,6 +15,16 @@ class TestDataFrameSortValues: + def test_sort_values_sparse_no_warning(self): + # GH#45618 + # TODO(2.0): test will be unnecessary + ser = pd.Series(Categorical(["a", "b", "a"], categories=["a", "b", "c"])) + df = pd.get_dummies(ser, sparse=True) + + with tm.assert_produces_warning(None): + # No warnings about constructing Index from SparseArray + df.sort_values(by=df.columns.tolist()) + def test_sort_values(self): frame = DataFrame( [[1, 1, 2], [3, 1, 0], [4, 5, 6]], index=[1, 2, 3], columns=list("ABC")
- [x] closes #45618 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45668
2022-01-28T00:30:29Z
2022-01-30T23:49:43Z
2022-01-30T23:49:42Z
2022-01-31T00:09:47Z
TST: Dynamically use doctest_namespace only if running the doctest
diff --git a/pandas/conftest.py b/pandas/conftest.py index e61d9ee18cadb..952177f342c46 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -115,6 +115,12 @@ def pytest_collection_modifyitems(items, config): ] for item in items: + if config.getoption("--doctest-modules") or config.getoption( + "--doctest-cython", default=False + ): + # autouse=True for the add_doctest_imports can lead to expensive teardowns + # since doctest_namespace is a session fixture + item.add_marker(pytest.mark.usefixtures("add_doctest_imports")) # mark all tests in the pandas/tests/frame directory with "arraymanager" if "/frame/" in item.nodeid: item.add_marker(pytest.mark.arraymanager) @@ -187,6 +193,15 @@ def pytest_collection_modifyitems(items, config): ) +@pytest.fixture +def add_doctest_imports(doctest_namespace): + """ + Make `np` and `pd` names available for doctests. + """ + doctest_namespace["np"] = np + doctest_namespace["pd"] = pd + + # ---------------------------------------------------------------- # Autouse fixtures # ---------------------------------------------------------------- @@ -198,15 +213,6 @@ def configure_tests(): pd.set_option("chained_assignment", "raise") -@pytest.fixture(autouse=True) -def add_imports(doctest_namespace): - """ - Make `np` and `pd` names available for doctests. - """ - doctest_namespace["np"] = np - doctest_namespace["pd"] = pd - - # ---------------------------------------------------------------- # Common arguments # ----------------------------------------------------------------
- [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them Will probably speed up the test suite. Example locally with running `pandas/tests/window/moments` Main ``` ======================================================================= slowest 30 durations ======================================================================= 0.07s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data4-True-False-0] 0.06s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_std[all_data9-False-False-2-False] 0.06s teardown pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data4-False-True-2] 0.05s teardown pandas/tests/window/moments/test_moments_consistency_rolling.py::test_rolling_consistency_var_debiasing_factors[all_data17-rolling_consistency_cases1-False] 0.03s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data3-False-False-2] 0.03s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data6-False-False-0] 0.03s setup pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data3-False-True-0] 0.03s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data11-False-False-2] 0.03s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data3-False-False-0] 0.03s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data5-False-False-2] 0.03s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data7-True-True-0] 0.03s setup pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data5-True-False-2] 0.03s setup pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data6-False-False-0] 0.03s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data11-False-False-0] 0.02s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data6-True-True-2] 0.02s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data9-True-False-0] 0.02s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data11-True-True-0] 0.02s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data7-True-False-0] 0.02s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data3-False-True-0] 0.02s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data9-False-True-0] 0.02s setup pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data9-False-False-0] 0.02s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data8-True-True-0] 0.02s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data12-True-False-0] 0.02s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data9-True-False-2] 0.02s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data10-True-False-0] 0.02s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data8-False-False-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data8-False-False-2] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data10-False-False-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data5-True-True-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data10-True-True-0] ``` This PR ``` ======================================== slowest 30 durations ======================================================================= 0.01s call pandas/tests/window/moments/test_moments_consistency_expanding.py::test_expanding_consistency_var_std_cov[all_data13-2-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_expanding.py::test_expanding_consistency_var_std_cov[all_data11-2-1] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_var_debiasing_factors[all_data9-True-True-2] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_series_cov_corr[series_data6-True-False-2-True] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_var_debiasing_factors[all_data9-False-False-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_expanding.py::test_expanding_consistency_var_std_cov[all_data16-2-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_rolling.py::test_rolling_consistency_series_cov_corr[series_data1-rolling_consistency_cases1-True-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_rolling.py::test_rolling_consistency_series_cov_corr[series_data5-rolling_consistency_cases0-True-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_rolling.py::test_rolling_consistency_series_cov_corr[series_data3-rolling_consistency_cases0-False-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_var_debiasing_factors[all_data12-False-True-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_series_cov_corr[series_data7-False-True-2-True] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_series_cov_corr[series_data2-False-True-0-True] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_series_cov_corr[series_data4-False-True-2-True] 0.01s call pandas/tests/window/moments/test_moments_consistency_rolling.py::test_rolling_consistency_var_std_cov[all_data17-rolling_consistency_cases1-True-1] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_mean[all_data4-False-False-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_series_cov_corr[series_data5-False-True-0-True] 0.01s call pandas/tests/window/moments/test_moments_consistency_rolling.py::test_rolling_consistency_var_std_cov[all_data9-rolling_consistency_cases0-True-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_series_cov_corr[series_data6-False-False-0-True] 0.01s call pandas/tests/window/moments/test_moments_consistency_expanding.py::test_expanding_consistency_var_std_cov[all_data14-2-1] 0.01s call pandas/tests/window/moments/test_moments_consistency_rolling.py::test_rolling_consistency_var_debiasing_factors[all_data9-rolling_consistency_cases1-True] 0.01s call pandas/tests/window/moments/test_moments_consistency_rolling.py::test_rolling_consistency_series_cov_corr[series_data6-rolling_consistency_cases1-False-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_var_debiasing_factors[all_data13-True-False-2] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_std[all_data14-False-True-0-False] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_std[all_data16-True-False-2-True] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_series_cov_corr[series_data5-True-True-0-False] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_std[all_data9-False-True-0-False] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_moments_consistency_var_constant[consistent_data3-True-True-0-False] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_std[all_data9-True-True-0-False] 0.01s call pandas/tests/window/moments/test_moments_consistency_expanding.py::test_expanding_consistency_var_std_cov[all_data6-2-0] 0.01s call pandas/tests/window/moments/test_moments_consistency_ewm.py::test_ewm_consistency_var_debiasing_factors[all_data10-False-True-2] ```
https://api.github.com/repos/pandas-dev/pandas/pulls/45667
2022-01-28T00:11:05Z
2022-01-28T22:09:38Z
2022-01-28T22:09:38Z
2022-01-28T22:29:07Z
Backport PR #45642 on branch 1.4.x (REGR: Series.fillna(downcast=False))
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 1bd8da2d2b03c..21aab5058d25b 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -15,6 +15,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Regression in :meth:`Series.mask` with ``inplace=True`` and ``PeriodDtype`` and an incompatible ``other`` coercing to a common dtype instead of raising (:issue:`45546`) +- Regression in :meth:`Series.fillna` with ``downcast=False`` incorrectly downcasting ``object`` dtype (:issue:`45603`) - Regression in :meth:`DataFrame.loc.__setitem__` losing :class:`Index` name if :class:`DataFrame` was empty before (:issue:`45621`) - diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 1bc27c80ef58e..5810f3515c4ae 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -528,6 +528,8 @@ def split_and_operate(self, func, *args, **kwargs) -> list[Block]: @final def _maybe_downcast(self, blocks: list[Block], downcast=None) -> list[Block]: + if downcast is False: + return blocks if self.dtype == _dtype_obj: # GH#44241 We downcast regardless of the argument; @@ -541,10 +543,6 @@ def _maybe_downcast(self, blocks: list[Block], downcast=None) -> list[Block]: if downcast is None: return blocks - if downcast is False: - # turn if off completely - # TODO: not reached, deprecate in favor of downcast=None - return blocks return extend_blocks([b._downcast_2d(downcast) for b in blocks]) diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index b5bdf6a70199c..21a45d9ee1f20 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -244,6 +244,12 @@ def test_fillna_downcast(self): expected = DataFrame({"a": [1, 0]}) tm.assert_frame_equal(result, expected) + def test_fillna_downcast_false(self, frame_or_series): + # GH#45603 preserve object dtype with downcast=False + obj = frame_or_series([1, 2, 3], dtype="object") + result = obj.fillna("", downcast=False) + tm.assert_equal(result, obj) + @pytest.mark.parametrize("columns", [["A", "A", "B"], ["A", "A"]]) def test_fillna_dictlike_value_duplicate_colnames(self, columns): # GH#43476
Backport PR #45642: REGR: Series.fillna(downcast=False)
https://api.github.com/repos/pandas-dev/pandas/pulls/45666
2022-01-27T22:24:59Z
2022-01-28T00:26:33Z
2022-01-28T00:26:33Z
2022-01-28T00:26:34Z
CI/TST: Skip external s3 bucket test that hangs on min build
diff --git a/pandas/tests/io/xml/test_xml.py b/pandas/tests/io/xml/test_xml.py index 8809c423a29ba..aef94af60c3dd 100644 --- a/pandas/tests/io/xml/test_xml.py +++ b/pandas/tests/io/xml/test_xml.py @@ -1102,6 +1102,10 @@ def test_unsuported_compression(datapath, parser): @tm.network @td.skip_if_no("s3fs") @td.skip_if_no("lxml") +@pytest.mark.skipif( + os.environ.get("PANDAS_CI", "0") == "1", + reason="2022.1.17: Hanging on the CI min versions build.", +) def test_s3_parser_consistency(): # Python Software Foundation (2019 IRS-990 RETURN) s3 = "s3://irs-form-990/201923199349319487_public.xml"
null
https://api.github.com/repos/pandas-dev/pandas/pulls/45665
2022-01-27T22:22:44Z
2022-01-28T06:41:11Z
2022-01-28T06:41:11Z
2022-01-28T06:41:15Z
CLN: suppress distutils warnings, assorted
diff --git a/pandas/core/array_algos/putmask.py b/pandas/core/array_algos/putmask.py index daf7d0bd3f213..1082f8d71af01 100644 --- a/pandas/core/array_algos/putmask.py +++ b/pandas/core/array_algos/putmask.py @@ -12,6 +12,7 @@ ArrayLike, npt, ) +from pandas.compat import np_version_under1p20 from pandas.core.dtypes.cast import ( can_hold_element, @@ -126,7 +127,8 @@ def putmask_without_repeat( mask : np.ndarray[bool] new : Any """ - new = setitem_datetimelike_compat(values, mask.sum(), new) + if np_version_under1p20: + new = setitem_datetimelike_compat(values, mask.sum(), new) if getattr(new, "ndim", 0) >= 1: new = new.astype(values.dtype, copy=False) diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index a40be5a988f26..3446d5fc43a65 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -180,7 +180,7 @@ def _values_for_argsort(self) -> np.ndarray: def argmin(self, axis: int = 0, skipna: bool = True): # type:ignore[override] # override base class by adding axis keyword validate_bool_kwarg(skipna, "skipna") - if not skipna and self.isna().any(): + if not skipna and self._hasna: raise NotImplementedError return nargminmax(self, "argmin", axis=axis) @@ -188,7 +188,7 @@ def argmin(self, axis: int = 0, skipna: bool = True): # type:ignore[override] def argmax(self, axis: int = 0, skipna: bool = True): # type:ignore[override] # override base class by adding axis keyword validate_bool_kwarg(skipna, "skipna") - if not skipna and self.isna().any(): + if not skipna and self._hasna: raise NotImplementedError return nargminmax(self, "argmax", axis=axis) diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 87acadc01faad..9c262fa37d760 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -2289,7 +2289,6 @@ def maybe_convert_dtype(data, copy: bool): copy = False elif is_extension_array_dtype(data.dtype) and not is_datetime64tz_dtype(data.dtype): - # Includes categorical # TODO: We have no tests for these data = np.array(data, dtype=np.object_) copy = False diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 3d4f53530b89c..accacbf464434 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -367,14 +367,16 @@ def iget(self, i: int | tuple[int, int] | tuple[slice, int]): # "Union[int, integer[Any]]" return self.values[i] # type: ignore[index] - def set_inplace(self, locs, values) -> None: + def set_inplace(self, locs, values: ArrayLike) -> None: """ Modify block values in-place with new item value. Notes ----- - `set` never creates a new array or new Block, whereas `setitem` _may_ - create a new array and always creates a new Block. + `set_inplace` never creates a new array or new Block, whereas `setitem` + _may_ create a new array and always creates a new Block. + + Caller is responsible for checking values.dtype == self.dtype. """ self.values[locs] = values @@ -1183,7 +1185,7 @@ def where(self, other, cond) -> list[Block]: icond, noop = validate_putmask(values, ~cond) if noop: # GH-39595: Always return a copy; short-circuit up/downcasting - return self.copy() + return [self.copy()] if other is lib.no_default: other = self.fill_value @@ -1375,7 +1377,8 @@ def setitem(self, indexer, value): values = self.values if values.ndim == 2: - # TODO: string[pyarrow] tests break if we transpose unconditionally + # TODO(GH#45419): string[pyarrow] tests break if we transpose + # unconditionally values = values.T check_setitem_lengths(indexer, value, values) values[indexer] = value @@ -1396,7 +1399,7 @@ def where(self, other, cond) -> list[Block]: if noop: # GH#44181, GH#45135 # Avoid a) raising for Interval/PeriodDtype and b) unnecessary object upcast - return self.copy() + return [self.copy()] try: res_values = arr._where(cond, other).T @@ -1597,12 +1600,16 @@ def iget(self, i: int | tuple[int, int] | tuple[slice, int]): raise IndexError(f"{self} only contains one item") return self.values - def set_inplace(self, locs, values) -> None: + def set_inplace(self, locs, values: ArrayLike) -> None: # NB: This is a misnomer, is supposed to be inplace but is not, # see GH#33457 # When an ndarray, we should have locs.tolist() == [0] # When a BlockPlacement we should have list(locs) == [0] - self.values = values + + # error: Incompatible types in assignment (expression has type + # "Union[ExtensionArray, ndarray[Any, Any]]", variable has type + # "ExtensionArray") + self.values = values # type: ignore[assignment] try: # TODO(GH33457) this can be removed self._cache.clear() diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 94b1f5d2717a4..bf74e11ae247a 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -797,7 +797,7 @@ def _is_datetime(x): def should_warn(*args): - not_mono = not any(map(operator.attrgetter("is_monotonic"), args)) + not_mono = not any(map(operator.attrgetter("is_monotonic_increasing"), args)) only_one_dt = reduce(operator.xor, map(_is_datetime, args)) return not_mono and only_one_dt diff --git a/pandas/tests/io/parser/test_unsupported.py b/pandas/tests/io/parser/test_unsupported.py index e223378b600e0..67f155817582c 100644 --- a/pandas/tests/io/parser/test_unsupported.py +++ b/pandas/tests/io/parser/test_unsupported.py @@ -166,7 +166,7 @@ def test_on_bad_lines_callable_python_only(self, all_parsers): parser.read_csv(sio, on_bad_lines=bad_lines_func) -def test_close_file_handle_on_invalide_usecols(all_parsers): +def test_close_file_handle_on_invalid_usecols(all_parsers): # GH 45384 parser = all_parsers diff --git a/pandas/util/_test_decorators.py b/pandas/util/_test_decorators.py index 33bde4e69b042..78ef335adf948 100644 --- a/pandas/util/_test_decorators.py +++ b/pandas/util/_test_decorators.py @@ -80,6 +80,12 @@ def safe_import(mod_name: str, min_version: str | None = None): message=".*Int64Index.*", ) + warnings.filterwarnings( + "ignore", + category=DeprecationWarning, + message="distutils Version classes are deprecated.*", + ) + try: mod = __import__(mod_name) except ImportError:
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45663
2022-01-27T18:47:30Z
2022-01-29T00:16:13Z
2022-01-29T00:16:13Z
2022-01-29T00:35:18Z
BUG: Fix joining overlapping IntervalIndex objects (GH-45661)
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 1bd8da2d2b03c..d62a1ebdb5eec 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -16,6 +16,7 @@ Fixed regressions ~~~~~~~~~~~~~~~~~ - Regression in :meth:`Series.mask` with ``inplace=True`` and ``PeriodDtype`` and an incompatible ``other`` coercing to a common dtype instead of raising (:issue:`45546`) - Regression in :meth:`DataFrame.loc.__setitem__` losing :class:`Index` name if :class:`DataFrame` was empty before (:issue:`45621`) +- Regression in :func:`join` with overlapping :class:`IntervalIndex` raising an ``InvalidIndexError`` (:issue:`45661`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index e0bd548eff70a..89617013c45d3 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4580,11 +4580,11 @@ def _join_via_get_indexer( if join_index is self: lindexer = None else: - lindexer = self.get_indexer(join_index) + lindexer = self.get_indexer_for(join_index) if join_index is other: rindexer = None else: - rindexer = other.get_indexer(join_index) + rindexer = other.get_indexer_for(join_index) return join_index, lindexer, rindexer @final diff --git a/pandas/tests/indexes/interval/test_join.py b/pandas/tests/indexes/interval/test_join.py new file mode 100644 index 0000000000000..2f42c530a6686 --- /dev/null +++ b/pandas/tests/indexes/interval/test_join.py @@ -0,0 +1,44 @@ +import pytest + +from pandas import ( + IntervalIndex, + MultiIndex, + RangeIndex, +) +import pandas._testing as tm + + +@pytest.fixture +def range_index(): + return RangeIndex(3, name="range_index") + + +@pytest.fixture +def interval_index(): + return IntervalIndex.from_tuples( + [(0.0, 1.0), (1.0, 2.0), (1.5, 2.5)], name="interval_index" + ) + + +def test_join_overlapping_in_mi_to_same_intervalindex(range_index, interval_index): + # GH-45661 + multi_index = MultiIndex.from_product([interval_index, range_index]) + result = multi_index.join(interval_index) + + tm.assert_index_equal(result, multi_index) + + +def test_join_overlapping_to_multiindex_with_same_interval(range_index, interval_index): + # GH-45661 + multi_index = MultiIndex.from_product([interval_index, range_index]) + result = interval_index.join(multi_index) + + tm.assert_index_equal(result, multi_index) + + +def test_join_overlapping_interval_to_another_intervalindex(interval_index): + # GH-45661 + flipped_interval_index = interval_index[::-1] + result = interval_index.join(flipped_interval_index) + + tm.assert_index_equal(result, interval_index)
Replacing calls to `get_indexer()` with `get_indexer_for()` as `IntervalIndex`es can be unique and overlapping. Similar to #44588 - [x] closes #45661 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45662
2022-01-27T18:36:54Z
2022-01-28T19:00:34Z
2022-01-28T19:00:33Z
2022-02-09T16:19:13Z
BUG: Fix window aggregations to skip over unused elements (GH-45647)
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 1bd8da2d2b03c..c950a71222c6c 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -25,6 +25,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ - Fixed segfault in :meth:``DataFrame.to_json`` when dumping tz-aware datetimes in Python 3.10 (:issue:`42130`) +- Fixed window aggregations in :meth:`DataFrame.rolling` and :meth:`Series.rolling` to skip over unused elements (:issue:`45647`) - .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx index 5ebb60dc7e41b..ff53a577af33f 100644 --- a/pandas/_libs/window/aggregations.pyx +++ b/pandas/_libs/window/aggregations.pyx @@ -122,9 +122,9 @@ def roll_sum(const float64_t[:] values, ndarray[int64_t] start, ndarray[int64_t] end, int64_t minp) -> np.ndarray: cdef: Py_ssize_t i, j - float64_t sum_x = 0, compensation_add = 0, compensation_remove = 0 + float64_t sum_x, compensation_add, compensation_remove int64_t s, e - int64_t nobs = 0, N = len(values) + int64_t nobs = 0, N = len(start) ndarray[float64_t] output bint is_monotonic_increasing_bounds @@ -139,10 +139,12 @@ def roll_sum(const float64_t[:] values, ndarray[int64_t] start, s = start[i] e = end[i] - if i == 0 or not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: # setup + sum_x = compensation_add = compensation_remove = 0 + nobs = 0 for j in range(s, e): add_sum(values[j], &nobs, &sum_x, &compensation_add) @@ -226,9 +228,9 @@ cdef inline void remove_mean(float64_t val, Py_ssize_t *nobs, float64_t *sum_x, def roll_mean(const float64_t[:] values, ndarray[int64_t] start, ndarray[int64_t] end, int64_t minp) -> np.ndarray: cdef: - float64_t val, compensation_add = 0, compensation_remove = 0, sum_x = 0 + float64_t val, compensation_add, compensation_remove, sum_x int64_t s, e - Py_ssize_t nobs = 0, i, j, neg_ct = 0, N = len(values) + Py_ssize_t nobs, i, j, neg_ct, N = len(start) ndarray[float64_t] output bint is_monotonic_increasing_bounds @@ -243,8 +245,10 @@ def roll_mean(const float64_t[:] values, ndarray[int64_t] start, s = start[i] e = end[i] - if i == 0 or not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + compensation_add = compensation_remove = sum_x = 0 + nobs = neg_ct = 0 # setup for j in range(s, e): val = values[j] @@ -349,11 +353,11 @@ def roll_var(const float64_t[:] values, ndarray[int64_t] start, Numerically stable implementation using Welford's method. """ cdef: - float64_t mean_x = 0, ssqdm_x = 0, nobs = 0, compensation_add = 0, - float64_t compensation_remove = 0, + float64_t mean_x, ssqdm_x, nobs, compensation_add, + float64_t compensation_remove, float64_t val, prev, delta, mean_x_old int64_t s, e - Py_ssize_t i, j, N = len(values) + Py_ssize_t i, j, N = len(start) ndarray[float64_t] output bint is_monotonic_increasing_bounds @@ -372,8 +376,9 @@ def roll_var(const float64_t[:] values, ndarray[int64_t] start, # Over the first window, observations can only be added # never removed - if i == 0 or not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + mean_x = ssqdm_x = nobs = compensation_add = compensation_remove = 0 for j in range(s, e): add_var(values[j], &nobs, &mean_x, &ssqdm_x, &compensation_add) @@ -500,11 +505,11 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, cdef: Py_ssize_t i, j float64_t val, prev, min_val, mean_val, sum_val = 0 - float64_t compensation_xxx_add = 0, compensation_xxx_remove = 0 - float64_t compensation_xx_add = 0, compensation_xx_remove = 0 - float64_t compensation_x_add = 0, compensation_x_remove = 0 - float64_t x = 0, xx = 0, xxx = 0 - int64_t nobs = 0, N = len(values), nobs_mean = 0 + float64_t compensation_xxx_add, compensation_xxx_remove + float64_t compensation_xx_add, compensation_xx_remove + float64_t compensation_x_add, compensation_x_remove + float64_t x, xx, xxx + int64_t nobs = 0, N = len(start), V = len(values), nobs_mean = 0 int64_t s, e ndarray[float64_t] output, mean_array, values_copy bint is_monotonic_increasing_bounds @@ -518,7 +523,7 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, values_copy = np.copy(values) with nogil: - for i in range(0, N): + for i in range(0, V): val = values_copy[i] if notnan(val): nobs_mean += 1 @@ -527,7 +532,7 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, # Other cases would lead to imprecision for smallest values if min_val - mean_val > -1e5: mean_val = round(mean_val) - for i in range(0, N): + for i in range(0, V): values_copy[i] = values_copy[i] - mean_val for i in range(0, N): @@ -537,8 +542,13 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, # Over the first window, observations can only be added # never removed - if i == 0 or not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + compensation_xxx_add = compensation_xxx_remove = 0 + compensation_xx_add = compensation_xx_remove = 0 + compensation_x_add = compensation_x_remove = 0 + x = xx = xxx = 0 + nobs = 0 for j in range(s, e): val = values_copy[j] add_skew(val, &nobs, &x, &xx, &xxx, &compensation_x_add, @@ -682,12 +692,12 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, cdef: Py_ssize_t i, j float64_t val, prev, mean_val, min_val, sum_val = 0 - float64_t compensation_xxxx_add = 0, compensation_xxxx_remove = 0 - float64_t compensation_xxx_remove = 0, compensation_xxx_add = 0 - float64_t compensation_xx_remove = 0, compensation_xx_add = 0 - float64_t compensation_x_remove = 0, compensation_x_add = 0 - float64_t x = 0, xx = 0, xxx = 0, xxxx = 0 - int64_t nobs = 0, s, e, N = len(values), nobs_mean = 0 + float64_t compensation_xxxx_add, compensation_xxxx_remove + float64_t compensation_xxx_remove, compensation_xxx_add + float64_t compensation_xx_remove, compensation_xx_add + float64_t compensation_x_remove, compensation_x_add + float64_t x, xx, xxx, xxxx + int64_t nobs, s, e, N = len(start), V = len(values), nobs_mean = 0 ndarray[float64_t] output, values_copy bint is_monotonic_increasing_bounds @@ -700,7 +710,7 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, min_val = np.nanmin(values) with nogil: - for i in range(0, N): + for i in range(0, V): val = values_copy[i] if notnan(val): nobs_mean += 1 @@ -709,7 +719,7 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, # Other cases would lead to imprecision for smallest values if min_val - mean_val > -1e4: mean_val = round(mean_val) - for i in range(0, N): + for i in range(0, V): values_copy[i] = values_copy[i] - mean_val for i in range(0, N): @@ -719,8 +729,14 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, # Over the first window, observations can only be added # never removed - if i == 0 or not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + compensation_xxxx_add = compensation_xxxx_remove = 0 + compensation_xxx_remove = compensation_xxx_add = 0 + compensation_xx_remove = compensation_xx_add = 0 + compensation_x_remove = compensation_x_add = 0 + x = xx = xxx = xxxx = 0 + nobs = 0 for j in range(s, e): add_kurt(values_copy[j], &nobs, &x, &xx, &xxx, &xxxx, &compensation_x_add, &compensation_xx_add, @@ -764,7 +780,7 @@ def roll_median_c(const float64_t[:] values, ndarray[int64_t] start, Py_ssize_t i, j bint err = False, is_monotonic_increasing_bounds int midpoint, ret = 0 - int64_t nobs = 0, N = len(values), s, e, win + int64_t nobs = 0, N = len(start), s, e, win float64_t val, res, prev skiplist_t *sl ndarray[float64_t] output @@ -791,8 +807,12 @@ def roll_median_c(const float64_t[:] values, ndarray[int64_t] start, s = start[i] e = end[i] - if i == 0 or not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + if i != 0: + skiplist_destroy(sl) + sl = skiplist_init(<int>win) + nobs = 0 # setup for j in range(s, e): val = values[j] @@ -948,7 +968,7 @@ cdef _roll_min_max(ndarray[numeric_t] values, cdef: numeric_t ai int64_t curr_win_size, start - Py_ssize_t i, k, nobs = 0, N = len(values) + Py_ssize_t i, k, nobs = 0, N = len(starti) deque Q[int64_t] # min/max always the front deque W[int64_t] # track the whole window for nobs compute ndarray[float64_t, ndim=1] output @@ -1031,7 +1051,7 @@ def roll_quantile(const float64_t[:] values, ndarray[int64_t] start, O(N log(window)) implementation using skip list """ cdef: - Py_ssize_t i, j, s, e, N = len(values), idx + Py_ssize_t i, j, s, e, N = len(start), idx int ret = 0 int64_t nobs = 0, win float64_t val, prev, midpoint, idx_with_fraction @@ -1068,8 +1088,8 @@ def roll_quantile(const float64_t[:] values, ndarray[int64_t] start, s = start[i] e = end[i] - if i == 0 or not is_monotonic_increasing_bounds: - if not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + if i != 0: nobs = 0 skiplist_destroy(skiplist) skiplist = skiplist_init(<int>win) @@ -1160,7 +1180,7 @@ def roll_rank(const float64_t[:] values, ndarray[int64_t] start, derived from roll_quantile """ cdef: - Py_ssize_t i, j, s, e, N = len(values), idx + Py_ssize_t i, j, s, e, N = len(start), idx float64_t rank_min = 0, rank = 0 int64_t nobs = 0, win float64_t val @@ -1193,8 +1213,8 @@ def roll_rank(const float64_t[:] values, ndarray[int64_t] start, s = start[i] e = end[i] - if i == 0 or not is_monotonic_increasing_bounds: - if not is_monotonic_increasing_bounds: + if i == 0 or not is_monotonic_increasing_bounds or s >= end[i - 1]: + if i != 0: nobs = 0 skiplist_destroy(skiplist) skiplist = skiplist_init(<int>win) diff --git a/pandas/tests/window/test_cython_aggregations.py b/pandas/tests/window/test_cython_aggregations.py new file mode 100644 index 0000000000000..c60cb6ea74ec0 --- /dev/null +++ b/pandas/tests/window/test_cython_aggregations.py @@ -0,0 +1,111 @@ +from functools import partial +import sys + +import numpy as np +import pytest + +import pandas._libs.window.aggregations as window_aggregations + +from pandas import Series +import pandas._testing as tm + + +def _get_rolling_aggregations(): + # list pairs of name and function + # each function has this signature: + # (const float64_t[:] values, ndarray[int64_t] start, + # ndarray[int64_t] end, int64_t minp) -> np.ndarray + named_roll_aggs = ( + [ + ("roll_sum", window_aggregations.roll_sum), + ("roll_mean", window_aggregations.roll_mean), + ] + + [ + (f"roll_var({ddof})", partial(window_aggregations.roll_var, ddof=ddof)) + for ddof in [0, 1] + ] + + [ + ("roll_skew", window_aggregations.roll_skew), + ("roll_kurt", window_aggregations.roll_kurt), + ("roll_median_c", window_aggregations.roll_median_c), + ("roll_max", window_aggregations.roll_max), + ("roll_min", window_aggregations.roll_min), + ] + + [ + ( + f"roll_quantile({quantile},{interpolation})", + partial( + window_aggregations.roll_quantile, + quantile=quantile, + interpolation=interpolation, + ), + ) + for quantile in [0.0001, 0.5, 0.9999] + for interpolation in window_aggregations.interpolation_types + ] + + [ + ( + f"roll_rank({percentile},{method},{ascending})", + partial( + window_aggregations.roll_rank, + percentile=percentile, + method=method, + ascending=ascending, + ), + ) + for percentile in [True, False] + for method in window_aggregations.rolling_rank_tiebreakers.keys() + for ascending in [True, False] + ] + ) + # unzip to a list of 2 tuples, names and functions + unzipped = list(zip(*named_roll_aggs)) + return {"ids": unzipped[0], "params": unzipped[1]} + + +_rolling_aggregations = _get_rolling_aggregations() + + +@pytest.fixture( + params=_rolling_aggregations["params"], ids=_rolling_aggregations["ids"] +) +def rolling_aggregation(request): + """Make a rolling aggregation function as fixture.""" + return request.param + + +def test_rolling_aggregation_boundary_consistency(rolling_aggregation): + # GH-45647 + minp, step, width, size, selection = 0, 1, 3, 11, [2, 7] + values = np.arange(1, 1 + size, dtype=np.float64) + end = np.arange(width, size, step, dtype=np.int64) + start = end - width + selarr = np.array(selection, dtype=np.int32) + result = Series(rolling_aggregation(values, start[selarr], end[selarr], minp)) + expected = Series(rolling_aggregation(values, start, end, minp)[selarr]) + tm.assert_equal(expected, result) + + +def test_rolling_aggregation_with_unused_elements(rolling_aggregation): + # GH-45647 + minp, width = 0, 5 # width at least 4 for kurt + size = 2 * width + 5 + values = np.arange(1, size + 1, dtype=np.float64) + values[width : width + 2] = sys.float_info.min + values[width + 2] = np.nan + values[width + 3 : width + 5] = sys.float_info.max + start = np.array([0, size - width], dtype=np.int64) + end = np.array([width, size], dtype=np.int64) + loc = np.array( + [j for i in range(len(start)) for j in range(start[i], end[i])], + dtype=np.int32, + ) + result = Series(rolling_aggregation(values, start, end, minp)) + compact_values = np.array(values[loc], dtype=np.float64) + compact_start = np.arange(0, len(start) * width, width, dtype=np.int64) + compact_end = compact_start + width + expected = Series( + rolling_aggregation(compact_values, compact_start, compact_end, minp) + ) + assert np.isfinite(expected.values).all(), "Not all expected values are finite" + tm.assert_equal(expected, result)
- [x] closes #45647 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45655
2022-01-27T10:53:45Z
2022-01-28T19:52:52Z
2022-01-28T19:52:51Z
2022-01-28T19:53:09Z
CI/TST: Skip another s3 test that can crash GHA worker
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml index 4beba743209b6..8080a81519d8f 100644 --- a/.github/workflows/posix.yml +++ b/.github/workflows/posix.yml @@ -50,7 +50,7 @@ jobs: COVERAGE: ${{ !contains(matrix.settings[0], 'pypy') }} concurrency: # https://github.community/t/concurrecy-not-work-for-push/183068/7 - group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{ matrix.settings[0] }}-${{ matrix.settings[1] }} + group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-${{ matrix.settings[0] }}-${{ matrix.settings[1] }}-${{ matrix.settings[2] }} cancel-in-progress: true services: diff --git a/pandas/tests/base/test_unique.py b/pandas/tests/base/test_unique.py index ac21c2f979dd4..e399ae45160fc 100644 --- a/pandas/tests/base/test_unique.py +++ b/pandas/tests/base/test_unique.py @@ -105,6 +105,9 @@ def test_nunique_null(null_obj, index_or_series_obj): @pytest.mark.single +@pytest.mark.xfail( + reason="Flaky in the CI. Remove once CI has a single build: GH 44584", strict=False +) def test_unique_bad_unicode(index_or_series): # regression test for #34550 uval = "\ud83d" # smiley emoji diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index d4c3c93a32af0..6b08ea4da8f56 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -7,6 +7,7 @@ StringIO, ) import logging +import os import numpy as np import pytest @@ -264,6 +265,12 @@ def test_read_csv_handles_boto_s3_object(self, s3_resource, tips_file): expected = read_csv(tips_file) tm.assert_frame_equal(result, expected) + @pytest.mark.skipif( + os.environ.get("PANDAS_CI", "0") == "1", + reason="This test can hang in our CI min_versions build " + "and leads to '##[error]The runner has " + "received a shutdown signal...' in GHA. GH: 45651", + ) def test_read_csv_chunked_download(self, s3_resource, caplog, s3so): # 8 MB, S3FS uses 5MB chunks import s3fs diff --git a/pandas/tests/io/test_fsspec.py b/pandas/tests/io/test_fsspec.py index 172065755d4b7..f1040c0bd30f2 100644 --- a/pandas/tests/io/test_fsspec.py +++ b/pandas/tests/io/test_fsspec.py @@ -3,7 +3,6 @@ import numpy as np import pytest -from pandas.compat import PY310 from pandas.compat._optional import VERSIONS from pandas import ( @@ -182,7 +181,6 @@ def test_arrowparquet_options(fsspectest): @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) fastparquet @td.skip_if_no("fastparquet") -@pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_fastparquet_options(fsspectest): """Regression test for writing to a not-yet-existent GCS Parquet file.""" df = DataFrame({"a": [0]}) diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index a1a39a1cf8881..2eb8738d88b41 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -13,10 +13,7 @@ from pandas._config import get_option -from pandas.compat import ( - PY310, - is_platform_windows, -) +from pandas.compat import is_platform_windows from pandas.compat.pyarrow import ( pa_version_under2p0, pa_version_under5p0, @@ -265,7 +262,6 @@ def test_options_py(df_compat, pa): check_round_trip(df_compat) -@pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_options_fp(df_compat, fp): # use the set option @@ -343,7 +339,6 @@ def test_get_engine_auto_error_message(): get_engine("auto") -@pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_cross_engine_pa_fp(df_cross_compat, pa, fp): # cross-compat with differing reading/writing engines @@ -409,11 +404,7 @@ def test_error(self, engine): msg = "to_parquet only supports IO with DataFrames" self.check_error_on_write(obj, engine, ValueError, msg) - def test_columns_dtypes(self, request, engine): - if PY310 and engine == "fastparquet": - request.node.add_marker( - pytest.mark.xfail(reason="fastparquet failing on 3.10") - ) + def test_columns_dtypes(self, engine): df = pd.DataFrame({"string": list("abc"), "int": list(range(1, 4))}) # unicode @@ -440,7 +431,7 @@ def test_columns_dtypes_invalid(self, engine): self.check_error_on_write(df, engine, ValueError, msg) @pytest.mark.parametrize("compression", [None, "gzip", "snappy", "brotli"]) - def test_compression(self, engine, compression, request): + def test_compression(self, engine, compression): if compression == "snappy": pytest.importorskip("snappy") @@ -448,19 +439,11 @@ def test_compression(self, engine, compression, request): elif compression == "brotli": pytest.importorskip("brotli") - if PY310 and engine == "fastparquet": - request.node.add_marker( - pytest.mark.xfail(reason="fastparquet failing on 3.10") - ) df = pd.DataFrame({"A": [1, 2, 3]}) check_round_trip(df, engine, write_kwargs={"compression": compression}) - def test_read_columns(self, engine, request): + def test_read_columns(self, engine): # GH18154 - if PY310 and engine == "fastparquet": - request.node.add_marker( - pytest.mark.xfail(reason="fastparquet failing on 3.10") - ) df = pd.DataFrame({"string": list("abc"), "int": list(range(1, 4))}) expected = pd.DataFrame({"string": list("abc")}) @@ -468,11 +451,7 @@ def test_read_columns(self, engine, request): df, engine, expected=expected, read_kwargs={"columns": ["string"]} ) - def test_write_index(self, engine, request): - if PY310 and engine == "fastparquet": - request.node.add_marker( - pytest.mark.xfail(reason="fastparquet failing on 3.10") - ) + def test_write_index(self, engine): check_names = engine != "fastparquet" df = pd.DataFrame({"A": [1, 2, 3]}) @@ -521,13 +500,9 @@ def test_multiindex_with_columns(self, pa): df, engine, read_kwargs={"columns": ["A", "B"]}, expected=df[["A", "B"]] ) - def test_write_ignoring_index(self, engine, request): + def test_write_ignoring_index(self, engine): # ENH 20768 # Ensure index=False omits the index from the written Parquet file. - if PY310 and engine == "fastparquet": - request.node.add_marker( - pytest.mark.xfail(reason="fastparquet failing on 3.10") - ) df = pd.DataFrame({"a": [1, 2, 3], "b": ["q", "r", "s"]}) write_kwargs = {"compression": None, "index": False} @@ -1011,7 +986,6 @@ def test_read_parquet_manager(self, pa, using_array_manager): class TestParquetFastParquet(Base): - @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_basic(self, fp, df_full): df = df_full @@ -1029,7 +1003,6 @@ def test_duplicate_columns(self, fp): msg = "Cannot create parquet dataset with duplicate column names" self.check_error_on_write(df, fp, ValueError, msg) - @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_bool_with_none(self, fp): df = pd.DataFrame({"a": [True, None, False]}) expected = pd.DataFrame({"a": [1.0, np.nan, 0.0]}, dtype="float16") @@ -1049,12 +1022,10 @@ def test_unsupported(self, fp): msg = "Can't infer object conversion type" self.check_error_on_write(df, fp, ValueError, msg) - @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_categorical(self, fp): df = pd.DataFrame({"a": pd.Categorical(list("abc"))}) check_round_trip(df, fp) - @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_filter_row_groups(self, fp): d = {"a": list(range(0, 3))} df = pd.DataFrame(d) @@ -1073,7 +1044,6 @@ def test_s3_roundtrip(self, df_compat, s3_resource, fp, s3so): write_kwargs={"compression": None, "storage_options": s3so}, ) - @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_partition_cols_supported(self, fp, df_full): # GH #23283 partition_cols = ["bool", "int"] @@ -1091,7 +1061,6 @@ def test_partition_cols_supported(self, fp, df_full): actual_partition_cols = fastparquet.ParquetFile(path, False).cats assert len(actual_partition_cols) == 2 - @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_partition_cols_string(self, fp, df_full): # GH #27117 partition_cols = "bool" @@ -1109,7 +1078,6 @@ def test_partition_cols_string(self, fp, df_full): actual_partition_cols = fastparquet.ParquetFile(path, False).cats assert len(actual_partition_cols) == 1 - @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_partition_on_supported(self, fp, df_full): # GH #23283 partition_cols = ["bool", "int"] @@ -1145,7 +1113,6 @@ def test_error_on_using_partition_cols_and_partition_on(self, fp, df_full): partition_cols=partition_cols, ) - @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_empty_dataframe(self, fp): # GH #27339 df = pd.DataFrame() @@ -1153,7 +1120,6 @@ def test_empty_dataframe(self, fp): expected.index.name = "index" check_round_trip(df, fp, expected=expected) - @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_timezone_aware_index(self, fp, timezone_aware_date_list): idx = 5 * [timezone_aware_date_list] diff --git a/pandas/tests/io/test_user_agent.py b/pandas/tests/io/test_user_agent.py index 78f2365a09d4c..a5869e919f478 100644 --- a/pandas/tests/io/test_user_agent.py +++ b/pandas/tests/io/test_user_agent.py @@ -5,18 +5,25 @@ import http.server from io import BytesIO import multiprocessing +import os import socket import time import urllib.error import pytest -from pandas.compat import PY310 import pandas.util._test_decorators as td import pandas as pd import pandas._testing as tm +pytestmark = pytest.mark.skipif( + os.environ.get("PANDAS_CI", "0") == "1", + reason="This test can hang in our CI min_versions build " + "and leads to '##[error]The runner has " + "received a shutdown signal...' in GHA. GH 45651", +) + class BaseUserAgentResponder(http.server.BaseHTTPRequestHandler): """ @@ -245,7 +252,6 @@ def responder(request): # TODO(ArrayManager) fastparquet marks=[ td.skip_array_manager_not_yet_implemented, - pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10"), ], ), (PickleUserAgentResponder, pd.read_pickle, None), @@ -283,7 +289,6 @@ def test_server_and_default_headers(responder, read_method, parquet_engine): # TODO(ArrayManager) fastparquet marks=[ td.skip_array_manager_not_yet_implemented, - pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10"), ], ), (PickleUserAgentResponder, pd.read_pickle, None),
Example from https://github.com/pandas-dev/pandas/runs/4957463823?check_suite_focus=true ``` .....ss...s...s.........sss..........ss..........ss..................ssssss...s...s...x.............................XXXXXXXXX.XxXX2022-01-26 21:25:12,489 - s3fs - DEBUG - Setting up s3fs instance 2022-01-26T21:25:12.5442600Z 2022-01-26 21:25:12,543 - s3fs - DEBUG - Get directory listing page for pandas-test 2022-01-26T21:25:12.5650735Z 2022-01-26 21:25:12,564 - s3fs - DEBUG - Fetch: pandas-test/large-file.csv, 0-5505024 2022-01-26T22:08:22.5747205Z ##[error]The runner has received a shutdown signal. This can happen when the runner service is stopped, or a manually started runner is canceled. 2022-01-26T22:08:23.3842467Z ```
https://api.github.com/repos/pandas-dev/pandas/pulls/45651
2022-01-26T23:58:12Z
2022-01-27T07:12:02Z
2022-01-27T07:12:02Z
2022-02-01T14:01:04Z
Backport PR #45623 on branch 1.4.x (REGR: loc.setitem losing index name when df was empty before)
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 79dae514b77e9..026051d126d5b 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -15,6 +15,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Regression in :meth:`Series.mask` with ``inplace=True`` and ``PeriodDtype`` and an incompatible ``other`` coercing to a common dtype instead of raising (:issue:`45546`) +- Regression in :meth:`DataFrame.loc.__setitem__` losing :class:`Index` name if :class:`DataFrame` was empty before (:issue:`45621`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 77482cbc88bf5..91255c563b2d3 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -2003,7 +2003,7 @@ def _setitem_with_indexer_missing(self, indexer, value): # We will ignore the existing dtypes instead of using # internals.concat logic df = value.to_frame().T - df.index = [indexer] + df.index = Index([indexer], name=self.obj.index.name) if not has_dtype: # i.e. if we already had a Series or ndarray, keep that # dtype. But if we had a list or dict, then do inference diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 8f9caf1cd13aa..23927b3d3264e 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1281,6 +1281,13 @@ def test_setting_mismatched_na_into_nullable_fails( with pytest.raises(TypeError, match=msg): df2.iloc[:2, 0] = [null, null] + def test_loc_expand_empty_frame_keep_index_name(self): + # GH#45621 + df = DataFrame(columns=["b"], index=Index([], name="a")) + df.loc[0] = 1 + expected = DataFrame({"b": [1]}, index=Index([0], name="a")) + tm.assert_frame_equal(df, expected) + class TestDataFrameIndexingUInt64: def test_setitem(self, uint64_frame):
Backport PR #45623: REGR: loc.setitem losing index name when df was empty before
https://api.github.com/repos/pandas-dev/pandas/pulls/45650
2022-01-26T23:35:11Z
2022-01-27T01:14:08Z
2022-01-27T01:14:08Z
2022-01-27T01:14:08Z
Backport PR #45646 on branch 1.4.x (Revert "PERF: nancorr pearson (#42761)")
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 79dae514b77e9..1b69c42e90e95 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -32,7 +32,7 @@ Bug fixes Other ~~~~~ -- +- Reverted performance speedup of :meth:`DataFrame.corr` for ``method=pearson`` to fix precision regression (:issue:`45640`, :issue:`42761`) - .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index 3d099a53163bc..1b33b90ba0fa5 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -329,12 +329,8 @@ def nancorr(const float64_t[:, :] mat, bint cov=False, minp=None): Py_ssize_t i, j, xi, yi, N, K bint minpv float64_t[:, ::1] result - # Initialize to None since we only use in the no missing value case - float64_t[::1] means=None, ssqds=None ndarray[uint8_t, ndim=2] mask - bint no_nans int64_t nobs = 0 - float64_t mean, ssqd, val float64_t vx, vy, dx, dy, meanx, meany, divisor, ssqdmx, ssqdmy, covxy N, K = (<object>mat).shape @@ -346,57 +342,25 @@ def nancorr(const float64_t[:, :] mat, bint cov=False, minp=None): result = np.empty((K, K), dtype=np.float64) mask = np.isfinite(mat).view(np.uint8) - no_nans = mask.all() - - # Computing the online means and variances is expensive - so if possible we can - # precompute these and avoid repeating the computations each time we handle - # an (xi, yi) pair - if no_nans: - means = np.empty(K, dtype=np.float64) - ssqds = np.empty(K, dtype=np.float64) - - with nogil: - for j in range(K): - ssqd = mean = 0 - for i in range(N): - val = mat[i, j] - dx = val - mean - mean += 1 / (i + 1) * dx - ssqd += (val - mean) * dx - - means[j] = mean - ssqds[j] = ssqd with nogil: for xi in range(K): for yi in range(xi + 1): - covxy = 0 - if no_nans: - for i in range(N): + # Welford's method for the variance-calculation + # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance + nobs = ssqdmx = ssqdmy = covxy = meanx = meany = 0 + for i in range(N): + if mask[i, xi] and mask[i, yi]: vx = mat[i, xi] vy = mat[i, yi] - covxy += (vx - means[xi]) * (vy - means[yi]) - - ssqdmx = ssqds[xi] - ssqdmy = ssqds[yi] - nobs = N - - else: - nobs = ssqdmx = ssqdmy = covxy = meanx = meany = 0 - for i in range(N): - # Welford's method for the variance-calculation - # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance - if mask[i, xi] and mask[i, yi]: - vx = mat[i, xi] - vy = mat[i, yi] - nobs += 1 - dx = vx - meanx - dy = vy - meany - meanx += 1 / nobs * dx - meany += 1 / nobs * dy - ssqdmx += (vx - meanx) * dx - ssqdmy += (vy - meany) * dy - covxy += (vx - meanx) * dy + nobs += 1 + dx = vx - meanx + dy = vy - meany + meanx += 1 / nobs * dx + meany += 1 / nobs * dy + ssqdmx += (vx - meanx) * dx + ssqdmy += (vy - meany) * dy + covxy += (vx - meanx) * dy if nobs < minpv: result[xi, yi] = result[yi, xi] = NaN diff --git a/pandas/tests/frame/methods/test_cov_corr.py b/pandas/tests/frame/methods/test_cov_corr.py index 60d5d8c8ccaca..6a1466ae1ea46 100644 --- a/pandas/tests/frame/methods/test_cov_corr.py +++ b/pandas/tests/frame/methods/test_cov_corr.py @@ -337,6 +337,13 @@ def test_corrwith_dup_cols(self): expected = Series(np.ones(4), index=[0, 0, 1, 2]) tm.assert_series_equal(result, expected) + def test_corr_numerical_instabilities(self): + # GH#45640 + df = DataFrame([[0.2, 0.4], [0.4, 0.2]]) + result = df.corr() + expected = DataFrame({0: [1.0, -1.0], 1: [-1.0, 1.0]}) + tm.assert_frame_equal(result - 1, expected - 1, atol=1e-17) + @td.skip_if_no_scipy def test_corrwith_spearman(self): # GH#21925
Backport PR #45646: Revert "PERF: nancorr pearson (#42761)"
https://api.github.com/repos/pandas-dev/pandas/pulls/45649
2022-01-26T23:34:11Z
2022-01-27T01:13:41Z
2022-01-27T01:13:41Z
2022-01-27T01:13:41Z
Revert "PERF: nancorr pearson (#42761)"
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 79dae514b77e9..1b69c42e90e95 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -32,7 +32,7 @@ Bug fixes Other ~~~~~ -- +- Reverted performance speedup of :meth:`DataFrame.corr` for ``method=pearson`` to fix precision regression (:issue:`45640`, :issue:`42761`) - .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/algos.pyx b/pandas/_libs/algos.pyx index 3d099a53163bc..1b33b90ba0fa5 100644 --- a/pandas/_libs/algos.pyx +++ b/pandas/_libs/algos.pyx @@ -329,12 +329,8 @@ def nancorr(const float64_t[:, :] mat, bint cov=False, minp=None): Py_ssize_t i, j, xi, yi, N, K bint minpv float64_t[:, ::1] result - # Initialize to None since we only use in the no missing value case - float64_t[::1] means=None, ssqds=None ndarray[uint8_t, ndim=2] mask - bint no_nans int64_t nobs = 0 - float64_t mean, ssqd, val float64_t vx, vy, dx, dy, meanx, meany, divisor, ssqdmx, ssqdmy, covxy N, K = (<object>mat).shape @@ -346,57 +342,25 @@ def nancorr(const float64_t[:, :] mat, bint cov=False, minp=None): result = np.empty((K, K), dtype=np.float64) mask = np.isfinite(mat).view(np.uint8) - no_nans = mask.all() - - # Computing the online means and variances is expensive - so if possible we can - # precompute these and avoid repeating the computations each time we handle - # an (xi, yi) pair - if no_nans: - means = np.empty(K, dtype=np.float64) - ssqds = np.empty(K, dtype=np.float64) - - with nogil: - for j in range(K): - ssqd = mean = 0 - for i in range(N): - val = mat[i, j] - dx = val - mean - mean += 1 / (i + 1) * dx - ssqd += (val - mean) * dx - - means[j] = mean - ssqds[j] = ssqd with nogil: for xi in range(K): for yi in range(xi + 1): - covxy = 0 - if no_nans: - for i in range(N): + # Welford's method for the variance-calculation + # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance + nobs = ssqdmx = ssqdmy = covxy = meanx = meany = 0 + for i in range(N): + if mask[i, xi] and mask[i, yi]: vx = mat[i, xi] vy = mat[i, yi] - covxy += (vx - means[xi]) * (vy - means[yi]) - - ssqdmx = ssqds[xi] - ssqdmy = ssqds[yi] - nobs = N - - else: - nobs = ssqdmx = ssqdmy = covxy = meanx = meany = 0 - for i in range(N): - # Welford's method for the variance-calculation - # https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance - if mask[i, xi] and mask[i, yi]: - vx = mat[i, xi] - vy = mat[i, yi] - nobs += 1 - dx = vx - meanx - dy = vy - meany - meanx += 1 / nobs * dx - meany += 1 / nobs * dy - ssqdmx += (vx - meanx) * dx - ssqdmy += (vy - meany) * dy - covxy += (vx - meanx) * dy + nobs += 1 + dx = vx - meanx + dy = vy - meany + meanx += 1 / nobs * dx + meany += 1 / nobs * dy + ssqdmx += (vx - meanx) * dx + ssqdmy += (vy - meany) * dy + covxy += (vx - meanx) * dy if nobs < minpv: result[xi, yi] = result[yi, xi] = NaN diff --git a/pandas/tests/frame/methods/test_cov_corr.py b/pandas/tests/frame/methods/test_cov_corr.py index 60d5d8c8ccaca..6a1466ae1ea46 100644 --- a/pandas/tests/frame/methods/test_cov_corr.py +++ b/pandas/tests/frame/methods/test_cov_corr.py @@ -337,6 +337,13 @@ def test_corrwith_dup_cols(self): expected = Series(np.ones(4), index=[0, 0, 1, 2]) tm.assert_series_equal(result, expected) + def test_corr_numerical_instabilities(self): + # GH#45640 + df = DataFrame([[0.2, 0.4], [0.4, 0.2]]) + result = df.corr() + expected = DataFrame({0: [1.0, -1.0], 1: [-1.0, 1.0]}) + tm.assert_frame_equal(result - 1, expected - 1, atol=1e-17) + @td.skip_if_no_scipy def test_corrwith_spearman(self): # GH#21925
- [x] closes #45640 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45646
2022-01-26T20:55:42Z
2022-01-26T23:34:02Z
2022-01-26T23:34:01Z
2022-01-28T10:19:04Z
Backport PR #45627 on branch 1.4.x (CLN: Use pytest -r to show skipped tests instead of print_skipped.py)
diff --git a/.github/workflows/assign.yml b/.github/workflows/assign.yml index a6d3f1f383751..a1812843b1a8f 100644 --- a/.github/workflows/assign.yml +++ b/.github/workflows/assign.yml @@ -4,11 +4,10 @@ on: types: created jobs: - one: + issue_assign: runs-on: ubuntu-latest steps: - if: github.event.comment.body == 'take' - name: run: | echo "Assigning issue ${{ github.event.issue.number }} to ${{ github.event.comment.user.login }}" curl -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" -d '{"assignees": ["${{ github.event.comment.user.login }}"]}' https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.issue.number }}/assignees diff --git a/.github/workflows/datamanger.yml b/.github/workflows/datamanger.yml index 28ce7bc5c0ef4..7e93696b3c317 100644 --- a/.github/workflows/datamanger.yml +++ b/.github/workflows/datamanger.yml @@ -49,6 +49,3 @@ jobs: run: | source activate pandas-dev ci/run_tests.sh - - - name: Print skipped tests - run: python ci/print_skipped.py diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml index e8ed6d4545194..4cce75779d750 100644 --- a/.github/workflows/docbuild-and-upload.yml +++ b/.github/workflows/docbuild-and-upload.yml @@ -40,12 +40,7 @@ jobs: - name: Build documentation run: | source activate pandas-dev - doc/make.py --warnings-are-errors | tee sphinx.log ; exit ${PIPESTATUS[0]} - - # This can be removed when the ipython directive fails when there are errors, - # including the `tee sphinx.log` in te previous step (https://github.com/ipython/ipython/issues/11547) - - name: Check ipython directive errors - run: "! grep -B10 \"^<<<-------------------------------------------------------------------------$\" sphinx.log" + doc/make.py --warnings-are-errors - name: Install ssh key run: | diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml index 4f3a06faf64af..4beba743209b6 100644 --- a/.github/workflows/posix.yml +++ b/.github/workflows/posix.yml @@ -150,9 +150,6 @@ jobs: path: test-data.xml if: failure() - - name: Print skipped tests - run: python ci/print_skipped.py - - name: Upload coverage to Codecov uses: codecov/codecov-action@v2 with: diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml index fa1eee2db6fc3..988859ca4ac93 100644 --- a/.github/workflows/python-dev.yml +++ b/.github/workflows/python-dev.yml @@ -85,10 +85,6 @@ jobs: path: test-data.xml if: failure() - - name: Print skipped tests - run: | - python ci/print_skipped.py - - name: Report Coverage run: | coverage report -m diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml index 02a4a9ad44865..9002f35376613 100644 --- a/ci/azure/posix.yml +++ b/ci/azure/posix.yml @@ -61,8 +61,3 @@ jobs: testResultsFiles: 'test-data.xml' testRunTitle: ${{ format('{0}-$(CONDA_PY)', parameters.name) }} displayName: 'Publish test results' - - - script: | - source activate pandas-dev - python ci/print_skipped.py - displayName: 'Print skipped tests' diff --git a/ci/azure/windows.yml b/ci/azure/windows.yml index 7061a266f28c7..836332251d7b3 100644 --- a/ci/azure/windows.yml +++ b/ci/azure/windows.yml @@ -79,8 +79,3 @@ jobs: testResultsFiles: 'test-data.xml' testRunTitle: ${{ format('{0}-$(CONDA_PY)', parameters.name) }} displayName: 'Publish test results' - - - bash: | - source activate pandas-dev - python ci/print_skipped.py - displayName: 'Print skipped tests' diff --git a/ci/print_skipped.py b/ci/print_skipped.py deleted file mode 100755 index 60e2f047235e6..0000000000000 --- a/ci/print_skipped.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python3 -import os -import xml.etree.ElementTree as et - - -def main(filename): - if not os.path.isfile(filename): - raise RuntimeError(f"Could not find junit file {repr(filename)}") - - tree = et.parse(filename) - root = tree.getroot() - current_class = "" - for el in root.iter("testcase"): - cn = el.attrib["classname"] - for sk in el.findall("skipped"): - old_class = current_class - current_class = cn - if old_class != current_class: - yield None - yield { - "class_name": current_class, - "test_name": el.attrib["name"], - "message": sk.attrib["message"], - } - - -if __name__ == "__main__": - print("SKIPPED TESTS:") - i = 1 - for test_data in main("test-data.xml"): - if test_data is None: - print("-" * 80) - else: - print( - f"#{i} {test_data['class_name']}." - f"{test_data['test_name']}: {test_data['message']}" - ) - i += 1 diff --git a/ci/run_tests.sh b/ci/run_tests.sh index 203f8fe293a06..020a3ed7f265c 100755 --- a/ci/run_tests.sh +++ b/ci/run_tests.sh @@ -24,7 +24,7 @@ if [[ $(uname) == "Linux" && -z $DISPLAY ]]; then XVFB="xvfb-run " fi -PYTEST_CMD="${XVFB}pytest -m \"$PATTERN\" -n $PYTEST_WORKERS --dist=loadfile $TEST_ARGS $COVERAGE $PYTEST_TARGET" +PYTEST_CMD="${XVFB}pytest -r fEs -m \"$PATTERN\" -n $PYTEST_WORKERS --dist=loadfile $TEST_ARGS $COVERAGE $PYTEST_TARGET" if [[ $(uname) != "Linux" && $(uname) != "Darwin" ]]; then PYTEST_CMD="$PYTEST_CMD --ignore=pandas/tests/plotting/"
Backport PR #45627: CLN: Use pytest -r to show skipped tests instead of print_skipped.py
https://api.github.com/repos/pandas-dev/pandas/pulls/45645
2022-01-26T20:20:32Z
2022-01-26T23:05:26Z
2022-01-26T23:05:26Z
2022-01-26T23:05:26Z
BUG: frame.shift(axis=1) with ArrayManager
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 2a34c71412789..4badae6acf4de 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -93,6 +93,7 @@ ) from pandas.core.dtypes.cast import ( + can_hold_element, construct_1d_arraylike_from_scalar, construct_2d_arraylike_from_scalar, find_common_type, @@ -5364,6 +5365,48 @@ def shift( result.columns = self.columns.copy() return result + elif ( + axis == 1 + and periods != 0 + and fill_value is not lib.no_default + and ncols > 0 + ): + arrays = self._mgr.arrays + if len(arrays) > 1 or ( + # If we only have one block and we know that we can't + # keep the same dtype (i.e. the _can_hold_element check) + # then we can go through the reindex_indexer path + # (and avoid casting logic in the Block method). + # The exception to this (until 2.0) is datetimelike + # dtypes with integers, which cast. + not can_hold_element(arrays[0], fill_value) + # TODO(2.0): remove special case for integer-with-datetimelike + # once deprecation is enforced + and not ( + lib.is_integer(fill_value) and needs_i8_conversion(arrays[0].dtype) + ) + ): + # GH#35488 we need to watch out for multi-block cases + # We only get here with fill_value not-lib.no_default + nper = abs(periods) + nper = min(nper, ncols) + if periods > 0: + indexer = np.array( + [-1] * nper + list(range(ncols - periods)), dtype=np.intp + ) + else: + indexer = np.array( + list(range(nper, ncols)) + [-1] * nper, dtype=np.intp + ) + mgr = self._mgr.reindex_indexer( + self.columns, + indexer, + axis=0, + fill_value=fill_value, + allow_dups=True, + ) + res_df = self._constructor(mgr) + return res_df.__finalize__(self, method="shift") return super().shift( periods=periods, freq=freq, axis=axis, fill_value=fill_value diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 8599a1281a976..af77e1057e310 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -36,7 +36,6 @@ is_1d_only_ea_dtype, is_dtype_equal, is_list_like, - needs_i8_conversion, ) from pandas.core.dtypes.dtypes import ExtensionDtype from pandas.core.dtypes.generic import ( @@ -366,50 +365,6 @@ def shift(self: T, periods: int, axis: int, fill_value) -> T: if fill_value is lib.no_default: fill_value = None - if ( - axis == 0 - and self.ndim == 2 - and ( - self.nblocks > 1 - or ( - # If we only have one block and we know that we can't - # keep the same dtype (i.e. the _can_hold_element check) - # then we can go through the reindex_indexer path - # (and avoid casting logic in the Block method). - # The exception to this (until 2.0) is datetimelike - # dtypes with integers, which cast. - not self.blocks[0]._can_hold_element(fill_value) - # TODO(2.0): remove special case for integer-with-datetimelike - # once deprecation is enforced - and not ( - lib.is_integer(fill_value) - and needs_i8_conversion(self.blocks[0].dtype) - ) - ) - ) - ): - # GH#35488 we need to watch out for multi-block cases - # We only get here with fill_value not-lib.no_default - ncols = self.shape[0] - nper = abs(periods) - nper = min(nper, ncols) - if periods > 0: - indexer = np.array( - [-1] * nper + list(range(ncols - periods)), dtype=np.intp - ) - else: - indexer = np.array( - list(range(nper, ncols)) + [-1] * nper, dtype=np.intp - ) - result = self.reindex_indexer( - self.items, - indexer, - axis=0, - fill_value=fill_value, - allow_dups=True, - ) - return result - return self.apply("shift", periods=periods, axis=axis, fill_value=fill_value) def fillna(self: T, value, limit, inplace: bool, downcast) -> T: diff --git a/pandas/tests/apply/test_str.py b/pandas/tests/apply/test_str.py index f215df4c24206..4fefc79e04aad 100644 --- a/pandas/tests/apply/test_str.py +++ b/pandas/tests/apply/test_str.py @@ -256,19 +256,10 @@ def test_transform_groupby_kernel_series(string_series, op): @pytest.mark.parametrize("op", frame_transform_kernels) -def test_transform_groupby_kernel_frame( - axis, float_frame, op, using_array_manager, request -): +def test_transform_groupby_kernel_frame(axis, float_frame, op, request): # TODO(2.0) Remove after pad/backfill deprecation enforced op = maybe_normalize_deprecated_kernels(op) # GH 35964 - if using_array_manager and op == "pct_change" and axis in (1, "columns"): - # TODO(ArrayManager) shift with axis=1 - request.node.add_marker( - pytest.mark.xfail( - reason="shift axis=1 not yet implemented for ArrayManager" - ) - ) args = [0.0] if op == "fillna" else [] if axis == 0 or axis == "index": diff --git a/pandas/tests/frame/methods/test_shift.py b/pandas/tests/frame/methods/test_shift.py index 2463e81d78edd..c053289bbe11a 100644 --- a/pandas/tests/frame/methods/test_shift.py +++ b/pandas/tests/frame/methods/test_shift.py @@ -611,14 +611,8 @@ def test_shift_dt64values_int_fill_deprecated(self): ) # TODO(2.0): remove filtering @pytest.mark.filterwarnings("ignore:Index.ravel.*:FutureWarning") - def test_shift_dt64values_axis1_invalid_fill( - self, vals, as_cat, using_array_manager, request - ): + def test_shift_dt64values_axis1_invalid_fill(self, vals, as_cat, request): # GH#44564 - if using_array_manager: - mark = pytest.mark.xfail(raises=NotImplementedError) - request.node.add_marker(mark) - ser = Series(vals) if as_cat: ser = ser.astype("category") @@ -665,7 +659,6 @@ def test_shift_axis1_categorical_columns(self): ) tm.assert_frame_equal(result, expected) - @td.skip_array_manager_not_yet_implemented def test_shift_axis1_many_periods(self): # GH#44978 periods > len(columns) df = DataFrame(np.random.rand(5, 3)) diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index 12a25a1e61211..6ef33513294a1 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -165,13 +165,9 @@ def test_transform_broadcast(tsframe, ts): assert_fp_equal(res.xs(idx), agged[idx]) -def test_transform_axis_1(request, transformation_func, using_array_manager): +def test_transform_axis_1(request, transformation_func): # GH 36308 - if using_array_manager and transformation_func == "pct_change": - # TODO(ArrayManager) column-wise shift - request.node.add_marker( - pytest.mark.xfail(reason="ArrayManager: shift axis=1 not yet implemented") - ) + # TODO(2.0) Remove after pad/backfill deprecation enforced transformation_func = maybe_normalize_deprecated_kernels(transformation_func)
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45644
2022-01-26T20:12:01Z
2022-01-30T23:51:34Z
2022-01-30T23:51:34Z
2022-01-31T00:08:47Z
REGR: Series.fillna(downcast=False)
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 1bd8da2d2b03c..21aab5058d25b 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -15,6 +15,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Regression in :meth:`Series.mask` with ``inplace=True`` and ``PeriodDtype`` and an incompatible ``other`` coercing to a common dtype instead of raising (:issue:`45546`) +- Regression in :meth:`Series.fillna` with ``downcast=False`` incorrectly downcasting ``object`` dtype (:issue:`45603`) - Regression in :meth:`DataFrame.loc.__setitem__` losing :class:`Index` name if :class:`DataFrame` was empty before (:issue:`45621`) - diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 3d4f53530b89c..4bc351ab0695e 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -531,6 +531,8 @@ def split_and_operate(self, func, *args, **kwargs) -> list[Block]: @final def _maybe_downcast(self, blocks: list[Block], downcast=None) -> list[Block]: + if downcast is False: + return blocks if self.dtype == _dtype_obj: # GH#44241 We downcast regardless of the argument; @@ -544,10 +546,6 @@ def _maybe_downcast(self, blocks: list[Block], downcast=None) -> list[Block]: if downcast is None: return blocks - if downcast is False: - # turn if off completely - # TODO: not reached, deprecate in favor of downcast=None - return blocks return extend_blocks([b._downcast_2d(downcast) for b in blocks]) diff --git a/pandas/tests/frame/methods/test_fillna.py b/pandas/tests/frame/methods/test_fillna.py index b5bdf6a70199c..21a45d9ee1f20 100644 --- a/pandas/tests/frame/methods/test_fillna.py +++ b/pandas/tests/frame/methods/test_fillna.py @@ -244,6 +244,12 @@ def test_fillna_downcast(self): expected = DataFrame({"a": [1, 0]}) tm.assert_frame_equal(result, expected) + def test_fillna_downcast_false(self, frame_or_series): + # GH#45603 preserve object dtype with downcast=False + obj = frame_or_series([1, 2, 3], dtype="object") + result = obj.fillna("", downcast=False) + tm.assert_equal(result, obj) + @pytest.mark.parametrize("columns", [["A", "A", "B"], ["A", "A"]]) def test_fillna_dictlike_value_duplicate_colnames(self, columns): # GH#43476
- [x] closes #45603 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45642
2022-01-26T18:15:20Z
2022-01-27T22:24:29Z
2022-01-27T22:24:29Z
2022-01-27T22:58:53Z
Switch deps to Conda
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 4492f9c20cd0a..6f91c885bf1e8 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -50,7 +50,7 @@ repos: - flake8==4.0.1 - flake8-comprehensions==3.7.0 - flake8-bugbear==21.3.2 - - pandas-dev-flaker==0.2.0 + - pandas-dev-flaker==0.4.0 - repo: https://github.com/PyCQA/isort rev: 5.10.1 hooks: diff --git a/environment.yml b/environment.yml index 51350a143b913..66df6a4ac05e6 100644 --- a/environment.yml +++ b/environment.yml @@ -32,10 +32,12 @@ dependencies: # documentation - gitpython # obtain contributors from git for whatsnew - gitdb - - sphinx - - sphinx-panels - numpydoc < 1.2 # 2021-02-09 1.2dev breaking CI + - pandas-dev-flaker=0.4.0 - pydata-sphinx-theme + - pytest-cython + - sphinx + - sphinx-panels - types-python-dateutil - types-PyMySQL - types-pytz @@ -78,7 +80,6 @@ dependencies: - ipywidgets - nbformat - notebook>=6.0.3 - - pip # optional - blosc @@ -120,6 +121,3 @@ dependencies: - pyreadstat # pandas.read_spss - tabulate>=0.8.3 # DataFrame.to_markdown - natsort # DataFrame.sort_values - - pip: - - pandas-dev-flaker==0.2.0 - - pytest-cython diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 768c462a746dc..8b060273cf55c 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -85,7 +85,9 @@ def __init__( **kwargs, ): if css_styles and css_converter: - css = ";".join(a + ":" + str(v) for (a, v) in css_styles[css_row, css_col]) + css = ";".join( + [a + ":" + str(v) for (a, v) in css_styles[css_row, css_col]] + ) style = css_converter(css) return super().__init__(row=row, col=col, val=val, style=style, **kwargs) diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index 9d4998784222f..910ba63b5bb3a 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -724,7 +724,7 @@ def _combine_lines(self, lines) -> str: Combines a list of JSON objects into one JSON object. """ return ( - f'[{",".join((line for line in (line.strip() for line in lines) if line))}]' + f'[{",".join([line for line in (line.strip() for line in lines) if line])}]' ) def read(self): diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index cfcdde40549b9..53b5079ed6be9 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -2040,10 +2040,10 @@ def __repr__(self) -> str: map(pprint_thing, (self.name, self.cname, self.axis, self.pos, self.kind)) ) return ",".join( - ( + [ f"{key}->{value}" for key, value in zip(["name", "cname", "axis", "pos", "kind"], temp) - ) + ] ) def __eq__(self, other: Any) -> bool: @@ -2341,10 +2341,10 @@ def __repr__(self) -> str: ) ) return ",".join( - ( + [ f"{key}->{value}" for key, value in zip(["name", "cname", "dtype", "kind", "shape"], temp) - ) + ] ) def __eq__(self, other: Any) -> bool: diff --git a/requirements-dev.txt b/requirements-dev.txt index 04ae7f6a97b16..729f44b4696ab 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -18,10 +18,12 @@ pycodestyle pyupgrade gitpython gitdb -sphinx -sphinx-panels numpydoc < 1.2 +pandas-dev-flaker==0.4.0 pydata-sphinx-theme +pytest-cython +sphinx +sphinx-panels types-python-dateutil types-PyMySQL types-pytz @@ -52,7 +54,6 @@ statsmodels ipywidgets nbformat notebook>=6.0.3 -pip blosc bottleneck>=1.3.1 ipykernel @@ -84,6 +85,4 @@ cftime pyreadstat tabulate>=0.8.3 natsort -pandas-dev-flaker==0.2.0 -pytest-cython setuptools>=51.0.0 diff --git a/scripts/tests/test_sync_flake8_versions.py b/scripts/tests/test_sync_flake8_versions.py index 21c3b743830ee..cd8d18f7e41cc 100644 --- a/scripts/tests/test_sync_flake8_versions.py +++ b/scripts/tests/test_sync_flake8_versions.py @@ -87,7 +87,7 @@ def test_get_revisions_no_failure(capsys): { "id": "flake8", "additional_dependencies": [ - "pandas-dev-flaker==0.2.0", + "pandas-dev-flaker==0.4.0", "flake8-bugs==1.1.1", ], } @@ -101,7 +101,7 @@ def test_get_revisions_no_failure(capsys): "id": "yesqa", "additional_dependencies": [ "flake8==0.1.1", - "pandas-dev-flaker==0.2.0", + "pandas-dev-flaker==0.4.0", "flake8-bugs==1.1.1", ], } @@ -116,7 +116,7 @@ def test_get_revisions_no_failure(capsys): { "pip": [ "git+https://github.com/pydata/pydata-sphinx-theme.git@master", - "pandas-dev-flaker==0.2.0", + "pandas-dev-flaker==0.4.0", ] }, ] diff --git a/setup.cfg b/setup.cfg index 9deebb835eff7..27a5c51d2f2aa 100644 --- a/setup.cfg +++ b/setup.cfg @@ -103,7 +103,11 @@ ignore = # tests use comparisons but not their returned value B015, # false positives - B301 + B301, + # single-letter variables + PDF023 + # "use 'pandas._testing' instead" in non-test code + PDF025 exclude = doc/sphinxext/*.py, doc/build/*.py,
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45641
2022-01-26T17:31:28Z
2022-02-06T22:37:35Z
2022-02-06T22:37:35Z
2022-02-06T22:38:50Z
BUG: ArrayManager indexing mismatched behavior
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 5f9bc142c5836..a98ba832e8a62 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -20,6 +20,7 @@ from pandas.util._decorators import doc from pandas.util._exceptions import find_stack_level +from pandas.core.dtypes.cast import can_hold_element from pandas.core.dtypes.common import ( is_array_like, is_bool_dtype, @@ -1583,15 +1584,13 @@ def _setitem_with_indexer(self, indexer, value, name="iloc"): # if there is only one block/type, still have to take split path # unless the block is one-dimensional or it can hold the value - if ( - not take_split_path - and getattr(self.obj._mgr, "blocks", False) - and self.ndim > 1 - ): + if not take_split_path and len(self.obj._mgr.arrays) and self.ndim > 1: # in case of dict, keys are indices val = list(value.values()) if isinstance(value, dict) else value - blk = self.obj._mgr.blocks[0] - take_split_path = not blk._can_hold_element(val) + arr = self.obj._mgr.arrays[0] + take_split_path = not can_hold_element( + arr, extract_array(val, extract_numpy=True) + ) # if we have any multi-indexes that have non-trivial slices # (not null slices) then we must take the split path, xref diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index a837c35b89f1a..80e1d0bede2cd 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -341,9 +341,8 @@ def where(self: T, other, cond, align: bool) -> T: cond=cond, ) - # TODO what is this used for? - # def setitem(self, indexer, value) -> ArrayManager: - # return self.apply_with_block("setitem", indexer=indexer, value=value) + def setitem(self: T, indexer, value) -> T: + return self.apply_with_block("setitem", indexer=indexer, value=value) def putmask(self, mask, new, align: bool = True): if align: @@ -467,7 +466,7 @@ def is_view(self) -> bool: @property def is_single_block(self) -> bool: - return False + return len(self.arrays) == 1 def _get_data_subset(self: T, predicate: Callable) -> T: indices = [i for i, arr in enumerate(self.arrays) if predicate(arr)] diff --git a/pandas/tests/extension/base/setitem.py b/pandas/tests/extension/base/setitem.py index 208a1a1757be2..7a822bd3c607a 100644 --- a/pandas/tests/extension/base/setitem.py +++ b/pandas/tests/extension/base/setitem.py @@ -1,13 +1,6 @@ import numpy as np import pytest -from pandas.core.dtypes.dtypes import ( - DatetimeTZDtype, - IntervalDtype, - PandasDtype, - PeriodDtype, -) - import pandas as pd import pandas._testing as tm from pandas.tests.extension.base.base import BaseExtensionTests @@ -367,19 +360,6 @@ def test_setitem_series(self, data, full_indexer): def test_setitem_frame_2d_values(self, data, request): # GH#44514 df = pd.DataFrame({"A": data}) - - # Avoiding using_array_manager fixture - # https://github.com/pandas-dev/pandas/pull/44514#discussion_r754002410 - using_array_manager = isinstance(df._mgr, pd.core.internals.ArrayManager) - if using_array_manager: - if not isinstance( - data.dtype, (PandasDtype, PeriodDtype, IntervalDtype, DatetimeTZDtype) - ): - # These dtypes have non-broken implementations of _can_hold_element - mark = pytest.mark.xfail(reason="Goes through split path, loses dtype") - request.node.add_marker(mark) - - df = pd.DataFrame({"A": data}) orig = df.copy() df.iloc[:] = df diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 5a97c591fd621..928f1742e1898 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1212,8 +1212,6 @@ def test_setitem_array_as_cell_value(self): expected = DataFrame({"a": [np.zeros((2,))], "b": [np.zeros((2, 2))]}) tm.assert_frame_equal(df, expected) - # with AM goes through split-path, loses dtype - @td.skip_array_manager_not_yet_implemented def test_iloc_setitem_nullable_2d_values(self): df = DataFrame({"A": [1, 2, 3]}, dtype="Int64") orig = df.copy() diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py index d60fe7d4f316d..76ef57391a7b3 100644 --- a/pandas/tests/frame/methods/test_quantile.py +++ b/pandas/tests/frame/methods/test_quantile.py @@ -673,19 +673,7 @@ def test_quantile_ea_with_na(self, obj, index): # TODO(GH#39763): filtering can be removed after GH#39763 is fixed @pytest.mark.filterwarnings("ignore:Using .astype to convert:FutureWarning") - def test_quantile_ea_all_na( - self, obj, index, frame_or_series, using_array_manager, request - ): - if ( - using_array_manager - and frame_or_series is DataFrame - and index.dtype == "m8[ns]" - ): - mark = pytest.mark.xfail( - reason="obj.astype fails bc obj is incorrectly dt64 at this point" - ) - request.node.add_marker(mark) - + def test_quantile_ea_all_na(self, obj, index, frame_or_series, request): obj.iloc[:] = index._na_value # TODO(ArrayManager): this casting should be unnecessary after GH#39763 is fixed diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index e028f6f293c62..68c2e3198a8c2 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -82,9 +82,7 @@ def test_iloc_setitem_fullcol_categorical(self, indexer, key, using_array_manage overwrite = isinstance(key, slice) and key == slice(None) - if overwrite or using_array_manager: - # TODO(ArrayManager) we always overwrite because ArrayManager takes - # the "split" path, which still overwrites + if overwrite: # TODO: GH#39986 this probably shouldn't behave differently expected = DataFrame({0: cat}) assert not np.shares_memory(df.values, orig_vals) @@ -108,13 +106,13 @@ def test_iloc_setitem_fullcol_categorical(self, indexer, key, using_array_manage tm.assert_frame_equal(df, expected) @pytest.mark.parametrize("box", [array, Series]) - def test_iloc_setitem_ea_inplace(self, frame_or_series, box, using_array_manager): + def test_iloc_setitem_ea_inplace(self, frame_or_series, box): # GH#38952 Case with not setting a full column # IntegerArray without NAs arr = array([1, 2, 3, 4]) obj = frame_or_series(arr.to_numpy("i8")) - if frame_or_series is Series or not using_array_manager: + if frame_or_series is Series: values = obj.values else: values = obj[0].values @@ -131,10 +129,7 @@ def test_iloc_setitem_ea_inplace(self, frame_or_series, box, using_array_manager if frame_or_series is Series: assert obj.values is values else: - if using_array_manager: - assert obj[0].values is values - else: - assert obj.values.base is values.base and values.base is not None + assert np.shares_memory(obj[0].values, values) def test_is_scalar_access(self): # GH#32085 index with duplicates doesn't matter for _is_scalar_access @@ -999,9 +994,6 @@ def test_iloc_getitem_readonly_key(self): expected = df["data"].loc[[1, 3, 6]] tm.assert_series_equal(result, expected) - # TODO(ArrayManager) setting single item with an iterable doesn't work yet - # in the "split" path - @td.skip_array_manager_not_yet_implemented def test_iloc_assign_series_to_df_cell(self): # GH 37593 df = DataFrame(columns=["a"], index=[0]) @@ -1224,8 +1216,6 @@ def test_iloc_getitem_setitem_fancy_exceptions(self, float_frame): # GH#32257 we let numpy do validation, get their exception float_frame.iloc[:, :, :] = 1 - # TODO(ArrayManager) "split" path doesn't properly implement DataFrame indexer - @td.skip_array_manager_not_yet_implemented def test_iloc_frame_indexer(self): # GH#39004 df = DataFrame({"a": [1, 2, 3]}) diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index c91a5c2764b34..6e1c3686f5dbe 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -7,8 +7,6 @@ import numpy as np import pytest -import pandas.util._test_decorators as td - from pandas.core.dtypes.common import ( is_float_dtype, is_integer_dtype, @@ -504,9 +502,6 @@ def test_multi_assign_broadcasting_rhs(self): df.loc[df["A"] == 0, ["A", "B"]] = df["D"] tm.assert_frame_equal(df, expected) - # TODO(ArrayManager) setting single item with an iterable doesn't work yet - # in the "split" path - @td.skip_array_manager_not_yet_implemented def test_setitem_list(self): # GH 6043 diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 4b751fa7d5e3e..27c8efd89a9b4 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -669,7 +669,7 @@ def test_loc_modify_datetime(self): tm.assert_frame_equal(df, expected) - def test_loc_setitem_frame_with_reindex(self, using_array_manager): + def test_loc_setitem_frame_with_reindex(self): # GH#6254 setting issue df = DataFrame(index=[3, 5, 4], columns=["A"], dtype=float) df.loc[[4, 3, 5], "A"] = np.array([1, 2, 3], dtype="int64") @@ -677,10 +677,6 @@ def test_loc_setitem_frame_with_reindex(self, using_array_manager): # setting integer values into a float dataframe with loc is inplace, # so we retain float dtype ser = Series([2, 3, 1], index=[3, 5, 4], dtype=float) - if using_array_manager: - # TODO(ArrayManager) with "split" path, we still overwrite the column - # and therefore don't take the dtype of the underlying object into account - ser = Series([2, 3, 1], index=[3, 5, 4], dtype="int64") expected = DataFrame({"A": ser}) tm.assert_frame_equal(df, expected) @@ -702,9 +698,6 @@ def test_loc_setitem_frame_with_inverted_slice(self): expected = DataFrame({"A": [3, 2, 1], "B": "string"}, index=[1, 2, 3]) tm.assert_frame_equal(df, expected) - # TODO(ArrayManager) "split" path overwrites column and therefore don't take - # the dtype of the underlying object into account - @td.skip_array_manager_not_yet_implemented def test_loc_setitem_empty_frame(self): # GH#6252 setting with an empty frame keys1 = ["@" + str(i) for i in range(5)] @@ -1225,6 +1218,10 @@ def test_loc_getitem_time_object(self, frame_or_series): @pytest.mark.parametrize("spmatrix_t", ["coo_matrix", "csc_matrix", "csr_matrix"]) @pytest.mark.parametrize("dtype", [np.int64, np.float64, complex]) @td.skip_if_no_scipy + @pytest.mark.filterwarnings( + # TODO(2.0): remove filtering; note only needed for using_array_manager + "ignore:The behavior of .astype from SparseDtype.*FutureWarning" + ) def test_loc_getitem_range_from_spmatrix(self, spmatrix_t, dtype): import scipy.sparse
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45639
2022-01-26T16:28:18Z
2022-01-28T02:04:36Z
2022-01-28T02:04:36Z
2022-01-28T02:52:13Z
added staircase entry in Domain Specific and Accessors section of pan…
diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst index 16cae9bbfbf46..15fa58f8d804a 100644 --- a/doc/source/ecosystem.rst +++ b/doc/source/ecosystem.rst @@ -363,6 +363,15 @@ Geopandas extends pandas data objects to include geographic information which su geometric operations. If your work entails maps and geographical coordinates, and you love pandas, you should take a close look at Geopandas. +`staircase <https://github.com/staircase-dev/staircase>`__ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +staircase is a data analysis package, built upon pandas and numpy, for modelling and +manipulation of mathematical step functions. It provides a rich variety of arithmetic +operations, relational operations, logical operations, statistical operations and +aggregations for step functions defined over real numbers, datetime and timedelta domains. + + `xarray <https://github.com/pydata/xarray>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -564,6 +573,7 @@ Library Accessor Classes Description `composeml`_ ``slice`` ``DataFrame`` Provides a generator for enhanced data slicing. `datatest`_ ``validate`` ``Series``, ``DataFrame``, ``Index`` Provides validation, differences, and acceptance managers. `woodwork`_ ``ww`` ``Series``, ``DataFrame`` Provides physical, logical, and semantic data typing information for Series and DataFrames. +`staircase`_ ``sc`` ``Series`` Provides methods for querying, aggregating and plotting step functions ================== ============ ==================================== =============================================================================== .. _cyberpandas: https://cyberpandas.readthedocs.io/en/latest @@ -576,6 +586,7 @@ Library Accessor Classes Description .. _composeml: https://github.com/alteryx/compose .. _datatest: https://datatest.readthedocs.io/en/stable/ .. _woodwork: https://github.com/alteryx/woodwork +.. _staircase: https://www.staircase.dev/ Development tools -----------------
…das ecosystem docs - [ ] closes #45635
https://api.github.com/repos/pandas-dev/pandas/pulls/45636
2022-01-26T13:01:39Z
2022-01-27T01:41:42Z
2022-01-27T01:41:42Z
2022-01-27T04:54:19Z
DOC: Fix typo in nth docstring
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index 229e8a1a4aa9d..b682723cb10de 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -2675,7 +2675,7 @@ def nth( A single nth value for the row or a list of nth values or slices. .. versionchanged:: 1.4.0 - Added slice and lists containiing slices. + Added slice and lists containing slices. Added index notation. dropna : {'any', 'all', None}, default None
Correct spelling mistake nth docstring in pandas/core/groupby/groupby.py
https://api.github.com/repos/pandas-dev/pandas/pulls/45633
2022-01-26T10:46:42Z
2022-01-26T17:49:15Z
2022-01-26T17:49:15Z
2022-02-10T19:26:39Z
TST: Added test for setitem loc using datetime-like str
diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 4b751fa7d5e3e..14ce47562c93d 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -2748,6 +2748,26 @@ def test_loc_setitem_uint8_upcast(value): tm.assert_frame_equal(df, expected) +@pytest.mark.parametrize( + "fill_val,exp_dtype", + [ + (Timestamp("2022-01-06"), "datetime64[ns]"), + (Timestamp("2022-01-07", tz="US/Eastern"), "datetime64[ns, US/Eastern]"), + ], +) +def test_loc_setitem_using_datetimelike_str_as_index(fill_val, exp_dtype): + + data = ["2022-01-02", "2022-01-03", "2022-01-04", fill_val.date()] + index = DatetimeIndex(data, tz=fill_val.tz, dtype=exp_dtype) + df = DataFrame([10, 11, 12, 14], columns=["a"], index=index) + # adding new row using an unexisting datetime-like str index + df.loc["2022-01-08", "a"] = 13 + + data.append("2022-01-08") + expected_index = DatetimeIndex(data, dtype=exp_dtype) + tm.assert_index_equal(df.index, expected_index, exact=True) + + class TestLocSeries: @pytest.mark.parametrize("val,expected", [(2 ** 63 - 1, 3), (2 ** 63, 4)]) def test_loc_uint64(self, val, expected):
Test to ensure index type conversion when updating existing dataframe which has datetime as index with datetime-like str using loc - [x] closes #28249 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45632
2022-01-26T08:53:10Z
2022-01-28T00:35:54Z
2022-01-28T00:35:53Z
2022-01-28T00:36:00Z
Backport PR #45628 on branch 1.4.x (CI/TST: Call join on server process test)
diff --git a/pandas/tests/io/test_user_agent.py b/pandas/tests/io/test_user_agent.py index fb6128bd514f9..bba8a45005e11 100644 --- a/pandas/tests/io/test_user_agent.py +++ b/pandas/tests/io/test_user_agent.py @@ -217,6 +217,7 @@ def responder(request): ) server_process.start() yield port + server_process.join(10) server_process.terminate() kill_time = 5 wait_time = 0
Backport PR #45628: CI/TST: Call join on server process test
https://api.github.com/repos/pandas-dev/pandas/pulls/45631
2022-01-26T05:12:07Z
2022-01-26T15:59:46Z
2022-01-26T15:59:46Z
2022-01-26T15:59:46Z
CI/TST: Call join on server process test
diff --git a/pandas/tests/io/test_user_agent.py b/pandas/tests/io/test_user_agent.py index 3d4c157e5f09e..78f2365a09d4c 100644 --- a/pandas/tests/io/test_user_agent.py +++ b/pandas/tests/io/test_user_agent.py @@ -218,6 +218,7 @@ def responder(request): ) server_process.start() yield port + server_process.join(10) server_process.terminate() kill_time = 5 wait_time = 0
Troubleshooting this current CI failure ``` @pytest.fixture def responder(request): """ Fixture that starts a local http server in a separate process on localhost and returns the port. Running in a separate process instead of a thread to allow termination/killing of http server upon cleanup. """ # Find an available port with socket.socket() as sock: sock.bind(("localhost", 0)) port = sock.getsockname()[1] server_process = multiprocessing.Process( target=process_server, args=(request.param, port) ) server_process.start() yield port server_process.terminate() kill_time = 5 wait_time = 0 while server_process.is_alive(): if wait_time > kill_time: server_process.kill() break else: wait_time += 0.1 time.sleep(0.1) > server_process.close() pandas/tests/io/test_user_agent.py:231: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ self = <Process name='Process-10' pid=13556 parent=8289 started> def close(self): ''' Close the Process object. This method releases resources held by the Process object. It is an error to call this method if the child process is still running. ''' if self._popen is not None: if self._popen.poll() is None: > raise ValueError("Cannot close a process while it is still running. " "You should first call join() or terminate().") E ValueError: Cannot close a process while it is still running. You should first call join() or terminate(). ```
https://api.github.com/repos/pandas-dev/pandas/pulls/45628
2022-01-26T02:14:28Z
2022-01-26T05:11:54Z
2022-01-26T05:11:54Z
2022-01-26T05:12:15Z
CLN: Use pytest -r to show skipped tests instead of print_skipped.py
diff --git a/.github/workflows/assign.yml b/.github/workflows/assign.yml index a6d3f1f383751..a1812843b1a8f 100644 --- a/.github/workflows/assign.yml +++ b/.github/workflows/assign.yml @@ -4,11 +4,10 @@ on: types: created jobs: - one: + issue_assign: runs-on: ubuntu-latest steps: - if: github.event.comment.body == 'take' - name: run: | echo "Assigning issue ${{ github.event.issue.number }} to ${{ github.event.comment.user.login }}" curl -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" -d '{"assignees": ["${{ github.event.comment.user.login }}"]}' https://api.github.com/repos/${{ github.repository }}/issues/${{ github.event.issue.number }}/assignees diff --git a/.github/workflows/datamanger.yml b/.github/workflows/datamanger.yml index 4ca92a7adcc52..368c770ad5f14 100644 --- a/.github/workflows/datamanger.yml +++ b/.github/workflows/datamanger.yml @@ -51,6 +51,3 @@ jobs: run: | source activate pandas-dev ci/run_tests.sh - - - name: Print skipped tests - run: python ci/print_skipped.py diff --git a/.github/workflows/docbuild-and-upload.yml b/.github/workflows/docbuild-and-upload.yml index e8ed6d4545194..4cce75779d750 100644 --- a/.github/workflows/docbuild-and-upload.yml +++ b/.github/workflows/docbuild-and-upload.yml @@ -40,12 +40,7 @@ jobs: - name: Build documentation run: | source activate pandas-dev - doc/make.py --warnings-are-errors | tee sphinx.log ; exit ${PIPESTATUS[0]} - - # This can be removed when the ipython directive fails when there are errors, - # including the `tee sphinx.log` in te previous step (https://github.com/ipython/ipython/issues/11547) - - name: Check ipython directive errors - run: "! grep -B10 \"^<<<-------------------------------------------------------------------------$\" sphinx.log" + doc/make.py --warnings-are-errors - name: Install ssh key run: | diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml index 4f3a06faf64af..4beba743209b6 100644 --- a/.github/workflows/posix.yml +++ b/.github/workflows/posix.yml @@ -150,9 +150,6 @@ jobs: path: test-data.xml if: failure() - - name: Print skipped tests - run: python ci/print_skipped.py - - name: Upload coverage to Codecov uses: codecov/codecov-action@v2 with: diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml index fa1eee2db6fc3..988859ca4ac93 100644 --- a/.github/workflows/python-dev.yml +++ b/.github/workflows/python-dev.yml @@ -85,10 +85,6 @@ jobs: path: test-data.xml if: failure() - - name: Print skipped tests - run: | - python ci/print_skipped.py - - name: Report Coverage run: | coverage report -m diff --git a/ci/azure/posix.yml b/ci/azure/posix.yml index 02a4a9ad44865..9002f35376613 100644 --- a/ci/azure/posix.yml +++ b/ci/azure/posix.yml @@ -61,8 +61,3 @@ jobs: testResultsFiles: 'test-data.xml' testRunTitle: ${{ format('{0}-$(CONDA_PY)', parameters.name) }} displayName: 'Publish test results' - - - script: | - source activate pandas-dev - python ci/print_skipped.py - displayName: 'Print skipped tests' diff --git a/ci/azure/windows.yml b/ci/azure/windows.yml index 7061a266f28c7..836332251d7b3 100644 --- a/ci/azure/windows.yml +++ b/ci/azure/windows.yml @@ -79,8 +79,3 @@ jobs: testResultsFiles: 'test-data.xml' testRunTitle: ${{ format('{0}-$(CONDA_PY)', parameters.name) }} displayName: 'Publish test results' - - - bash: | - source activate pandas-dev - python ci/print_skipped.py - displayName: 'Print skipped tests' diff --git a/ci/print_skipped.py b/ci/print_skipped.py deleted file mode 100755 index 60e2f047235e6..0000000000000 --- a/ci/print_skipped.py +++ /dev/null @@ -1,38 +0,0 @@ -#!/usr/bin/env python3 -import os -import xml.etree.ElementTree as et - - -def main(filename): - if not os.path.isfile(filename): - raise RuntimeError(f"Could not find junit file {repr(filename)}") - - tree = et.parse(filename) - root = tree.getroot() - current_class = "" - for el in root.iter("testcase"): - cn = el.attrib["classname"] - for sk in el.findall("skipped"): - old_class = current_class - current_class = cn - if old_class != current_class: - yield None - yield { - "class_name": current_class, - "test_name": el.attrib["name"], - "message": sk.attrib["message"], - } - - -if __name__ == "__main__": - print("SKIPPED TESTS:") - i = 1 - for test_data in main("test-data.xml"): - if test_data is None: - print("-" * 80) - else: - print( - f"#{i} {test_data['class_name']}." - f"{test_data['test_name']}: {test_data['message']}" - ) - i += 1 diff --git a/ci/run_tests.sh b/ci/run_tests.sh index 203f8fe293a06..020a3ed7f265c 100755 --- a/ci/run_tests.sh +++ b/ci/run_tests.sh @@ -24,7 +24,7 @@ if [[ $(uname) == "Linux" && -z $DISPLAY ]]; then XVFB="xvfb-run " fi -PYTEST_CMD="${XVFB}pytest -m \"$PATTERN\" -n $PYTEST_WORKERS --dist=loadfile $TEST_ARGS $COVERAGE $PYTEST_TARGET" +PYTEST_CMD="${XVFB}pytest -r fEs -m \"$PATTERN\" -n $PYTEST_WORKERS --dist=loadfile $TEST_ARGS $COVERAGE $PYTEST_TARGET" if [[ $(uname) != "Linux" && $(uname) != "Darwin" ]]; then PYTEST_CMD="$PYTEST_CMD --ignore=pandas/tests/plotting/"
Example when using `pytest -r s` ``` =========================== short test summary info ============================ SKIPPED [1] pandas/tests/test_downstream.py:30: skipping as toolz not available SKIPPED [1] pandas/tests/test_downstream.py:30: skipping as dask not available SKIPPED [1] pandas/tests/test_downstream.py:90: Could not import 'cftime' SKIPPED [1] pandas/tests/test_algos.py:1790: skipping high memory test since --run-high-memory was not set SKIPPED [1] pandas/tests/test_downstream.py:30: skipping as statsmodels not available SKIPPED [1] pandas/tests/test_downstream.py:30: skipping as sklearn not available SKIPPED [1] pandas/tests/test_downstream.py:30: skipping as seaborn not available SKIPPED [1] pandas/tests/test_downstream.py:30: skipping as pandas_datareader not available SKIPPED [1] pandas/tests/test_downstream.py:30: skipping as geopandas not available SKIPPED [1] pandas/tests/test_downstream.py:30: skipping as torch not available SKIPPED [3] pandas/tests/apply/test_frame_transform.py:22: Test is only for DataFrame with axis=1 SKIPPED [3] pandas/tests/apply/test_frame_transform.py:22: Test is only for DataFrame with axis=index SKIPPED [3] pandas/tests/apply/test_frame_transform.py:22: Test is only for DataFrame with axis=columns SKIPPED [1] pandas/tests/apply/test_series_apply.py:288: fillna doesn't raise TypeError on object SKIPPED [1] pandas/tests/apply/test_series_apply.py:288: rank doesn't raise TypeError on object SKIPPED [3] pandas/tests/apply/test_series_apply.py:502: Initializing a Series from a MultiIndex is not supported SKIPPED [1] pandas/tests/arrays/categorical/test_warnings.py:9: Missing dependency pytest-asyncio SKIPPED [10] pandas/tests/arrays/masked/test_arithmetic.py:29: subtract not implemented for boolean SKIPPED [2] pandas/tests/arrays/test_datetimelike.py:1415: Could not import 'dask.array' SKIPPED [1] pandas/tests/arrays/string_/test_string_arrow.py:59: chunked not applicable to numpy array SKIPPED [1] pandas/tests/arrays/string_/test_string_arrow.py:120: pyarrow is installed SKIPPED [4] pandas/tests/base/test_fillna.py:41: <class 'pandas.core.indexes.numeric.Int64Index'> doesn't allow for NA operations SKIPPED [2] pandas/tests/base/test_fillna.py:41: <class 'pandas.core.indexes.numeric.UInt64Index'> doesn't allow for NA operations SKIPPED [2] pandas/tests/base/test_fillna.py:41: <class 'pandas.core.indexes.range.RangeIndex'> doesn't allow for NA operations SKIPPED [16] pandas/tests/base/test_fillna.py:41: <class 'pandas.core.indexes.numeric.NumericIndex'> doesn't allow for NA operations SKIPPED [4] pandas/tests/base/test_fillna.py:41: <class 'pandas.core.indexes.base.Index'> doesn't allow for NA operations SKIPPED [4] pandas/tests/base/test_fillna.py:43: Test doesn't make sense on empty data SKIPPED [3] pandas/tests/base/test_fillna.py:45: MultiIndex can't hold 'nan' SKIPPED [3] pandas/tests/base/test_fillna.py:45: MultiIndex can't hold 'None' SKIPPED [12] pandas/tests/base/test_fillna.py:41: <class 'pandas.core.series.Series'> doesn't allow for NA operations SKIPPED [3] pandas/tests/base/test_misc.py:158: np.searchsorted doesn't work on pd.MultiIndex SKIPPED [1] pandas/tests/base/test_misc.py:172: Test doesn't make sense on empty data SKIPPED [1] pandas/tests/arrays/string_/test_string.py:526: not applicable SKIPPED [40] pandas/tests/base/test_unique.py:41: type doesn't allow for NA operations SKIPPED [4] pandas/tests/base/test_unique.py:43: Test doesn't make sense on empty data SKIPPED [3] pandas/tests/base/test_unique.py:45: MultiIndex can't hold 'nan' SKIPPED [3] pandas/tests/base/test_unique.py:45: MultiIndex can't hold 'None' SKIPPED [40] pandas/tests/base/test_value_counts.py:50: type doesn't allow for NA operations SKIPPED [40] pandas/tests/base/test_unique.py:87: type doesn't allow for NA operations SKIPPED [3] pandas/tests/base/test_unique.py:89: MultiIndex can't hold 'nan' SKIPPED [3] pandas/tests/base/test_unique.py:89: MultiIndex can't hold 'None' SKIPPED [4] pandas/tests/base/test_value_counts.py:52: Test doesn't make sense on empty data SKIPPED [3] pandas/tests/base/test_value_counts.py:54: MultiIndex can't hold 'nan' SKIPPED [3] pandas/tests/base/test_value_counts.py:54: MultiIndex can't hold 'None' SKIPPED [1] pandas/tests/extension/test_categorical.py:89: Memory usage doesn't match SKIPPED [1] pandas/tests/extension/test_categorical.py:135: Backwards compatibility SKIPPED [1] pandas/tests/extension/test_categorical.py:152: Not implemented SKIPPED [1] pandas/tests/extension/test_categorical.py:156: Not implemented SKIPPED [2] pandas/tests/extension/base/methods.py:350: <class 'pandas.core.arrays.categorical.Categorical'> does not support diff SKIPPED [2] pandas/tests/extension/test_categorical.py:166: Unobserved categories included SKIPPED [1] pandas/tests/extension/test_categorical.py:187: Not Applicable SKIPPED [2] pandas/tests/extension/base/ops.py:127: Categorical does not implement add SKIPPED [1] pandas/tests/extension/test_datetime.py:178: We have DatetimeTZBlock SKIPPED [40] pandas/tests/extension/base/reduce.py:65: Tested in tests/reductions/test_reductions.py SKIPPED [2] pandas/tests/extension/base/methods.py:350: <class 'pandas.core.arrays.interval.IntervalArray'> does not support diff SKIPPED [1] pandas/tests/extension/test_interval.py:124: addition is not defined for intervals SKIPPED [1] pandas/tests/extension/test_interval.py:141: Unsupported fillna option. SKIPPED [1] pandas/tests/extension/test_interval.py:145: Unsupported fillna option. SKIPPED [1] pandas/tests/extension/test_interval.py:149: Unsupported fillna option. SKIPPED [1] pandas/tests/extension/test_interval.py:153: Unsupported fillna option. SKIPPED [1] pandas/tests/extension/test_interval.py:157: Unsupported fillna option. SKIPPED [1] pandas/tests/extension/test_interval.py:176: custom repr SKIPPED [2] pandas/tests/extension/test_numpy.py:199: We don't register our dtype SKIPPED [2] pandas/tests/extension/test_numpy.py:211: Incorrect expected. SKIPPED [2] pandas/tests/extension/test_numpy.py:348: Incorrect expected. SKIPPED [397] pandas/tests/extension/test_string.py:31: chunked array n/a SKIPPED [4] pandas/tests/extension/base/methods.py:350: <class 'pandas.core.arrays.string_arrow.ArrowStringArray'> does not support diff SKIPPED [2] pandas/tests/extension/base/methods.py:350: <class 'pandas.core.arrays.string_.StringArray'> does not support diff SKIPPED [8] pandas/tests/extension/test_string.py:161: returns nullable SKIPPED [4] pandas/tests/extension/test_string.py:165: returns nullable SKIPPED [15] pandas/tests/extension/test_sparse.py:111: Can't store nan in int array. SKIPPED [1] pandas/tests/extension/test_sparse.py:269: Unsupported SKIPPED [2] pandas/tests/extension/test_sparse.py:348: Not Applicable SKIPPED [28] pandas/tests/extension/test_sparse.py:456: Incorrected expected from Series.combine SKIPPED [1] pandas/tests/extension/json/test_json.py:158: not implemented constructor from dtype SKIPPED [2] pandas/tests/frame/test_api.py:292: Missing dependency pytest-asyncio SKIPPED [1] pandas/tests/extension/json/test_json.py:180: Different definitions of NA SKIPPED [1] pandas/tests/extension/json/test_json.py:204: Setting a dict as a scalar SKIPPED [1] pandas/tests/extension/json/test_json.py:208: Setting a dict as a scalar SKIPPED [1] pandas/tests/extension/base/methods.py:21: value_counts is not implemented SKIPPED [2] pandas/tests/extension/base/methods.py:350: <class 'pandas.tests.extension.json.array.JSONArray'> does not support diff SKIPPED [2] pandas/tests/extension/json/test_json.py:221: Unhashable SKIPPED [1] pandas/tests/extension/json/test_json.py:225: Unhashable SKIPPED [1] pandas/tests/extension/json/test_json.py:229: Unhashable SKIPPED [1] pandas/tests/extension/json/test_json.py:246: combine for JSONArray not supported SKIPPED [1] pandas/tests/extension/json/test_json.py:250: combine for JSONArray not supported SKIPPED [1] pandas/tests/extension/json/test_json.py:254: combine for JSONArray not supported SKIPPED [1] pandas/tests/extension/json/test_json.py:258: Unhashable SKIPPED [1] pandas/tests/extension/json/test_json.py:262: broadcasting error SKIPPED [1] pandas/tests/extension/json/test_json.py:269: Can't compare dicts. SKIPPED [2] pandas/tests/extension/json/test_json.py:273: Can't compare dicts. SKIPPED [1] pandas/tests/extension/json/test_json.py:279: failing on np.array(self, dtype=str) SKIPPED [1] pandas/tests/extension/json/test_json.py:292: Unhashable SKIPPED [1] pandas/tests/extension/json/test_json.py:301: Unhashable SKIPPED [1] pandas/tests/extension/json/test_json.py:313: Unhashable SKIPPED [1] pandas/tests/extension/json/test_json.py:320: Unhashable SKIPPED [2] pandas/tests/extension/base/ops.py:127: JSONArray does not implement add SKIPPED [1] pandas/tests/frame/test_constructors.py:303: NumPy change. SKIPPED [26] pandas/tests/frame/test_query_eval.py:35: cannot evaluate with parser 'python' SKIPPED [4] pandas/tests/frame/test_reductions.py:1476: Count does not accept skipna. Mad needs a deprecation cycle. SKIPPED [2] pandas/tests/frame/methods/test_between_time.py:21: Specific locale is set en_US SKIPPED [1] pandas/tests/frame/methods/test_rank.py:330: skipping high memory test since --run-high-memory was not set SKIPPED [1] pandas/tests/generic/test_to_xarray.py:37: Test doesn't make sense for empty index SKIPPED [3] pandas/tests/groupby/test_categorical.py:1353: ngroup is not truly a reduction SKIPPED [1] pandas/tests/groupby/test_categorical.py:1386: ngroup is not truly a reduction SKIPPED [1] pandas/tests/groupby/test_categorical.py:1428: ngroup does not return the Categories on the index SKIPPED [2] pandas/tests/groupby/test_categorical.py:1458: ngroup does not return the Categories on the index SKIPPED [1] pandas/tests/groupby/test_groupby.py:721: Test not applicable SKIPPED [2] pandas/tests/groupby/test_groupby.py:724: Skip until behavior is determined (GH #5755) SKIPPED [1] pandas/tests/groupby/test_groupby_subclass.py:27: Not applicable SKIPPED [6] pandas/tests/groupby/test_groupby.py:2272: Not applicable SKIPPED [2] pandas/tests/groupby/test_quantile.py:39: Unclear numpy expectation for nearest result with equidistant data SKIPPED [12] pandas/tests/indexes/test_common.py:226: Skip na-check if index cannot hold na SKIPPED [1] pandas/tests/indexes/test_common.py:208: Skip check for empty Index and MultiIndex SKIPPED [1] pandas/tests/indexes/test_common.py:258: Skip check for empty Index SKIPPED [3] pandas/tests/indexes/test_common.py:298: RangeIndex is tested in test_drop_duplicates_no_duplicates as it cannot hold duplicates SKIPPED [3] pandas/tests/indexes/test_common.py:303: empty index is tested in test_drop_duplicates_no_duplicates as it cannot hold duplicates SKIPPED [2] pandas/tests/indexes/test_common.py:365: Skip check for empty Index, MultiIndex, and RangeIndex SKIPPED [1] pandas/tests/indexes/test_base.py:1159: Missing dependency pytest-asyncio SKIPPED [2] pandas/tests/indexes/test_common.py:453: missing value sorting order not well-defined SKIPPED [2] pandas/tests/indexes/common.py:610: skipping tests for <class 'pandas.core.indexes.category.CategoricalIndex'> SKIPPED [1] pandas/tests/io/test_fsspec.py:164: Could not import 'pyarrow' satisfying a min_version of 2 SKIPPED [1] pandas/tests/io/test_fsspec.py:241: Skipping because fsspec is installed. SKIPPED [1] pandas/tests/io/test_gcs.py:191: Skipping because gcsfs is installed. SKIPPED [2] pandas/tests/io/test_parquet.py:446: could not import 'snappy': No module named 'snappy' SKIPPED [1] pandas/tests/io/test_parquet.py:1024: not supported SKIPPED [1] pandas/tests/io/test_sql.py:1524: SQLAlchemy is installed SKIPPED [4] pandas/tests/io/test_sql.py:1742: no column with datetime with time zone SKIPPED [1] pandas/tests/io/test_html.py:1206: Not applicable for lxml SKIPPED [3] pandas/tests/io/test_sql.py:2258: Nested transactions rollbacks don't work with Pandas SKIPPED [2] pandas/tests/io/excel/test_readers.py:615: Skipped for engine: xlrd SKIPPED [4] pandas/tests/io/excel/test_readers.py:615: Skipped for engine: openpyxl SKIPPED [6] pandas/tests/io/excel/test_readers.py:615: Skipped for engine: None SKIPPED [2] pandas/tests/io/excel/test_readers.py:615: Skipped for engine: pyxlsb SKIPPED [1] pandas/tests/io/excel/test_readers.py:1265: chartsheets do not exist in the ODF format SKIPPED [1] pandas/tests/io/excel/test_readers.py:1278: chartsheets do not exist in the ODF format SKIPPED [8] pandas/tests/io/excel/test_readers.py:1498: xlrd no longer supports xlsx SKIPPED [3] pandas/tests/io/excel/test_writers.py:1110: Defaults to openpyxl and fails with floating point error on datetimes; may be fixed on newer versions of openpyxl - GH #38644 SKIPPED [1] pandas/tests/io/excel/test_readers.py:1553: chartsheets do not exist in the ODF format SKIPPED [3] pandas/tests/io/excel/test_readers.py:1567: Skipped SKIPPED [1] pandas/tests/io/formats/test_info.py:391: on PyPy deep=True does not change result SKIPPED [1] pandas/tests/io/formats/test_series_info.py:130: on PyPy deep=True does not change result SKIPPED [1] pandas/tests/io/json/test_ujson.py:950: Not idiomatic pandas SKIPPED [2] pandas/tests/io/json/test_ujson.py:1002: Incompatible with labelled=True SKIPPED [2] pandas/tests/io/json/test_pandas.py:1552: unconditional skip SKIPPED [635] pandas/tests/io/parser/conftest.py:280: pyarrow doesn't support this. SKIPPED [2] pandas/tests/io/parser/test_c_parser_only.py:558: skipping high memory test since --run-high-memory was not set SKIPPED [15] pandas/tests/io/parser/test_compression.py:102: Cannot deduce compression from buffer of compressed data. SKIPPED [1] pandas/tests/io/parser/common/test_common_basic.py:200: This is a low-memory specific test SKIPPED [2] pandas/tests/io/parser/test_parse_dates.py:1708: parse_datetime_string cannot reliably tell whether e.g. %m.%Y is a float or a date, thus we skip it SKIPPED [2] pandas/tests/io/parser/common/test_read_errors.py:248: 'c' engine does not support sep=None with delim_whitespace=False SKIPPED [171] pandas/tests/io/parser/dtypes/test_dtypes_basic.py:218: Skip test if no thousands sep is defined and sep is in value SKIPPED [1] pandas/tests/io/pytables/test_pytables_missing.py:9: Skipping because tables is installed. SKIPPED [1] pandas/tests/io/xml/test_to_xml.py:944: Skipping because lxml is installed. SKIPPED [1] pandas/tests/io/xml/test_xml.py:761: Skipping because lxml is installed. SKIPPED [1] pandas/tests/plotting/test_backend.py:95: matplotlib is present SKIPPED [1] pandas/tests/plotting/test_misc.py:23: matplotlib is present SKIPPED [9] pandas/tests/resample/test_base.py:105: need to test for ohlc from GH13083 SKIPPED [1] pandas/tests/resample/test_datetime_index.py:183: covered by test_resample_how_ohlc SKIPPED [1] pandas/tests/resample/test_resampler_grouper.py:27: Missing dependency pytest-asyncio SKIPPED [1] pandas/tests/scalar/test_nat.py:115: Period cannot parse empty string SKIPPED [2] pandas/tests/series/test_arithmetic.py:832: Test doesn't make sense on empty data SKIPPED [1] pandas/tests/series/test_constructors.py:804: Could not import 'dask' SKIPPED [3] pandas/tests/series/test_constructors.py:1978: fails on numpy below 1.19 SKIPPED [25] pandas/tests/series/indexing/test_setitem.py:720: test not applicable for this dtype SKIPPED [25] pandas/tests/series/indexing/test_setitem.py:731: test not applicable for this dtype SKIPPED [6] pandas/tests/series/methods/test_drop_duplicates.py:23: tested separately in test_drop_duplicates_bool SKIPPED [12] pandas/tests/series/methods/test_interpolate.py:800: This interpolation method is not supported for Timedelta Index yet. SKIPPED [1] pandas/tests/series/methods/test_rank.py:478: skipping high memory test since --run-high-memory was not set SKIPPED [3] pandas/tests/strings/test_extract.py:183: Index too short SKIPPED [3] pandas/tests/strings/test_extract.py:360: Index too short SKIPPED [2] pandas/tests/tools/test_to_datetime.py:318: Specific locale is set en_US SKIPPED [2] pandas/tests/tools/test_to_datetime.py:1714: Specific locale is set en_US SKIPPED [2] pandas/tests/tools/test_to_datetime.py:1724: Specific locale is set en_US SKIPPED [2] pandas/tests/tools/test_to_numeric.py:405: Missing PeriodDtype support in to_numeric SKIPPED [3] pandas/tests/tslibs/test_parsing.py:186: Specific locale is set en_US SKIPPED [1] pandas/tests/tslibs/test_timezones.py:27: UTC: special case in dateutil SKIPPED [1] pandas/tests/util/test_numba.py:8: Skipping because numba is installed. SKIPPED [1] pandas/conftest.py:1121: Could not find /home/runner/work/pandas/pandas/pandas/tests/not_a_file. ```
https://api.github.com/repos/pandas-dev/pandas/pulls/45627
2022-01-25T23:53:06Z
2022-01-26T20:19:37Z
2022-01-26T20:19:37Z
2022-01-26T20:27:46Z
BUG: parse_time_string with np.str_ obj
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 4e73ea348dfde..03da62983df22 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -264,6 +264,7 @@ Indexing - Bug in :meth:`Series.__setitem__` when setting ``boolean`` dtype values containing ``NA`` incorrectly raising instead of casting to ``boolean`` dtype (:issue:`45462`) - Bug in :meth:`Series.__setitem__` where setting :attr:`NA` into a numeric-dtpye :class:`Series` would incorrectly upcast to object-dtype rather than treating the value as ``np.nan`` (:issue:`44199`) - Bug in getting a column from a DataFrame with an object-dtype row index with datetime-like values: the resulting Series now preserves the exact object-dtype Index from the parent DataFrame (:issue:`42950`) +- Bug in indexing on a :class:`DatetimeIndex` with a ``np.str_`` key incorrectly raising (:issue:`45580`) - Missing diff --git a/pandas/_libs/tslibs/parsing.pyx b/pandas/_libs/tslibs/parsing.pyx index 559c56992f71e..942a07760b86e 100644 --- a/pandas/_libs/tslibs/parsing.pyx +++ b/pandas/_libs/tslibs/parsing.pyx @@ -291,7 +291,7 @@ def parse_datetime_string( return dt -def parse_time_string(arg: str, freq=None, dayfirst=None, yearfirst=None): +def parse_time_string(arg, freq=None, dayfirst=None, yearfirst=None): """ Try hard to parse datetime string, leveraging dateutil plus some extra goodies like quarter recognition. @@ -312,6 +312,16 @@ def parse_time_string(arg: str, freq=None, dayfirst=None, yearfirst=None): str Describing resolution of parsed string. """ + if type(arg) is not str: + # GH#45580 np.str_ satisfies isinstance(obj, str) but if we annotate + # arg as "str" this raises here + if not isinstance(arg, np.str_): + raise TypeError( + "Argument 'arg' has incorrect type " + f"(expected str, got {type(arg).__name__})" + ) + arg = str(arg) + if is_offset_object(freq): freq = freq.rule_code diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 4b751fa7d5e3e..dac5a2cea4090 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -209,6 +209,13 @@ def test_loc_getitem_single_boolean_arg(self, obj, key, exp): class TestLocBaseIndependent: # Tests for loc that do not depend on subclassing Base + def test_loc_npstr(self): + # GH#45580 + df = DataFrame(index=date_range("2021", "2022")) + result = df.loc[np.array(["2021/6/1"])[0] :] + expected = df.iloc[151:] + tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize( "msg, key", [
- [x] closes #45580 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45626
2022-01-25T23:12:07Z
2022-01-28T00:36:45Z
2022-01-28T00:36:45Z
2022-01-28T00:40:17Z
BUG: SeriesGroupBy.value_counts - index name missing in categorical columns
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 039a86da0541e..18fc16b5f38d3 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -224,6 +224,7 @@ Datetimelike - Bug in :func:`to_datetime` with sequences of ``np.str_`` objects incorrectly raising (:issue:`32264`) - Bug in :class:`Timestamp` construction when passing datetime components as positional arguments and ``tzinfo`` as a keyword argument incorrectly raising (:issue:`31929`) - Bug in :meth:`Index.astype` when casting from object dtype to ``timedelta64[ns]`` dtype incorrectly casting ``np.datetime64("NaT")`` values to ``np.timedelta64("NaT")`` instead of raising (:issue:`45722`) +- Bug in :meth:`SeriesGroupBy.value_counts` index when passing categorical column (:issue:`44324`) - Timedelta diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 949f369849323..9d0305d0d1208 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -602,23 +602,23 @@ def value_counts( ids, _, _ = self.grouper.group_info val = self.obj._values - def apply_series_value_counts(): - return self.apply( + names = self.grouper.names + [self.obj.name] + + if is_categorical_dtype(val.dtype) or ( + bins is not None and not np.iterable(bins) + ): + # scalar bins cannot be done at top level + # in a backward compatible way + # GH38672 relates to categorical dtype + ser = self.apply( Series.value_counts, normalize=normalize, sort=sort, ascending=ascending, bins=bins, ) - - if bins is not None: - if not np.iterable(bins): - # scalar bins cannot be done at top level - # in a backward compatible way - return apply_series_value_counts() - elif is_categorical_dtype(val.dtype): - # GH38672 - return apply_series_value_counts() + ser.index.names = names + return ser # groupby removes null keys from groupings mask = ids != -1 @@ -683,7 +683,6 @@ def apply_series_value_counts(): levels = [ping.group_index for ping in self.grouper.groupings] + [ lev # type: ignore[list-item] ] - names = self.grouper.names + [self.obj.name] if dropna: mask = codes[-1] != -1 diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index a33e4efbe3b6d..0cc7fa11d096a 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -271,7 +271,7 @@ def test_sorting_with_different_categoricals(): index = ["low", "med", "high", "low", "med", "high"] index = Categorical(index, categories=["low", "med", "high"], ordered=True) index = [["A", "A", "A", "B", "B", "B"], CategoricalIndex(index)] - index = MultiIndex.from_arrays(index, names=["group", None]) + index = MultiIndex.from_arrays(index, names=["group", "dose"]) expected = Series([2] * 6, index=index, name="dose") tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/test_value_counts.py b/pandas/tests/groupby/test_value_counts.py index 54f672cb69800..d38ba84cd1397 100644 --- a/pandas/tests/groupby/test_value_counts.py +++ b/pandas/tests/groupby/test_value_counts.py @@ -22,6 +22,26 @@ import pandas._testing as tm +def tests_value_counts_index_names_category_column(): + # GH44324 Missing name of index category column + df = DataFrame( + { + "gender": ["female"], + "country": ["US"], + } + ) + df["gender"] = df["gender"].astype("category") + result = df.groupby("country")["gender"].value_counts() + + # Construct expected, very specific multiindex + df_mi_expected = DataFrame([["US", "female"]], columns=["country", "gender"]) + df_mi_expected["gender"] = df_mi_expected["gender"].astype("category") + mi_expected = MultiIndex.from_frame(df_mi_expected) + expected = Series([1], index=mi_expected, name="gender") + + tm.assert_series_equal(result, expected) + + # our starting frame def seed_df(seed_nans, n, m): np.random.seed(1234)
- [X] closes #44324 - [X] tests added / passed - [X] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [X] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45625
2022-01-25T22:29:57Z
2022-02-05T23:19:28Z
2022-02-05T23:19:27Z
2022-02-06T22:02:07Z
DOC CLN: remove unnecessary substitution, due to curly brackets
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 432e12f303919..f97f558fd0e0b 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -1659,7 +1659,6 @@ def _apply_index( alt="applymap", altwise="elementwise", func="take a Series and return a string array of the same length", - axis='{0, 1, "index", "columns"}', input_note="the index as a Series, if an Index, or a level of a MultiIndex", output_note="an identically sized array of CSS styles as strings", var="s", @@ -1684,7 +1683,7 @@ def apply_index( ---------- func : function ``func`` should {func}. - axis : {axis} + axis : {{0, 1, "index", "columns"}} The headers over which to apply the function. level : int, str, list, optional If index is MultiIndex the level(s) over which to apply the function. @@ -1745,7 +1744,6 @@ def apply_index( alt="apply", altwise="level-wise", func="take a scalar and return a string", - axis='{0, 1, "index", "columns"}', input_note="an index value, if an Index, or a level value of a MultiIndex", output_note="CSS styles as a string", var="v", @@ -2754,7 +2752,6 @@ def hide( name="background", alt="text", image_prefix="bg", - axis="{0 or 'index', 1 or 'columns', None}", text_threshold="", ) @Substitution(subset=subset) @@ -2789,7 +2786,7 @@ def background_gradient( Compress the color range at the high end. This is a multiple of the data range to extend above the maximum; good values usually in [0, 1], defaults to 0. - axis : {axis}, default 0 + axis : {{0, 1, "index", "columns", None}}, default 0 Apply to each column (``axis=0`` or ``'index'``), to each row (``axis=1`` or ``'columns'``), or to the entire DataFrame at once with ``axis=None``. @@ -2915,7 +2912,6 @@ def background_gradient( name="text", alt="background", image_prefix="tg", - axis="{0 or 'index', 1 or 'columns', None}", text_threshold="This argument is ignored (only used in `background_gradient`).", ) def text_gradient(
null
https://api.github.com/repos/pandas-dev/pandas/pulls/45624
2022-01-25T21:21:25Z
2022-01-26T01:41:16Z
2022-01-26T01:41:16Z
2022-01-26T06:16:24Z
REGR: loc.setitem losing index name when df was empty before
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 79dae514b77e9..026051d126d5b 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -15,6 +15,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Regression in :meth:`Series.mask` with ``inplace=True`` and ``PeriodDtype`` and an incompatible ``other`` coercing to a common dtype instead of raising (:issue:`45546`) +- Regression in :meth:`DataFrame.loc.__setitem__` losing :class:`Index` name if :class:`DataFrame` was empty before (:issue:`45621`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 5f9bc142c5836..fdcb55f3a637a 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -2017,7 +2017,7 @@ def _setitem_with_indexer_missing(self, indexer, value): # We will ignore the existing dtypes instead of using # internals.concat logic df = value.to_frame().T - df.index = [indexer] + df.index = Index([indexer], name=self.obj.index.name) if not has_dtype: # i.e. if we already had a Series or ndarray, keep that # dtype. But if we had a list or dict, then do inference diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 5a97c591fd621..4476fbe2f78c9 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1279,6 +1279,13 @@ def test_setting_mismatched_na_into_nullable_fails( with pytest.raises(TypeError, match=msg): df2.iloc[:2, 0] = [null, null] + def test_loc_expand_empty_frame_keep_index_name(self): + # GH#45621 + df = DataFrame(columns=["b"], index=Index([], name="a")) + df.loc[0] = 1 + expected = DataFrame({"b": [1]}, index=Index([0], name="a")) + tm.assert_frame_equal(df, expected) + class TestDataFrameIndexingUInt64: def test_setitem(self, uint64_frame):
- [x] closes #45621 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45623
2022-01-25T21:15:50Z
2022-01-26T23:35:01Z
2022-01-26T23:35:01Z
2022-01-28T10:19:23Z
BUG: NumericArray * td64_array
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 270a58c33cb8a..9b4131de10689 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -234,6 +234,7 @@ Timezones Numeric ^^^^^^^ - Bug in operations with array-likes with ``dtype="boolean"`` and :attr:`NA` incorrectly altering the array in-place (:issue:`45421`) +- Bug in multiplying a :class:`Series` with ``IntegerDtype`` or ``FloatingDtype`` by an arraylike with ``timedelta64[ns]`` dtype incorrectly raising (:issue:`45622`) - Conversion diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index f05f99b5764d5..6a69d4d610336 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -349,11 +349,10 @@ def _coerce_to_array( def _logical_method(self, other, op): assert op.__name__ in {"or_", "ror_", "and_", "rand_", "xor", "rxor"} - other_is_booleanarray = isinstance(other, BooleanArray) other_is_scalar = lib.is_scalar(other) mask = None - if other_is_booleanarray: + if isinstance(other, BooleanArray): other, mask = other._data, other._mask elif is_list_like(other): other = np.asarray(other, dtype="bool") @@ -370,7 +369,7 @@ def _logical_method(self, other, op): ) if not other_is_scalar and len(self) != len(other): - raise ValueError("Lengths must match to compare") + raise ValueError("Lengths must match") if op.__name__ in {"or_", "ror_"}: result, mask = ops.kleene_or(self._data, other, self._mask, mask) @@ -387,7 +386,7 @@ def _arith_method(self, other, op): mask = None op_name = op.__name__ - if isinstance(other, BooleanArray): + if isinstance(other, BaseMaskedArray): other, mask = other._data, other._mask elif is_list_like(other): @@ -397,14 +396,7 @@ def _arith_method(self, other, op): if len(self) != len(other): raise ValueError("Lengths must match") - # nans propagate - if mask is None: - mask = self._mask - if other is libmissing.NA: - # GH#45421 don't alter inplace - mask = mask | True - else: - mask = self._mask | mask + mask = self._propagate_mask(mask, other) if other is libmissing.NA: # if other is NA, the result will be all NA and we can't run the @@ -425,14 +417,6 @@ def _arith_method(self, other, op): with np.errstate(all="ignore"): result = op(self._data, other) - # divmod returns a tuple - if op_name == "divmod": - div, mod = result - return ( - self._maybe_mask_result(div, mask, other, "floordiv"), - self._maybe_mask_result(mod, mask, other, "mod"), - ) - return self._maybe_mask_result(result, mask, other, op_name) def __abs__(self): diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index 2ddbd54e23368..aa8148537fc1c 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -13,7 +13,6 @@ import numpy as np from pandas._libs import ( - iNaT, lib, missing as libmissing, ) @@ -582,6 +581,18 @@ def _hasna(self) -> bool: # error: Incompatible return value type (got "bool_", expected "bool") return self._mask.any() # type: ignore[return-value] + def _propagate_mask( + self, mask: npt.NDArray[np.bool_] | None, other + ) -> npt.NDArray[np.bool_]: + if mask is None: + mask = self._mask.copy() # TODO: need test for BooleanArray needing a copy + if other is libmissing.NA: + # GH#45421 don't alter inplace + mask = mask | True + else: + mask = self._mask | mask + return mask + def _cmp_method(self, other, op) -> BooleanArray: from pandas.core.arrays import BooleanArray @@ -619,12 +630,7 @@ def _cmp_method(self, other, op) -> BooleanArray: if result is NotImplemented: result = invalid_comparison(self._data, other, op) - # nans propagate - if mask is None: - mask = self._mask.copy() - else: - mask = self._mask | mask - + mask = self._propagate_mask(mask, other) return BooleanArray(result, mask, copy=False) def _maybe_mask_result(self, result, mask, other, op_name: str): @@ -636,6 +642,14 @@ def _maybe_mask_result(self, result, mask, other, op_name: str): other : scalar or array-like op_name : str """ + if op_name == "divmod": + # divmod returns a tuple + div, mod = result + return ( + self._maybe_mask_result(div, mask, other, "floordiv"), + self._maybe_mask_result(mod, mask, other, "mod"), + ) + # if we have a float operand we are by-definition # a float result # or our op is a divide @@ -657,8 +671,11 @@ def _maybe_mask_result(self, result, mask, other, op_name: str): # e.g. test_numeric_arr_mul_tdscalar_numexpr_path from pandas.core.arrays import TimedeltaArray - result[mask] = iNaT - return TimedeltaArray._simple_new(result) + if not isinstance(result, TimedeltaArray): + result = TimedeltaArray._simple_new(result) + + result[mask] = result.dtype.type("NaT") + return result elif is_integer_dtype(result): from pandas.core.arrays import IntegerArray diff --git a/pandas/core/arrays/numeric.py b/pandas/core/arrays/numeric.py index 3aceb76a3bba0..5bd4b8c96ffc4 100644 --- a/pandas/core/arrays/numeric.py +++ b/pandas/core/arrays/numeric.py @@ -1,6 +1,5 @@ from __future__ import annotations -import datetime import numbers from typing import ( TYPE_CHECKING, @@ -10,7 +9,6 @@ import numpy as np from pandas._libs import ( - Timedelta, lib, missing as libmissing, ) @@ -23,9 +21,7 @@ from pandas.core.dtypes.common import ( is_bool_dtype, - is_float, is_float_dtype, - is_integer, is_integer_dtype, is_list_like, is_object_dtype, @@ -33,10 +29,13 @@ pandas_dtype, ) +from pandas.core import ops +from pandas.core.arrays.base import ExtensionArray from pandas.core.arrays.masked import ( BaseMaskedArray, BaseMaskedDtype, ) +from pandas.core.construction import ensure_wrapped_if_datetimelike if TYPE_CHECKING: import pyarrow @@ -219,34 +218,40 @@ def _arith_method(self, other, op): op_name = op.__name__ omask = None - if getattr(other, "ndim", 0) > 1: - raise NotImplementedError("can only perform ops with 1-d structures") - - if isinstance(other, NumericArray): + if isinstance(other, BaseMaskedArray): other, omask = other._data, other._mask elif is_list_like(other): - other = np.asarray(other) + if not isinstance(other, ExtensionArray): + other = np.asarray(other) if other.ndim > 1: raise NotImplementedError("can only perform ops with 1-d structures") - if len(self) != len(other): - raise ValueError("Lengths must match") - if not (is_float_dtype(other) or is_integer_dtype(other)): - raise TypeError("can only perform ops with numeric values") - elif isinstance(other, (datetime.timedelta, np.timedelta64)): - other = Timedelta(other) + # We wrap the non-masked arithmetic logic used for numpy dtypes + # in Series/Index arithmetic ops. + other = ops.maybe_prepare_scalar_for_op(other, (len(self),)) + pd_op = ops.get_array_op(op) + other = ensure_wrapped_if_datetimelike(other) - else: - if not (is_float(other) or is_integer(other) or other is libmissing.NA): - raise TypeError("can only perform ops with numeric values") + mask = self._propagate_mask(omask, other) - if omask is None: - mask = self._mask.copy() - if other is libmissing.NA: - mask |= True + if other is libmissing.NA: + result = np.ones_like(self._data) + if "truediv" in op_name and self.dtype.kind != "f": + # The actual data here doesn't matter since the mask + # will be all-True, but since this is division, we want + # to end up with floating dtype. + result = result.astype(np.float64) else: - mask = self._mask | omask + # Make sure we do this before the "pow" mask checks + # to get an expected exception message on shape mismatch. + if self.dtype.kind in ["i", "u"] and op_name in ["floordiv", "mod"]: + # ATM we don't match the behavior of non-masked types with + # respect to floordiv-by-zero + pd_op = op + + with np.errstate(all="ignore"): + result = pd_op(self._data, other) if op_name == "pow": # 1 ** x is 1. @@ -266,25 +271,6 @@ def _arith_method(self, other, op): # x ** 0 is 1. mask = np.where((self._data == 0) & ~self._mask, False, mask) - if other is libmissing.NA: - result = np.ones_like(self._data) - if "truediv" in op_name and self.dtype.kind != "f": - # The actual data here doesn't matter since the mask - # will be all-True, but since this is division, we want - # to end up with floating dtype. - result = result.astype(np.float64) - else: - with np.errstate(all="ignore"): - result = op(self._data, other) - - # divmod returns a tuple - if op_name == "divmod": - div, mod = result - return ( - self._maybe_mask_result(div, mask, other, "floordiv"), - self._maybe_mask_result(mod, mask, other, "mod"), - ) - return self._maybe_mask_result(result, mask, other, op_name) _HANDLED_TYPES = (np.ndarray, numbers.Number) diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 212cfc267cb00..6e591e2f87cad 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -1097,6 +1097,7 @@ def test_dt64arr_addsub_intlike( # IntegerArray "can only perform ops with numeric values", "unsupported operand type.*Categorical", + r"unsupported operand type\(s\) for -: 'int' and 'Timestamp'", ] ) assert_invalid_addsub_type(obj, 1, msg) diff --git a/pandas/tests/arrays/boolean/test_arithmetic.py b/pandas/tests/arrays/boolean/test_arithmetic.py index f8f1af4c3da51..c6c52f90c065a 100644 --- a/pandas/tests/arrays/boolean/test_arithmetic.py +++ b/pandas/tests/arrays/boolean/test_arithmetic.py @@ -103,9 +103,11 @@ def test_error_invalid_values(data, all_arithmetic_operators): ) with pytest.raises(TypeError, match=msg): ops("foo") - msg = ( - r"unsupported operand type\(s\) for|" - "Concatenation operation is not implemented for NumPy arrays" + msg = "|".join( + [ + r"unsupported operand type\(s\) for", + "Concatenation operation is not implemented for NumPy arrays", + ] ) with pytest.raises(TypeError, match=msg): ops(pd.Timestamp("20180101")) @@ -113,9 +115,12 @@ def test_error_invalid_values(data, all_arithmetic_operators): # invalid array-likes if op not in ("__mul__", "__rmul__"): # TODO(extension) numpy's mul with object array sees booleans as numbers - msg = ( - r"unsupported operand type\(s\) for|can only concatenate str|" - "not all arguments converted during string formatting" + msg = "|".join( + [ + r"unsupported operand type\(s\) for", + "can only concatenate str", + "not all arguments converted during string formatting", + ] ) with pytest.raises(TypeError, match=msg): ops(pd.Series("foo", index=s.index)) diff --git a/pandas/tests/arrays/boolean/test_logical.py b/pandas/tests/arrays/boolean/test_logical.py index b4cca635fa238..66c117ea3fc66 100644 --- a/pandas/tests/arrays/boolean/test_logical.py +++ b/pandas/tests/arrays/boolean/test_logical.py @@ -63,7 +63,7 @@ def test_eq_mismatched_type(self, other): def test_logical_length_mismatch_raises(self, all_logical_operators): op_name = all_logical_operators a = pd.array([True, False, None], dtype="boolean") - msg = "Lengths must match to compare" + msg = "Lengths must match" with pytest.raises(ValueError, match=msg): getattr(a, op_name)([True, False]) diff --git a/pandas/tests/arrays/floating/test_arithmetic.py b/pandas/tests/arrays/floating/test_arithmetic.py index e5f67a2dce3ad..eac1a8c156504 100644 --- a/pandas/tests/arrays/floating/test_arithmetic.py +++ b/pandas/tests/arrays/floating/test_arithmetic.py @@ -129,9 +129,19 @@ def test_error_invalid_values(data, all_arithmetic_operators): ops = getattr(s, op) # invalid scalars - msg = ( - r"(:?can only perform ops with numeric values)" - r"|(:?FloatingArray cannot perform the operation mod)" + msg = "|".join( + [ + r"can only perform ops with numeric values", + r"FloatingArray cannot perform the operation mod", + "unsupported operand type", + "not all arguments converted during string formatting", + "can't multiply sequence by non-int of type 'float'", + "ufunc 'subtract' cannot use operands with types dtype", + r"can only concatenate str \(not \"float\"\) to str", + "ufunc '.*' not supported for the input types, and the inputs could not", + "ufunc '.*' did not contain a loop with signature matching types", + "Concatenation operation is not implemented for NumPy arrays", + ] ) with pytest.raises(TypeError, match=msg): ops("foo") @@ -148,6 +158,13 @@ def test_error_invalid_values(data, all_arithmetic_operators): "cannot perform .* with this index type: DatetimeArray", "Addition/subtraction of integers and integer-arrays " "with DatetimeArray is no longer supported. *", + "unsupported operand type", + "not all arguments converted during string formatting", + "can't multiply sequence by non-int of type 'float'", + "ufunc 'subtract' cannot use operands with types dtype", + r"ufunc 'add' cannot use operands with types dtype\('<M8\[ns\]'\)", + r"ufunc 'add' cannot use operands with types dtype\('float\d{2}'\)", + "cannot subtract DatetimeArray from ndarray", ] ) with pytest.raises(TypeError, match=msg): diff --git a/pandas/tests/arrays/integer/test_arithmetic.py b/pandas/tests/arrays/integer/test_arithmetic.py index 273bd9e4d34d5..89690f2e6bbc7 100644 --- a/pandas/tests/arrays/integer/test_arithmetic.py +++ b/pandas/tests/arrays/integer/test_arithmetic.py @@ -3,8 +3,6 @@ import numpy as np import pytest -from pandas.compat import np_version_under1p20 - import pandas as pd import pandas._testing as tm from pandas.core.arrays import FloatingArray @@ -166,9 +164,17 @@ def test_error_invalid_values(data, all_arithmetic_operators): ops = getattr(s, op) # invalid scalars - msg = ( - r"(:?can only perform ops with numeric values)" - r"|(:?IntegerArray cannot perform the operation mod)" + msg = "|".join( + [ + r"can only perform ops with numeric values", + r"IntegerArray cannot perform the operation mod", + r"unsupported operand type", + r"can only concatenate str \(not \"int\"\) to str", + "not all arguments converted during string", + "ufunc '.*' not supported for the input types, and the inputs could not", + "ufunc '.*' did not contain a loop with signature matching types", + "Addition/subtraction of integers and integer-arrays with Timestamp", + ] ) with pytest.raises(TypeError, match=msg): ops("foo") @@ -176,8 +182,18 @@ def test_error_invalid_values(data, all_arithmetic_operators): ops(pd.Timestamp("20180101")) # invalid array-likes - with pytest.raises(TypeError, match=msg): - ops(pd.Series("foo", index=s.index)) + str_ser = pd.Series("foo", index=s.index) + # with pytest.raises(TypeError, match=msg): + if all_arithmetic_operators in [ + "__mul__", + "__rmul__", + ]: # (data[~data.isna()] >= 0).all(): + res = ops(str_ser) + expected = pd.Series(["foo" * x for x in data], index=s.index) + tm.assert_series_equal(res, expected) + else: + with pytest.raises(TypeError, match=msg): + ops(str_ser) msg = "|".join( [ @@ -185,6 +201,10 @@ def test_error_invalid_values(data, all_arithmetic_operators): "cannot perform .* with this index type: DatetimeArray", "Addition/subtraction of integers and integer-arrays " "with DatetimeArray is no longer supported. *", + "unsupported operand type", + r"can only concatenate str \(not \"int\"\) to str", + "not all arguments converted during string", + "cannot subtract DatetimeArray from ndarray", ] ) with pytest.raises(TypeError, match=msg): @@ -206,16 +226,9 @@ def test_arith_coerce_scalar(data, all_arithmetic_operators): result = op(s, other) expected = op(s.astype(float), other) expected = expected.astype("Float64") - # rfloordiv results in nan instead of inf - if all_arithmetic_operators == "__rfloordiv__" and np_version_under1p20: - # for numpy 1.20 https://github.com/numpy/numpy/pull/16161 - # updated floordiv, now matches our behavior defined in core.ops - mask = ( - ((expected == np.inf) | (expected == -np.inf)).fillna(False).to_numpy(bool) - ) - expected.array._data[mask] = np.nan + # rmod results in NaN that wasn't NA in original nullable Series -> unmask it - elif all_arithmetic_operators == "__rmod__": + if all_arithmetic_operators == "__rmod__": mask = (s == 0).fillna(False).to_numpy(bool) expected.array._mask[mask] = False diff --git a/pandas/tests/arrays/masked/test_arithmetic.py b/pandas/tests/arrays/masked/test_arithmetic.py index 61775a2b94107..6f6fc957d1303 100644 --- a/pandas/tests/arrays/masked/test_arithmetic.py +++ b/pandas/tests/arrays/masked/test_arithmetic.py @@ -153,12 +153,22 @@ def test_error_len_mismatch(data, all_arithmetic_operators): other = [scalar] * (len(data) - 1) + msg = "|".join( + [ + r"operands could not be broadcast together with shapes \(3,\) \(4,\)", + r"operands could not be broadcast together with shapes \(4,\) \(3,\)", + ] + ) + + if data.dtype.kind == "b": + msg = "Lengths must match" + for other in [other, np.array(other)]: - with pytest.raises(ValueError, match="Lengths must match"): + with pytest.raises(ValueError, match=msg): op(data, other) s = pd.Series(data) - with pytest.raises(ValueError, match="Lengths must match"): + with pytest.raises(ValueError, match=msg): op(s, other) diff --git a/pandas/tests/arrays/masked_shared.py b/pandas/tests/arrays/masked_shared.py index 94029b5f1215b..7defccaf3dddf 100644 --- a/pandas/tests/arrays/masked_shared.py +++ b/pandas/tests/arrays/masked_shared.py @@ -144,3 +144,12 @@ def test_ufunc_with_out(self, dtype): assert res is arr tm.assert_extension_array_equal(res, expected) tm.assert_extension_array_equal(arr, expected) + + def test_mul_td64_array(self, dtype): + # GH#45622 + arr = pd.array([1, 2, pd.NA], dtype=dtype) + other = np.arange(3, dtype=np.int64).view("m8[ns]") + + result = arr * other + expected = pd.array([pd.Timedelta(0), pd.Timedelta(2), pd.NaT]) + tm.assert_extension_array_equal(result, expected) diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 43cf8cccb1784..74838e605930f 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -1706,6 +1706,7 @@ def test_mad_nullable_integer_all_na(any_signed_int_ea_dtype): result = df2.mad() expected = df.mad() expected[1] = pd.NA + expected = expected.astype("Float64") tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index fb2b9f0632f0d..2da835737bad4 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -22,11 +22,7 @@ to_datetime, ) import pandas._testing as tm -from pandas.core.arrays import ( - BooleanArray, - FloatingArray, - IntegerArray, -) +from pandas.core.arrays import BooleanArray from pandas.core.base import SpecificationError import pandas.core.common as com from pandas.core.groupby.base import maybe_normalize_deprecated_kernels @@ -1821,6 +1817,18 @@ def test_pivot_table_values_key_error(): pd.array([0], dtype="Float64"), pd.array([False], dtype="boolean"), ], + ids=[ + "bool", + "int", + "float", + "str", + "cat", + "dt64", + "dt64tz", + "Int64", + "Float64", + "boolean", + ], ) @pytest.mark.parametrize("method", ["attr", "agg", "apply"]) @pytest.mark.parametrize( @@ -1877,15 +1885,6 @@ def test_empty_groupby(columns, keys, values, method, op, request, using_array_m raises=AssertionError, match="(DataFrame|Series) are different" ) request.node.add_marker(mark) - elif ( - isinstance(values, (IntegerArray, FloatingArray)) - and op == "mad" - and isinstance(columns, list) - ): - mark = pytest.mark.xfail( - raises=TypeError, match="can only perform ops with numeric values" - ) - request.node.add_marker(mark) elif ( op == "mad"
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45622
2022-01-25T21:09:44Z
2022-01-28T00:33:24Z
2022-01-28T00:33:24Z
2022-01-28T00:35:35Z
Backport PR #45437 on branch 1.4.x (CI: Don't split slow vs non slow jobs for GHA posix)
diff --git a/.github/workflows/datamanger.yml b/.github/workflows/datamanger.yml index 3fc515883a225..28ce7bc5c0ef4 100644 --- a/.github/workflows/datamanger.yml +++ b/.github/workflows/datamanger.yml @@ -26,12 +26,9 @@ jobs: AWS_SECRET_ACCESS_KEY: foobar_secret ports: - 5000:5000 - strategy: - matrix: - pattern: ["not slow and not network and not clipboard", "slow"] concurrency: # https://github.community/t/concurrecy-not-work-for-push/183068/7 - group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-data_manager-${{ matrix.pattern }} + group: ${{ github.event_name == 'push' && github.run_number || github.ref }}-data_manager cancel-in-progress: true steps: @@ -46,7 +43,7 @@ jobs: - name: Run tests env: PANDAS_DATA_MANAGER: array - PATTERN: ${{ matrix.pattern }} + PATTERN: "not network and not clipboard" PYTEST_WORKERS: "auto" PYTEST_TARGET: pandas run: | diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml index 1cc8188919980..4f3a06faf64af 100644 --- a/.github/workflows/posix.yml +++ b/.github/workflows/posix.yml @@ -26,18 +26,14 @@ jobs: matrix: settings: [ [actions-38-downstream_compat.yaml, "not slow and not network and not clipboard", "", "", "", "", ""], - [actions-38-minimum_versions.yaml, "slow", "", "", "", "", ""], - [actions-38-minimum_versions.yaml, "not slow and not network and not clipboard", "", "", "", "", ""], + [actions-38-minimum_versions.yaml, "not clipboard", "", "", "", "", ""], [actions-38.yaml, "not slow and not network", "language-pack-it xsel", "it_IT.utf8", "it_IT.utf8", "", ""], [actions-38.yaml, "not slow and not network", "language-pack-zh-hans xsel", "zh_CN.utf8", "zh_CN.utf8", "", ""], - [actions-38.yaml, "not slow and not clipboard", "", "", "", "", ""], - [actions-38.yaml, "slow", "", "", "", "", ""], + [actions-38.yaml, "not clipboard", "", "", "", "", ""], [actions-pypy-38.yaml, "not slow and not clipboard", "", "", "", "", "--max-worker-restart 0"], - [actions-39.yaml, "slow", "", "", "", "", ""], - [actions-39.yaml, "not slow and not clipboard", "", "", "", "", ""], + [actions-39.yaml, "not clipboard", "", "", "", "", ""], [actions-310-numpydev.yaml, "not slow and not network", "xsel", "", "", "deprecate", "-W error"], - [actions-310.yaml, "not slow and not clipboard", "", "", "", "", ""], - [actions-310.yaml, "slow", "", "", "", "", ""], + [actions-310.yaml, "not clipboard", "", "", "", "", ""], ] fail-fast: false env:
Backport PR #45437: CI: Don't split slow vs non slow jobs for GHA posix
https://api.github.com/repos/pandas-dev/pandas/pulls/45620
2022-01-25T18:29:47Z
2022-01-25T21:29:43Z
2022-01-25T21:29:43Z
2022-01-25T21:29:43Z
BUG: is_bool_dtype raises AttributeError when checking categorical Series
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 9509b96055255..9c813a4803004 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -31,7 +31,7 @@ Bug fixes - Fixed segfault in :meth:``DataFrame.to_json`` when dumping tz-aware datetimes in Python 3.10 (:issue:`42130`) - Stopped emitting unnecessary ``FutureWarning`` in :meth:`DataFrame.sort_values` with sparse columns (:issue:`45618`) - Fixed window aggregations in :meth:`DataFrame.rolling` and :meth:`Series.rolling` to skip over unused elements (:issue:`45647`) -- +- Bug in :func:`api.types.is_bool_dtype` was raising an ``AttributeError`` when evaluating a categorical :class:`Series` (:issue:`45615`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 109073c7511d0..6776064342db0 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -1319,7 +1319,7 @@ def is_bool_dtype(arr_or_dtype) -> bool: return False if isinstance(dtype, CategoricalDtype): - arr_or_dtype = arr_or_dtype.categories + arr_or_dtype = dtype.categories # now we use the special definition for Index if isinstance(arr_or_dtype, ABCIndex): diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index 165873186aa5a..a32b37fbdd71b 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -562,12 +562,14 @@ def test_is_bool_dtype(): assert not com.is_bool_dtype(int) assert not com.is_bool_dtype(str) assert not com.is_bool_dtype(pd.Series([1, 2])) + assert not com.is_bool_dtype(pd.Series(["a", "b"], dtype="category")) assert not com.is_bool_dtype(np.array(["a", "b"])) assert not com.is_bool_dtype(pd.Index(["a", "b"])) assert not com.is_bool_dtype("Int64") assert com.is_bool_dtype(bool) assert com.is_bool_dtype(np.bool_) + assert com.is_bool_dtype(pd.Series([True, False], dtype="category")) assert com.is_bool_dtype(np.array([True, False])) assert com.is_bool_dtype(pd.Index([True, False]))
- [X] closes #45615 - [X] tests added / passed - [X] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [X] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45616
2022-01-25T14:11:30Z
2022-01-31T13:23:05Z
2022-01-31T13:23:05Z
2022-02-08T16:44:05Z
TST/CI: Mark TestS3 as xfail(strict=False) due to flakiness
diff --git a/pandas/tests/io/parser/test_network.py b/pandas/tests/io/parser/test_network.py index 1e6d7e8ef50ab..d4c3c93a32af0 100644 --- a/pandas/tests/io/parser/test_network.py +++ b/pandas/tests/io/parser/test_network.py @@ -69,14 +69,14 @@ def tips_df(datapath): @pytest.mark.usefixtures("s3_resource") +@pytest.mark.xfail( + reason="CI race condition GH 45433, GH 44584", + raises=FileNotFoundError, + strict=False, +) @td.skip_if_not_us_locale() class TestS3: @td.skip_if_no("s3fs") - @pytest.mark.xfail( - reason="CI race condition GH 45433, GH 44584", - raises=FileNotFoundError, - strict=False, - ) def test_parse_public_s3_bucket(self, tips_df, s3so): # more of an integration test due to the not-public contents portion
- [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them Another example: https://github.com/pandas-dev/pandas/runs/4930469212?check_suite_focus=true#step:10:58
https://api.github.com/repos/pandas-dev/pandas/pulls/45613
2022-01-25T04:35:37Z
2022-01-25T16:46:11Z
2022-01-25T16:46:11Z
2022-01-25T16:46:15Z
DOC: Improve reshaping.rst
diff --git a/doc/source/user_guide/reshaping.rst b/doc/source/user_guide/reshaping.rst index e74272c825e46..f9e68b1b39ddc 100644 --- a/doc/source/user_guide/reshaping.rst +++ b/doc/source/user_guide/reshaping.rst @@ -13,37 +13,12 @@ Reshaping by pivoting DataFrame objects .. image:: ../_static/reshaping_pivot.png -.. ipython:: python - :suppress: - - import pandas._testing as tm - - def unpivot(frame): - N, K = frame.shape - data = { - "value": frame.to_numpy().ravel("F"), - "variable": np.asarray(frame.columns).repeat(N), - "date": np.tile(np.asarray(frame.index), K), - } - columns = ["date", "variable", "value"] - return pd.DataFrame(data, columns=columns) - - df = unpivot(tm.makeTimeDataFrame(3)) - Data is often stored in so-called "stacked" or "record" format: .. ipython:: python - df - - -For the curious here is how the above ``DataFrame`` was created: - -.. code-block:: python - import pandas._testing as tm - def unpivot(frame): N, K = frame.shape data = { @@ -53,14 +28,15 @@ For the curious here is how the above ``DataFrame`` was created: } return pd.DataFrame(data, columns=["date", "variable", "value"]) - df = unpivot(tm.makeTimeDataFrame(3)) + df To select out everything for variable ``A`` we could do: .. ipython:: python - df[df["variable"] == "A"] + filtered = df[df["variable"] == "A"] + filtered But suppose we wish to do time series operations with the variables. A better representation would be where the ``columns`` are the unique variables and an @@ -70,11 +46,12 @@ top level function :func:`~pandas.pivot`): .. ipython:: python - df.pivot(index="date", columns="variable", values="value") + pivoted = df.pivot(index="date", columns="variable", values="value") + pivoted -If the ``values`` argument is omitted, and the input ``DataFrame`` has more than -one column of values which are not used as column or index inputs to ``pivot``, -then the resulting "pivoted" ``DataFrame`` will have :ref:`hierarchical columns +If the ``values`` argument is omitted, and the input :class:`DataFrame` has more than +one column of values which are not used as column or index inputs to :meth:`~DataFrame.pivot`, +then the resulting "pivoted" :class:`DataFrame` will have :ref:`hierarchical columns <advanced.hierarchical>` whose topmost level indicates the respective value column: @@ -84,7 +61,7 @@ column: pivoted = df.pivot(index="date", columns="variable") pivoted -You can then select subsets from the pivoted ``DataFrame``: +You can then select subsets from the pivoted :class:`DataFrame`: .. ipython:: python @@ -108,16 +85,16 @@ Reshaping by stacking and unstacking Closely related to the :meth:`~DataFrame.pivot` method are the related :meth:`~DataFrame.stack` and :meth:`~DataFrame.unstack` methods available on -``Series`` and ``DataFrame``. These methods are designed to work together with -``MultiIndex`` objects (see the section on :ref:`hierarchical indexing +:class:`Series` and :class:`DataFrame`. These methods are designed to work together with +:class:`MultiIndex` objects (see the section on :ref:`hierarchical indexing <advanced.hierarchical>`). Here are essentially what these methods do: -* ``stack``: "pivot" a level of the (possibly hierarchical) column labels, - returning a ``DataFrame`` with an index with a new inner-most level of row +* :meth:`~DataFrame.stack`: "pivot" a level of the (possibly hierarchical) column labels, + returning a :class:`DataFrame` with an index with a new inner-most level of row labels. -* ``unstack``: (inverse operation of ``stack``) "pivot" a level of the +* :meth:`~DataFrame.unstack`: (inverse operation of :meth:`~DataFrame.stack`) "pivot" a level of the (possibly hierarchical) row index to the column axis, producing a reshaped - ``DataFrame`` with a new inner-most level of column labels. + :class:`DataFrame` with a new inner-most level of column labels. .. image:: ../_static/reshaping_unstack.png @@ -139,22 +116,22 @@ from the hierarchical indexing section: df2 = df[:4] df2 -The ``stack`` function "compresses" a level in the ``DataFrame``'s columns to +The :meth:`~DataFrame.stack` function "compresses" a level in the :class:`DataFrame` columns to produce either: -* A ``Series``, in the case of a simple column Index. -* A ``DataFrame``, in the case of a ``MultiIndex`` in the columns. +* A :class:`Series`, in the case of a simple column Index. +* A :class:`DataFrame`, in the case of a :class:`MultiIndex` in the columns. -If the columns have a ``MultiIndex``, you can choose which level to stack. The -stacked level becomes the new lowest level in a ``MultiIndex`` on the columns: +If the columns have a :class:`MultiIndex`, you can choose which level to stack. The +stacked level becomes the new lowest level in a :class:`MultiIndex` on the columns: .. ipython:: python stacked = df2.stack() stacked -With a "stacked" ``DataFrame`` or ``Series`` (having a ``MultiIndex`` as the -``index``), the inverse operation of ``stack`` is ``unstack``, which by default +With a "stacked" :class:`DataFrame` or :class:`Series` (having a :class:`MultiIndex` as the +``index``), the inverse operation of :meth:`~DataFrame.stack` is :meth:`~DataFrame.unstack`, which by default unstacks the **last level**: .. ipython:: python @@ -177,9 +154,9 @@ the level numbers: .. image:: ../_static/reshaping_unstack_0.png -Notice that the ``stack`` and ``unstack`` methods implicitly sort the index -levels involved. Hence a call to ``stack`` and then ``unstack``, or vice versa, -will result in a **sorted** copy of the original ``DataFrame`` or ``Series``: +Notice that the :meth:`~DataFrame.stack` and :meth:`~DataFrame.unstack` methods implicitly sort the index +levels involved. Hence a call to :meth:`~DataFrame.stack` and then :meth:`~DataFrame.unstack`, or vice versa, +will result in a **sorted** copy of the original :class:`DataFrame` or :class:`Series`: .. ipython:: python @@ -188,7 +165,7 @@ will result in a **sorted** copy of the original ``DataFrame`` or ``Series``: df all(df.unstack().stack() == df.sort_index()) -The above code will raise a ``TypeError`` if the call to ``sort_index`` is +The above code will raise a ``TypeError`` if the call to :meth:`~DataFrame.sort_index` is removed. .. _reshaping.stack_multiple: @@ -231,7 +208,7 @@ Missing data These functions are intelligent about handling missing data and do not expect each subgroup within the hierarchical index to have the same set of labels. They also can handle the index being unsorted (but you can make it sorted by -calling ``sort_index``, of course). Here is a more complex example: +calling :meth:`~DataFrame.sort_index`, of course). Here is a more complex example: .. ipython:: python @@ -251,7 +228,7 @@ calling ``sort_index``, of course). Here is a more complex example: df2 = df.iloc[[0, 1, 2, 4, 5, 7]] df2 -As mentioned above, ``stack`` can be called with a ``level`` argument to select +As mentioned above, :meth:`~DataFrame.stack` can be called with a ``level`` argument to select which level in the columns to stack: .. ipython:: python @@ -281,7 +258,7 @@ the value of missing data. With a MultiIndex ~~~~~~~~~~~~~~~~~ -Unstacking when the columns are a ``MultiIndex`` is also careful about doing +Unstacking when the columns are a :class:`MultiIndex` is also careful about doing the right thing: .. ipython:: python @@ -297,7 +274,7 @@ Reshaping by melt .. image:: ../_static/reshaping_melt.png The top-level :func:`~pandas.melt` function and the corresponding :meth:`DataFrame.melt` -are useful to massage a ``DataFrame`` into a format where one or more columns +are useful to massage a :class:`DataFrame` into a format where one or more columns are *identifier variables*, while all other columns, considered *measured variables*, are "unpivoted" to the row axis, leaving just two non-identifier columns, "variable" and "value". The names of those columns can be customized @@ -363,7 +340,7 @@ user-friendly. Combining with stats and GroupBy -------------------------------- -It should be no shock that combining ``pivot`` / ``stack`` / ``unstack`` with +It should be no shock that combining :meth:`~DataFrame.pivot` / :meth:`~DataFrame.stack` / :meth:`~DataFrame.unstack` with GroupBy and the basic Series and DataFrame statistical functions can produce some very expressive and fast data manipulations. @@ -385,8 +362,6 @@ Pivot tables .. _reshaping.pivot: - - While :meth:`~DataFrame.pivot` provides general purpose pivoting with various data types (strings, numerics, etc.), pandas also provides :func:`~pandas.pivot_table` for pivoting with aggregation of numeric data. @@ -437,7 +412,7 @@ We can produce pivot tables from this data very easily: aggfunc=np.sum, ) -The result object is a ``DataFrame`` having potentially hierarchical indexes on the +The result object is a :class:`DataFrame` having potentially hierarchical indexes on the rows and columns. If the ``values`` column name is not given, the pivot table will include all of the data that can be aggregated in an additional level of hierarchy in the columns: @@ -446,21 +421,21 @@ hierarchy in the columns: pd.pivot_table(df, index=["A", "B"], columns=["C"]) -Also, you can use ``Grouper`` for ``index`` and ``columns`` keywords. For detail of ``Grouper``, see :ref:`Grouping with a Grouper specification <groupby.specify>`. +Also, you can use :class:`Grouper` for ``index`` and ``columns`` keywords. For detail of :class:`Grouper`, see :ref:`Grouping with a Grouper specification <groupby.specify>`. .. ipython:: python pd.pivot_table(df, values="D", index=pd.Grouper(freq="M", key="F"), columns="C") You can render a nice output of the table omitting the missing values by -calling ``to_string`` if you wish: +calling :meth:`~DataFrame.to_string` if you wish: .. ipython:: python table = pd.pivot_table(df, index=["A", "B"], columns=["C"]) print(table.to_string(na_rep="")) -Note that ``pivot_table`` is also available as an instance method on DataFrame, +Note that :meth:`~DataFrame.pivot_table` is also available as an instance method on DataFrame, i.e. :meth:`DataFrame.pivot_table`. .. _reshaping.pivot.margins: @@ -468,7 +443,7 @@ Note that ``pivot_table`` is also available as an instance method on DataFrame, Adding margins ~~~~~~~~~~~~~~ -If you pass ``margins=True`` to ``pivot_table``, special ``All`` columns and +If you pass ``margins=True`` to :meth:`~DataFrame.pivot_table`, special ``All`` columns and rows will be added with partial group aggregates across the categories on the rows and columns: @@ -490,7 +465,7 @@ Cross tabulations ----------------- Use :func:`~pandas.crosstab` to compute a cross-tabulation of two (or more) -factors. By default ``crosstab`` computes a frequency table of the factors +factors. By default :func:`~pandas.crosstab` computes a frequency table of the factors unless an array of values and an aggregation function are passed. It takes a number of arguments @@ -509,7 +484,7 @@ It takes a number of arguments Normalize by dividing all values by the sum of values. -Any ``Series`` passed will have their name attributes used unless row or column +Any :class:`Series` passed will have their name attributes used unless row or column names for the cross-tabulation are specified For example: @@ -523,7 +498,7 @@ For example: pd.crosstab(a, [b, c], rownames=["a"], colnames=["b", "c"]) -If ``crosstab`` receives only two Series, it will provide a frequency table. +If :func:`~pandas.crosstab` receives only two Series, it will provide a frequency table. .. ipython:: python @@ -534,8 +509,8 @@ If ``crosstab`` receives only two Series, it will provide a frequency table. pd.crosstab(df["A"], df["B"]) -``crosstab`` can also be implemented -to ``Categorical`` data. +:func:`~pandas.crosstab` can also be implemented +to :class:`Categorical` data. .. ipython:: python @@ -568,9 +543,9 @@ using the ``normalize`` argument: pd.crosstab(df["A"], df["B"], normalize="columns") -``crosstab`` can also be passed a third ``Series`` and an aggregation function -(``aggfunc``) that will be applied to the values of the third ``Series`` within -each group defined by the first two ``Series``: +:func:`~pandas.crosstab` can also be passed a third :class:`Series` and an aggregation function +(``aggfunc``) that will be applied to the values of the third :class:`Series` within +each group defined by the first two :class:`Series`: .. ipython:: python @@ -611,7 +586,7 @@ Alternatively we can specify custom bin-edges: c = pd.cut(ages, bins=[0, 18, 35, 70]) c -If the ``bins`` keyword is an ``IntervalIndex``, then these will be +If the ``bins`` keyword is an :class:`IntervalIndex`, then these will be used to bin the passed data.:: pd.cut([25, 20, 50], bins=c.categories) @@ -622,9 +597,9 @@ used to bin the passed data.:: Computing indicator / dummy variables ------------------------------------- -To convert a categorical variable into a "dummy" or "indicator" ``DataFrame``, -for example a column in a ``DataFrame`` (a ``Series``) which has ``k`` distinct -values, can derive a ``DataFrame`` containing ``k`` columns of 1s and 0s using +To convert a categorical variable into a "dummy" or "indicator" :class:`DataFrame`, +for example a column in a :class:`DataFrame` (a :class:`Series`) which has ``k`` distinct +values, can derive a :class:`DataFrame` containing ``k`` columns of 1s and 0s using :func:`~pandas.get_dummies`: .. ipython:: python @@ -634,7 +609,7 @@ values, can derive a ``DataFrame`` containing ``k`` columns of 1s and 0s using pd.get_dummies(df["key"]) Sometimes it's useful to prefix the column names, for example when merging the result -with the original ``DataFrame``: +with the original :class:`DataFrame`: .. ipython:: python @@ -643,7 +618,7 @@ with the original ``DataFrame``: df[["data1"]].join(dummies) -This function is often used along with discretization functions like ``cut``: +This function is often used along with discretization functions like :func:`~pandas.cut`: .. ipython:: python @@ -656,7 +631,7 @@ This function is often used along with discretization functions like ``cut``: See also :func:`Series.str.get_dummies <pandas.Series.str.get_dummies>`. -:func:`get_dummies` also accepts a ``DataFrame``. By default all categorical +:func:`get_dummies` also accepts a :class:`DataFrame`. By default all categorical variables (categorical in the statistical sense, those with ``object`` or ``categorical`` dtype) are encoded as dummy variables. @@ -677,8 +652,8 @@ Notice that the ``B`` column is still included in the output, it just hasn't been encoded. You can drop ``B`` before calling ``get_dummies`` if you don't want to include it in the output. -As with the ``Series`` version, you can pass values for the ``prefix`` and -``prefix_sep``. By default the column name is used as the prefix, and '_' as +As with the :class:`Series` version, you can pass values for the ``prefix`` and +``prefix_sep``. By default the column name is used as the prefix, and ``_`` as the prefix separator. You can specify ``prefix`` and ``prefix_sep`` in 3 ways: * string: Use the same value for ``prefix`` or ``prefix_sep`` for each column @@ -742,7 +717,7 @@ To encode 1-d values as an enumerated type use :func:`~pandas.factorize`: labels uniques -Note that ``factorize`` is similar to ``numpy.unique``, but differs in its +Note that :func:`~pandas.factorize` is similar to ``numpy.unique``, but differs in its handling of NaN: .. note:: @@ -750,16 +725,12 @@ handling of NaN: because of an ordering bug. See also `here <https://github.com/numpy/numpy/issues/641>`__. -.. code-block:: ipython - - In [1]: x = pd.Series(['A', 'A', np.nan, 'B', 3.14, np.inf]) - In [2]: pd.factorize(x, sort=True) - Out[2]: - (array([ 2, 2, -1, 3, 0, 1]), - Index([3.14, inf, 'A', 'B'], dtype='object')) +.. ipython:: python + :okexcept: - In [3]: np.unique(x, return_inverse=True)[::-1] - Out[3]: (array([3, 3, 0, 4, 1, 2]), array([nan, 3.14, inf, 'A', 'B'], dtype=object)) + ser = pd.Series(['A', 'A', np.nan, 'B', 3.14, np.inf]) + pd.factorize(ser, sort=True) + np.unique(ser, return_inverse=True)[::-1] .. note:: If you just want to handle one column as a categorical variable (like R's factor), @@ -907,13 +878,13 @@ We can 'explode' the ``values`` column, transforming each list-like to a separat df["values"].explode() -You can also explode the column in the ``DataFrame``. +You can also explode the column in the :class:`DataFrame`. .. ipython:: python df.explode("values") -:meth:`Series.explode` will replace empty lists with ``np.nan`` and preserve scalar entries. The dtype of the resulting ``Series`` is always ``object``. +:meth:`Series.explode` will replace empty lists with ``np.nan`` and preserve scalar entries. The dtype of the resulting :class:`Series` is always ``object``. .. ipython:: python diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 157404305c5d9..36eabe93dbd7e 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -631,6 +631,10 @@ def factorize( cut : Discretize continuous-valued array. unique : Find the unique value in an array. + Notes + ----- + Reference :ref:`the user guide <reshaping.factorize>` for more examples. + Examples -------- These examples all show factorize as a top-level method like diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 693ae2f3203fd..d76af1ce42546 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -7792,6 +7792,8 @@ def groupby( For finer-tuned control, see hierarchical indexing documentation along with the related stack/unstack methods. + Reference :ref:`the user guide <reshaping.pivot>` for more examples. + Examples -------- >>> df = pd.DataFrame({'foo': ['one', 'one', 'one', 'two', 'two', @@ -7950,6 +7952,10 @@ def pivot(self, index=None, columns=None, values=None) -> DataFrame: wide_to_long : Wide panel to long format. Less flexible but more user-friendly than melt. + Notes + ----- + Reference :ref:`the user guide <reshaping.pivot>` for more examples. + Examples -------- >>> df = pd.DataFrame({"A": ["foo", "foo", "foo", "foo", "foo", @@ -8106,6 +8112,8 @@ def stack(self, level: Level = -1, dropna: bool = True): vertically on top of each other (in the index of the dataframe). + Reference :ref:`the user guide <reshaping.stacking>` for more examples. + Examples -------- **Single level columns** @@ -8285,6 +8293,8 @@ def explode( result in a np.nan for that row. In addition, the ordering of rows in the output will be non-deterministic when exploding sets. + Reference :ref:`the user guide <reshaping.explode>` for more examples. + Examples -------- >>> df = pd.DataFrame({'A': [[0, 1, 2], 'foo', [], [3, 4]], @@ -8384,6 +8394,10 @@ def unstack(self, level: Level = -1, fill_value=None): DataFrame.stack : Pivot a level of the column labels (inverse operation from `unstack`). + Notes + ----- + Reference :ref:`the user guide <reshaping.stacking>` for more examples. + Examples -------- >>> index = pd.MultiIndex.from_tuples([('one', 'a'), ('one', 'b'), diff --git a/pandas/core/reshape/pivot.py b/pandas/core/reshape/pivot.py index 069f0e5003cdf..b428155e722ff 100644 --- a/pandas/core/reshape/pivot.py +++ b/pandas/core/reshape/pivot.py @@ -589,6 +589,8 @@ def crosstab( In the event that there aren't overlapping indexes an empty DataFrame will be returned. + Reference :ref:`the user guide <reshaping.crosstabulations>` for more examples. + Examples -------- >>> a = np.array(["foo", "foo", "foo", "foo", "bar", "bar", diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 75f005489785a..7f67d3408ae6c 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -857,6 +857,10 @@ def get_dummies( -------- Series.str.get_dummies : Convert Series to dummy codes. + Notes + ----- + Reference :ref:`the user guide <reshaping.dummies>` for more examples. + Examples -------- >>> s = pd.Series(list('abca')) diff --git a/pandas/core/reshape/tile.py b/pandas/core/reshape/tile.py index 8cf94e5e433a6..d8c4f3f3da765 100644 --- a/pandas/core/reshape/tile.py +++ b/pandas/core/reshape/tile.py @@ -145,6 +145,8 @@ def cut( Any NA values will be NA in the result. Out of bounds values will be NA in the resulting Series or Categorical object. + Reference :ref:`the user guide <reshaping.tile.cut>` for more examples. + Examples -------- Discretize into three equal-sized bins. diff --git a/pandas/core/series.py b/pandas/core/series.py index c0080789a277b..596953652d2ff 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4083,6 +4083,8 @@ def explode(self, ignore_index: bool = False) -> Series: result in a np.nan for that row. In addition, the ordering of elements in the output will be non-deterministic when exploding sets. + Reference :ref:`the user guide <reshaping.explode>` for more examples. + Examples -------- >>> s = pd.Series([[1, 2, 3], 'foo', [], [3, 4]]) @@ -4132,6 +4134,10 @@ def unstack(self, level=-1, fill_value=None) -> DataFrame: DataFrame Unstacked Series. + Notes + ----- + Reference :ref:`the user guide <reshaping.stacking>` for more examples. + Examples -------- >>> s = pd.Series([1, 2, 3, 4], diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py index 3547b75eac807..35ee1c7a4ddbb 100644 --- a/pandas/core/shared_docs.py +++ b/pandas/core/shared_docs.py @@ -195,6 +195,10 @@ DataFrame.explode : Explode a DataFrame from list-like columns to long format. +Notes +----- +Reference :ref:`the user guide <reshaping.melt>` for more examples. + Examples -------- >>> df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c'},
* Add more sphinx references * Links function docs back to `reshaping.rst` * Convert `code-block` to `ipython`
https://api.github.com/repos/pandas-dev/pandas/pulls/45612
2022-01-25T04:29:53Z
2022-01-28T00:34:01Z
2022-01-28T00:34:01Z
2022-01-28T00:54:31Z
TYP: return type of read_csv/table
diff --git a/pandas/io/parsers/readers.py b/pandas/io/parsers/readers.py index c5b84dd18ec13..7684fa32fbd66 100644 --- a/pandas/io/parsers/readers.py +++ b/pandas/io/parsers/readers.py @@ -11,7 +11,10 @@ IO, Any, Callable, + Literal, NamedTuple, + Sequence, + overload, ) import warnings @@ -538,7 +541,7 @@ def _validate_names(names): def _read( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], kwds -): +) -> DataFrame | TextFileReader: """Generic reader of line files.""" # if we pass a date_parser and parse_dates=False, we should not parse the # dates GH#44366 @@ -579,6 +582,246 @@ def _read( return parser.read(nrows) +# iterator=True -> TextFileReader +@overload +def read_csv( + filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], + *, + sep: str | None | lib.NoDefault = ..., + delimiter: str | None | lib.NoDefault = ..., + header: int | Sequence[int] | None | Literal["infer"] = ..., + names=..., + index_col=..., + usecols=..., + squeeze: bool | None = ..., + prefix: str | lib.NoDefault = ..., + mangle_dupe_cols: bool = ..., + dtype: DtypeArg | None = ..., + engine: CSVEngine | None = ..., + converters=..., + true_values=..., + false_values=..., + skipinitialspace: bool = ..., + skiprows=..., + skipfooter: int = ..., + nrows: int | None = ..., + na_values=..., + keep_default_na: bool = ..., + na_filter: bool = ..., + verbose: bool = ..., + skip_blank_lines: bool = ..., + parse_dates=..., + infer_datetime_format: bool = ..., + keep_date_col: bool = ..., + date_parser=..., + dayfirst: bool = ..., + cache_dates: bool = ..., + iterator: Literal[True], + chunksize: int | None = ..., + compression: CompressionOptions = ..., + thousands: str | None = ..., + decimal: str = ..., + lineterminator: str | None = ..., + quotechar: str = ..., + quoting: int = ..., + doublequote: bool = ..., + escapechar: str | None = ..., + comment: str | None = ..., + encoding: str | None = ..., + encoding_errors: str | None = ..., + dialect=..., + error_bad_lines: bool | None = ..., + warn_bad_lines: bool | None = ..., + on_bad_lines=..., + delim_whitespace: bool = ..., + low_memory=..., + memory_map: bool = ..., + float_precision: Literal["high", "legacy"] | None = ..., + storage_options: StorageOptions = ..., +) -> TextFileReader: + ... + + +# chunksize=int -> TextFileReader +@overload +def read_csv( + filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], + *, + sep: str | None | lib.NoDefault = ..., + delimiter: str | None | lib.NoDefault = ..., + header: int | Sequence[int] | None | Literal["infer"] = ..., + names=..., + index_col=..., + usecols=..., + squeeze: bool | None = ..., + prefix: str | lib.NoDefault = ..., + mangle_dupe_cols: bool = ..., + dtype: DtypeArg | None = ..., + engine: CSVEngine | None = ..., + converters=..., + true_values=..., + false_values=..., + skipinitialspace: bool = ..., + skiprows=..., + skipfooter: int = ..., + nrows: int | None = ..., + na_values=..., + keep_default_na: bool = ..., + na_filter: bool = ..., + verbose: bool = ..., + skip_blank_lines: bool = ..., + parse_dates=..., + infer_datetime_format: bool = ..., + keep_date_col: bool = ..., + date_parser=..., + dayfirst: bool = ..., + cache_dates: bool = ..., + iterator: bool = ..., + chunksize: int, + compression: CompressionOptions = ..., + thousands: str | None = ..., + decimal: str = ..., + lineterminator: str | None = ..., + quotechar: str = ..., + quoting: int = ..., + doublequote: bool = ..., + escapechar: str | None = ..., + comment: str | None = ..., + encoding: str | None = ..., + encoding_errors: str | None = ..., + dialect=..., + error_bad_lines: bool | None = ..., + warn_bad_lines: bool | None = ..., + on_bad_lines=..., + delim_whitespace: bool = ..., + low_memory=..., + memory_map: bool = ..., + float_precision: Literal["high", "legacy"] | None = ..., + storage_options: StorageOptions = ..., +) -> TextFileReader: + ... + + +# default case -> DataFrame +@overload +def read_csv( + filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], + *, + sep: str | None | lib.NoDefault = ..., + delimiter: str | None | lib.NoDefault = ..., + header: int | Sequence[int] | None | Literal["infer"] = ..., + names=..., + index_col=..., + usecols=..., + squeeze: bool | None = ..., + prefix: str | lib.NoDefault = ..., + mangle_dupe_cols: bool = ..., + dtype: DtypeArg | None = ..., + engine: CSVEngine | None = ..., + converters=..., + true_values=..., + false_values=..., + skipinitialspace: bool = ..., + skiprows=..., + skipfooter: int = ..., + nrows: int | None = ..., + na_values=..., + keep_default_na: bool = ..., + na_filter: bool = ..., + verbose: bool = ..., + skip_blank_lines: bool = ..., + parse_dates=..., + infer_datetime_format: bool = ..., + keep_date_col: bool = ..., + date_parser=..., + dayfirst: bool = ..., + cache_dates: bool = ..., + iterator: Literal[False] = ..., + chunksize: None = ..., + compression: CompressionOptions = ..., + thousands: str | None = ..., + decimal: str = ..., + lineterminator: str | None = ..., + quotechar: str = ..., + quoting: int = ..., + doublequote: bool = ..., + escapechar: str | None = ..., + comment: str | None = ..., + encoding: str | None = ..., + encoding_errors: str | None = ..., + dialect=..., + error_bad_lines: bool | None = ..., + warn_bad_lines: bool | None = ..., + on_bad_lines=..., + delim_whitespace: bool = ..., + low_memory=..., + memory_map: bool = ..., + float_precision: Literal["high", "legacy"] | None = ..., + storage_options: StorageOptions = ..., +) -> DataFrame: + ... + + +# Unions -> DataFrame | TextFileReader +@overload +def read_csv( + filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], + *, + sep: str | None | lib.NoDefault = ..., + delimiter: str | None | lib.NoDefault = ..., + header: int | Sequence[int] | None | Literal["infer"] = ..., + names=..., + index_col=..., + usecols=..., + squeeze: bool | None = ..., + prefix: str | lib.NoDefault = ..., + mangle_dupe_cols: bool = ..., + dtype: DtypeArg | None = ..., + engine: CSVEngine | None = ..., + converters=..., + true_values=..., + false_values=..., + skipinitialspace: bool = ..., + skiprows=..., + skipfooter: int = ..., + nrows: int | None = ..., + na_values=..., + keep_default_na: bool = ..., + na_filter: bool = ..., + verbose: bool = ..., + skip_blank_lines: bool = ..., + parse_dates=..., + infer_datetime_format: bool = ..., + keep_date_col: bool = ..., + date_parser=..., + dayfirst: bool = ..., + cache_dates: bool = ..., + iterator: bool = ..., + chunksize: int | None = ..., + compression: CompressionOptions = ..., + thousands: str | None = ..., + decimal: str = ..., + lineterminator: str | None = ..., + quotechar: str = ..., + quoting: int = ..., + doublequote: bool = ..., + escapechar: str | None = ..., + comment: str | None = ..., + encoding: str | None = ..., + encoding_errors: str | None = ..., + dialect=..., + error_bad_lines: bool | None = ..., + warn_bad_lines: bool | None = ..., + on_bad_lines=..., + delim_whitespace: bool = ..., + low_memory=..., + memory_map: bool = ..., + float_precision: Literal["high", "legacy"] | None = ..., + storage_options: StorageOptions = ..., +) -> DataFrame | TextFileReader: + ... + + @deprecate_nonkeyword_arguments( version=None, allowed_args=["filepath_or_buffer"], stacklevel=3 ) @@ -593,68 +836,68 @@ def _read( ) def read_csv( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], - sep=lib.no_default, - delimiter=None, + sep: str | None | lib.NoDefault = lib.no_default, + delimiter: str | None | lib.NoDefault = None, # Column and Index Locations and Names - header="infer", + header: int | Sequence[int] | None | Literal["infer"] = "infer", names=lib.no_default, index_col=None, usecols=None, - squeeze=None, - prefix=lib.no_default, - mangle_dupe_cols=True, + squeeze: bool | None = None, + prefix: str | lib.NoDefault = lib.no_default, + mangle_dupe_cols: bool = True, # General Parsing Configuration dtype: DtypeArg | None = None, engine: CSVEngine | None = None, converters=None, true_values=None, false_values=None, - skipinitialspace=False, + skipinitialspace: bool = False, skiprows=None, - skipfooter=0, - nrows=None, + skipfooter: int = 0, + nrows: int | None = None, # NA and Missing Data Handling na_values=None, - keep_default_na=True, - na_filter=True, - verbose=False, - skip_blank_lines=True, + keep_default_na: bool = True, + na_filter: bool = True, + verbose: bool = False, + skip_blank_lines: bool = True, # Datetime Handling parse_dates=None, - infer_datetime_format=False, - keep_date_col=False, + infer_datetime_format: bool = False, + keep_date_col: bool = False, date_parser=None, - dayfirst=False, - cache_dates=True, + dayfirst: bool = False, + cache_dates: bool = True, # Iteration - iterator=False, - chunksize=None, + iterator: bool = False, + chunksize: int | None = None, # Quoting, Compression, and File Format compression: CompressionOptions = "infer", - thousands=None, + thousands: str | None = None, decimal: str = ".", - lineterminator=None, - quotechar='"', - quoting=csv.QUOTE_MINIMAL, - doublequote=True, - escapechar=None, - comment=None, - encoding=None, + lineterminator: str | None = None, + quotechar: str = '"', + quoting: int = csv.QUOTE_MINIMAL, + doublequote: bool = True, + escapechar: str | None = None, + comment: str | None = None, + encoding: str | None = None, encoding_errors: str | None = "strict", dialect=None, # Error Handling - error_bad_lines=None, - warn_bad_lines=None, + error_bad_lines: bool | None = None, + warn_bad_lines: bool | None = None, # TODO(2.0): set on_bad_lines to "error". # See _refine_defaults_read comment for why we do this. on_bad_lines=None, # Internal - delim_whitespace=False, + delim_whitespace: bool = False, low_memory=_c_parser_defaults["low_memory"], - memory_map=False, - float_precision=None, + memory_map: bool = False, + float_precision: Literal["high", "legacy"] | None = None, storage_options: StorageOptions = None, -): +) -> DataFrame | TextFileReader: # locals() should never be modified kwds = locals().copy() del kwds["filepath_or_buffer"] @@ -678,6 +921,246 @@ def read_csv( return _read(filepath_or_buffer, kwds) +# iterator=True -> TextFileReader +@overload +def read_table( + filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], + *, + sep: str | None | lib.NoDefault = ..., + delimiter: str | None | lib.NoDefault = ..., + header: int | Sequence[int] | None | Literal["infer"] = ..., + names=..., + index_col=..., + usecols=..., + squeeze: bool | None = ..., + prefix: str | lib.NoDefault = ..., + mangle_dupe_cols: bool = ..., + dtype: DtypeArg | None = ..., + engine: CSVEngine | None = ..., + converters=..., + true_values=..., + false_values=..., + skipinitialspace: bool = ..., + skiprows=..., + skipfooter: int = ..., + nrows: int | None = ..., + na_values=..., + keep_default_na: bool = ..., + na_filter: bool = ..., + verbose: bool = ..., + skip_blank_lines: bool = ..., + parse_dates=..., + infer_datetime_format: bool = ..., + keep_date_col: bool = ..., + date_parser=..., + dayfirst: bool = ..., + cache_dates: bool = ..., + iterator: Literal[True], + chunksize: int | None = ..., + compression: CompressionOptions = ..., + thousands: str | None = ..., + decimal: str = ..., + lineterminator: str | None = ..., + quotechar: str = ..., + quoting: int = ..., + doublequote: bool = ..., + escapechar: str | None = ..., + comment: str | None = ..., + encoding: str | None = ..., + encoding_errors: str | None = ..., + dialect=..., + error_bad_lines: bool | None = ..., + warn_bad_lines: bool | None = ..., + on_bad_lines=..., + delim_whitespace=..., + low_memory=..., + memory_map: bool = ..., + float_precision: str | None = ..., + storage_options: StorageOptions = ..., +) -> TextFileReader: + ... + + +# chunksize=int -> TextFileReader +@overload +def read_table( + filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], + *, + sep: str | None | lib.NoDefault = ..., + delimiter: str | None | lib.NoDefault = ..., + header: int | Sequence[int] | None | Literal["infer"] = ..., + names=..., + index_col=..., + usecols=..., + squeeze: bool | None = ..., + prefix: str | lib.NoDefault = ..., + mangle_dupe_cols: bool = ..., + dtype: DtypeArg | None = ..., + engine: CSVEngine | None = ..., + converters=..., + true_values=..., + false_values=..., + skipinitialspace: bool = ..., + skiprows=..., + skipfooter: int = ..., + nrows: int | None = ..., + na_values=..., + keep_default_na: bool = ..., + na_filter: bool = ..., + verbose: bool = ..., + skip_blank_lines: bool = ..., + parse_dates=..., + infer_datetime_format: bool = ..., + keep_date_col: bool = ..., + date_parser=..., + dayfirst: bool = ..., + cache_dates: bool = ..., + iterator: bool = ..., + chunksize: int, + compression: CompressionOptions = ..., + thousands: str | None = ..., + decimal: str = ..., + lineterminator: str | None = ..., + quotechar: str = ..., + quoting: int = ..., + doublequote: bool = ..., + escapechar: str | None = ..., + comment: str | None = ..., + encoding: str | None = ..., + encoding_errors: str | None = ..., + dialect=..., + error_bad_lines: bool | None = ..., + warn_bad_lines: bool | None = ..., + on_bad_lines=..., + delim_whitespace=..., + low_memory=..., + memory_map: bool = ..., + float_precision: str | None = ..., + storage_options: StorageOptions = ..., +) -> TextFileReader: + ... + + +# default -> DataFrame +@overload +def read_table( + filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], + *, + sep: str | None | lib.NoDefault = ..., + delimiter: str | None | lib.NoDefault = ..., + header: int | Sequence[int] | None | Literal["infer"] = ..., + names=..., + index_col=..., + usecols=..., + squeeze: bool | None = ..., + prefix: str | lib.NoDefault = ..., + mangle_dupe_cols: bool = ..., + dtype: DtypeArg | None = ..., + engine: CSVEngine | None = ..., + converters=..., + true_values=..., + false_values=..., + skipinitialspace: bool = ..., + skiprows=..., + skipfooter: int = ..., + nrows: int | None = ..., + na_values=..., + keep_default_na: bool = ..., + na_filter: bool = ..., + verbose: bool = ..., + skip_blank_lines: bool = ..., + parse_dates=..., + infer_datetime_format: bool = ..., + keep_date_col: bool = ..., + date_parser=..., + dayfirst: bool = ..., + cache_dates: bool = ..., + iterator: Literal[False] = ..., + chunksize: None = ..., + compression: CompressionOptions = ..., + thousands: str | None = ..., + decimal: str = ..., + lineterminator: str | None = ..., + quotechar: str = ..., + quoting: int = ..., + doublequote: bool = ..., + escapechar: str | None = ..., + comment: str | None = ..., + encoding: str | None = ..., + encoding_errors: str | None = ..., + dialect=..., + error_bad_lines: bool | None = ..., + warn_bad_lines: bool | None = ..., + on_bad_lines=..., + delim_whitespace=..., + low_memory=..., + memory_map: bool = ..., + float_precision: str | None = ..., + storage_options: StorageOptions = ..., +) -> DataFrame: + ... + + +# Unions -> DataFrame | TextFileReader +@overload +def read_table( + filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], + *, + sep: str | None | lib.NoDefault = ..., + delimiter: str | None | lib.NoDefault = ..., + header: int | Sequence[int] | None | Literal["infer"] = ..., + names=..., + index_col=..., + usecols=..., + squeeze: bool | None = ..., + prefix: str | lib.NoDefault = ..., + mangle_dupe_cols: bool = ..., + dtype: DtypeArg | None = ..., + engine: CSVEngine | None = ..., + converters=..., + true_values=..., + false_values=..., + skipinitialspace: bool = ..., + skiprows=..., + skipfooter: int = ..., + nrows: int | None = ..., + na_values=..., + keep_default_na: bool = ..., + na_filter: bool = ..., + verbose: bool = ..., + skip_blank_lines: bool = ..., + parse_dates=..., + infer_datetime_format: bool = ..., + keep_date_col: bool = ..., + date_parser=..., + dayfirst: bool = ..., + cache_dates: bool = ..., + iterator: bool = ..., + chunksize: int | None = ..., + compression: CompressionOptions = ..., + thousands: str | None = ..., + decimal: str = ..., + lineterminator: str | None = ..., + quotechar: str = ..., + quoting: int = ..., + doublequote: bool = ..., + escapechar: str | None = ..., + comment: str | None = ..., + encoding: str | None = ..., + encoding_errors: str | None = ..., + dialect=..., + error_bad_lines: bool | None = ..., + warn_bad_lines: bool | None = ..., + on_bad_lines=..., + delim_whitespace=..., + low_memory=..., + memory_map: bool = ..., + float_precision: str | None = ..., + storage_options: StorageOptions = ..., +) -> DataFrame | TextFileReader: + ... + + @deprecate_nonkeyword_arguments( version=None, allowed_args=["filepath_or_buffer"], stacklevel=3 ) @@ -692,68 +1175,68 @@ def read_csv( ) def read_table( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], - sep=lib.no_default, - delimiter=None, + sep: str | None | lib.NoDefault = lib.no_default, + delimiter: str | None | lib.NoDefault = None, # Column and Index Locations and Names - header="infer", + header: int | Sequence[int] | None | Literal["infer"] = "infer", names=lib.no_default, index_col=None, usecols=None, - squeeze=None, - prefix=lib.no_default, - mangle_dupe_cols=True, + squeeze: bool | None = None, + prefix: str | lib.NoDefault = lib.no_default, + mangle_dupe_cols: bool = True, # General Parsing Configuration dtype: DtypeArg | None = None, engine: CSVEngine | None = None, converters=None, true_values=None, false_values=None, - skipinitialspace=False, + skipinitialspace: bool = False, skiprows=None, - skipfooter=0, - nrows=None, + skipfooter: int = 0, + nrows: int | None = None, # NA and Missing Data Handling na_values=None, - keep_default_na=True, - na_filter=True, - verbose=False, - skip_blank_lines=True, + keep_default_na: bool = True, + na_filter: bool = True, + verbose: bool = False, + skip_blank_lines: bool = True, # Datetime Handling parse_dates=False, - infer_datetime_format=False, - keep_date_col=False, + infer_datetime_format: bool = False, + keep_date_col: bool = False, date_parser=None, - dayfirst=False, - cache_dates=True, + dayfirst: bool = False, + cache_dates: bool = True, # Iteration - iterator=False, - chunksize=None, + iterator: bool = False, + chunksize: int | None = None, # Quoting, Compression, and File Format compression: CompressionOptions = "infer", - thousands=None, + thousands: str | None = None, decimal: str = ".", - lineterminator=None, - quotechar='"', - quoting=csv.QUOTE_MINIMAL, - doublequote=True, - escapechar=None, - comment=None, - encoding=None, + lineterminator: str | None = None, + quotechar: str = '"', + quoting: int = csv.QUOTE_MINIMAL, + doublequote: bool = True, + escapechar: str | None = None, + comment: str | None = None, + encoding: str | None = None, encoding_errors: str | None = "strict", dialect=None, # Error Handling - error_bad_lines=None, - warn_bad_lines=None, + error_bad_lines: bool | None = None, + warn_bad_lines: bool | None = None, # TODO(2.0): set on_bad_lines to "error". # See _refine_defaults_read comment for why we do this. on_bad_lines=None, # Internal delim_whitespace=False, low_memory=_c_parser_defaults["low_memory"], - memory_map=False, - float_precision=None, + memory_map: bool = False, + float_precision: str | None = None, storage_options: StorageOptions = None, -): +) -> DataFrame | TextFileReader: # locals() should never be modified kwds = locals().copy() del kwds["filepath_or_buffer"] @@ -782,8 +1265,8 @@ def read_table( ) def read_fwf( filepath_or_buffer: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str], - colspecs: list[tuple[int, int]] | str | None = "infer", - widths: list[int] | None = None, + colspecs: Sequence[tuple[int, int]] | str | None = "infer", + widths: Sequence[int] | None = None, infer_nrows: int = 100, **kwds, ) -> DataFrame | TextFileReader: @@ -930,12 +1413,12 @@ def __init__( self.handles: IOHandles | None = None self._engine = self._make_engine(f, self.engine) - def close(self): + def close(self) -> None: if self.handles is not None: self.handles.close() self._engine.close() - def _get_options_with_defaults(self, engine): + def _get_options_with_defaults(self, engine: CSVEngine) -> dict[str, Any]: kwds = self.orig_options options = {} @@ -1002,7 +1485,7 @@ def _get_options_with_defaults(self, engine): return options - def _check_file_or_buffer(self, f, engine): + def _check_file_or_buffer(self, f, engine: CSVEngine) -> None: # see gh-16530 if is_file_like(f) and engine != "c" and not hasattr(f, "__iter__"): # The C engine doesn't need the file-like to have the "__iter__" @@ -1013,7 +1496,9 @@ def _check_file_or_buffer(self, f, engine): "The 'python' engine cannot iterate through this file buffer." ) - def _clean_options(self, options, engine): + def _clean_options( + self, options: dict[str, Any], engine: CSVEngine + ) -> tuple[dict[str, Any], CSVEngine]: result = options.copy() fallback_reason = None @@ -1180,7 +1665,7 @@ def _clean_options(self, options, engine): return result, engine - def __next__(self): + def __next__(self) -> DataFrame: try: return self.get_chunk() except StopIteration: @@ -1191,7 +1676,7 @@ def _make_engine( self, f: FilePath | ReadCsvBuffer[bytes] | ReadCsvBuffer[str] | list | IO, engine: CSVEngine = "c", - ): + ) -> ParserBase: mapping: dict[str, type[ParserBase]] = { "c": CParserWrapper, "python": PythonParser, @@ -1232,20 +1717,28 @@ def _make_engine( self.handles.close() raise - def _failover_to_python(self): + def _failover_to_python(self) -> None: raise AbstractMethodError(self) - def read(self, nrows=None): + def read(self, nrows: int | None = None) -> DataFrame: if self.engine == "pyarrow": try: - df = self._engine.read() + # error: "ParserBase" has no attribute "read" + df = self._engine.read() # type: ignore[attr-defined] except Exception: self.close() raise else: nrows = validate_integer("nrows", nrows) try: - index, columns, col_dict = self._engine.read(nrows) + # error: "ParserBase" has no attribute "read" + ( + index, + columns, + col_dict, + ) = self._engine.read( # type: ignore[attr-defined] + nrows + ) except Exception: self.close() raise @@ -1268,7 +1761,7 @@ def read(self, nrows=None): return df.squeeze("columns").copy() return df - def get_chunk(self, size=None): + def get_chunk(self, size: int | None = None) -> DataFrame: if size is None: size = self.chunksize if self.nrows is not None: @@ -1277,10 +1770,10 @@ def get_chunk(self, size=None): size = min(size, self.nrows - self._currow) return self.read(nrows=size) - def __enter__(self): + def __enter__(self) -> TextFileReader: return self - def __exit__(self, exc_type, exc_value, traceback): + def __exit__(self, exc_type, exc_value, traceback) -> None: self.close() @@ -1421,15 +1914,15 @@ def _stringify_na_values(na_values): def _refine_defaults_read( dialect: str | csv.Dialect, - delimiter: str | object, + delimiter: str | None | lib.NoDefault, delim_whitespace: bool, engine: CSVEngine | None, - sep: str | object, + sep: str | None | lib.NoDefault, error_bad_lines: bool | None, warn_bad_lines: bool | None, on_bad_lines: str | Callable | None, - names: ArrayLike | None | object, - prefix: str | None | object, + names: ArrayLike | None | lib.NoDefault, + prefix: str | None | lib.NoDefault, defaults: dict[str, Any], ): """Validate/refine default values of input parameters of read_csv, read_table.
Return type of read_csv/table (union for now, overload can be used when positional keywords are deprecated), type TextFileReader, and type some random arguments of read_csv/table
https://api.github.com/repos/pandas-dev/pandas/pulls/45610
2022-01-25T02:34:26Z
2022-03-02T01:55:38Z
2022-03-02T01:55:38Z
2022-03-09T02:56:04Z
CLN: Remove Python 2 compat in np_datetime.c
diff --git a/pandas/_libs/tslibs/src/datetime/np_datetime.c b/pandas/_libs/tslibs/src/datetime/np_datetime.c index 0efed210a7fdf..8f59f53a555d8 100644 --- a/pandas/_libs/tslibs/src/datetime/np_datetime.c +++ b/pandas/_libs/tslibs/src/datetime/np_datetime.c @@ -27,10 +27,6 @@ This file is derived from NumPy 1.7. See NUMPY_LICENSE.txt #include <numpy/ndarraytypes.h> #include "np_datetime.h" -#if PY_MAJOR_VERSION >= 3 -#define PyInt_AsLong PyLong_AsLong -#endif // PyInt_AsLong - const npy_datetimestruct _NS_MIN_DTS = { 1677, 9, 21, 0, 12, 43, 145224, 193000, 0}; const npy_datetimestruct _NS_MAX_DTS = { @@ -330,9 +326,9 @@ int convert_pydatetime_to_datetimestruct(PyObject *dtobj, out->month = 1; out->day = 1; - out->year = PyInt_AsLong(PyObject_GetAttrString(obj, "year")); - out->month = PyInt_AsLong(PyObject_GetAttrString(obj, "month")); - out->day = PyInt_AsLong(PyObject_GetAttrString(obj, "day")); + out->year = PyLong_AsLong(PyObject_GetAttrString(obj, "year")); + out->month = PyLong_AsLong(PyObject_GetAttrString(obj, "month")); + out->day = PyLong_AsLong(PyObject_GetAttrString(obj, "day")); // TODO(anyone): If we can get PyDateTime_IMPORT to work, we could use // PyDateTime_Check here, and less verbose attribute lookups. @@ -345,10 +341,10 @@ int convert_pydatetime_to_datetimestruct(PyObject *dtobj, return 0; } - out->hour = PyInt_AsLong(PyObject_GetAttrString(obj, "hour")); - out->min = PyInt_AsLong(PyObject_GetAttrString(obj, "minute")); - out->sec = PyInt_AsLong(PyObject_GetAttrString(obj, "second")); - out->us = PyInt_AsLong(PyObject_GetAttrString(obj, "microsecond")); + out->hour = PyLong_AsLong(PyObject_GetAttrString(obj, "hour")); + out->min = PyLong_AsLong(PyObject_GetAttrString(obj, "minute")); + out->sec = PyLong_AsLong(PyObject_GetAttrString(obj, "second")); + out->us = PyLong_AsLong(PyObject_GetAttrString(obj, "microsecond")); /* Apply the time zone offset if datetime obj is tz-aware */ if (PyObject_HasAttrString((PyObject*)obj, "tzinfo")) { @@ -384,7 +380,7 @@ int convert_pydatetime_to_datetimestruct(PyObject *dtobj, Py_DECREF(tmp); return -1; } - seconds_offset = PyInt_AsLong(tmp_int); + seconds_offset = PyLong_AsLong(tmp_int); if (seconds_offset == -1 && PyErr_Occurred()) { Py_DECREF(tmp_int); Py_DECREF(tmp);
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45606
2022-01-24T23:48:55Z
2022-01-26T01:40:29Z
2022-01-26T01:40:29Z
2022-01-26T01:59:47Z
Backport PR #45576 on branch 1.4.x (CI: Use xsel instead of xclip for numpydev)
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml index 135ca0703de8b..1cc8188919980 100644 --- a/.github/workflows/posix.yml +++ b/.github/workflows/posix.yml @@ -35,7 +35,7 @@ jobs: [actions-pypy-38.yaml, "not slow and not clipboard", "", "", "", "", "--max-worker-restart 0"], [actions-39.yaml, "slow", "", "", "", "", ""], [actions-39.yaml, "not slow and not clipboard", "", "", "", "", ""], - [actions-310-numpydev.yaml, "not slow and not network", "xclip", "", "", "deprecate", "-W error"], + [actions-310-numpydev.yaml, "not slow and not network", "xsel", "", "", "deprecate", "-W error"], [actions-310.yaml, "not slow and not clipboard", "", "", "", "", ""], [actions-310.yaml, "slow", "", "", "", "", ""], ] diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py index 40b2eb1f4114b..4a53705193e99 100644 --- a/pandas/tests/io/test_clipboard.py +++ b/pandas/tests/io/test_clipboard.py @@ -307,6 +307,11 @@ def test_round_trip_valid_encodings(self, enc, df): @pytest.mark.single @pytest.mark.clipboard @pytest.mark.parametrize("data", ["\U0001f44d...", "Ωœ∑´...", "abcd..."]) +@pytest.mark.xfail( + reason="Flaky test in multi-process CI environment: GH 44584", + raises=AssertionError, + strict=False, +) def test_raw_roundtrip(data): # PR #25040 wide unicode wasn't copied correctly on PY3 on windows clipboard_set(data)
Backport PR #45576: CI: Use xsel instead of xclip for numpydev
https://api.github.com/repos/pandas-dev/pandas/pulls/45604
2022-01-24T22:27:49Z
2022-01-25T14:20:48Z
2022-01-25T14:20:48Z
2022-01-25T14:20:49Z
Backport PR #45597 on branch 1.4.x (CI: Fix failing CI for test_alignment_deprecation_many_inputs)
diff --git a/pandas/compat/numpy/__init__.py b/pandas/compat/numpy/__init__.py index c6666551ffad6..623c5fbecc48c 100644 --- a/pandas/compat/numpy/__init__.py +++ b/pandas/compat/numpy/__init__.py @@ -9,7 +9,7 @@ np_version_under1p19 = _nlv < Version("1.19") np_version_under1p20 = _nlv < Version("1.20") np_version_under1p22 = _nlv < Version("1.22") -np_version_is1p22 = _nlv == Version("1.22") +np_version_gte1p22 = _nlv >= Version("1.22") is_numpy_dev = _nlv.dev is not None _min_numpy_ver = "1.18.5" diff --git a/pandas/tests/frame/test_ufunc.py b/pandas/tests/frame/test_ufunc.py index bcfcc084bd302..79e9b1f34978d 100644 --- a/pandas/tests/frame/test_ufunc.py +++ b/pandas/tests/frame/test_ufunc.py @@ -3,7 +3,7 @@ import numpy as np import pytest -from pandas.compat.numpy import np_version_is1p22 +from pandas.compat.numpy import np_version_gte1p22 import pandas.util._test_decorators as td import pandas as pd @@ -262,7 +262,7 @@ def test_alignment_deprecation_many_inputs(request): vectorize, ) - if np_version_is1p22: + if np_version_gte1p22: mark = pytest.mark.xfail( reason="ufunc 'my_ufunc' did not contain a loop with signature matching " "types",
Backport PR #45597: CI: Fix failing CI for test_alignment_deprecation_many_inputs
https://api.github.com/repos/pandas-dev/pandas/pulls/45600
2022-01-24T20:43:17Z
2022-01-24T21:57:50Z
2022-01-24T21:57:50Z
2022-01-24T21:57:50Z
CI: Fix failing CI for test_alignment_deprecation_many_inputs
diff --git a/pandas/compat/numpy/__init__.py b/pandas/compat/numpy/__init__.py index c6666551ffad6..623c5fbecc48c 100644 --- a/pandas/compat/numpy/__init__.py +++ b/pandas/compat/numpy/__init__.py @@ -9,7 +9,7 @@ np_version_under1p19 = _nlv < Version("1.19") np_version_under1p20 = _nlv < Version("1.20") np_version_under1p22 = _nlv < Version("1.22") -np_version_is1p22 = _nlv == Version("1.22") +np_version_gte1p22 = _nlv >= Version("1.22") is_numpy_dev = _nlv.dev is not None _min_numpy_ver = "1.18.5" diff --git a/pandas/tests/frame/test_ufunc.py b/pandas/tests/frame/test_ufunc.py index bcfcc084bd302..79e9b1f34978d 100644 --- a/pandas/tests/frame/test_ufunc.py +++ b/pandas/tests/frame/test_ufunc.py @@ -3,7 +3,7 @@ import numpy as np import pytest -from pandas.compat.numpy import np_version_is1p22 +from pandas.compat.numpy import np_version_gte1p22 import pandas.util._test_decorators as td import pandas as pd @@ -262,7 +262,7 @@ def test_alignment_deprecation_many_inputs(request): vectorize, ) - if np_version_is1p22: + if np_version_gte1p22: mark = pytest.mark.xfail( reason="ufunc 'my_ufunc' did not contain a loop with signature matching " "types",
xref https://github.com/pandas-dev/pandas/issues/45182 https://github.com/pandas-dev/pandas/pull/45179 was a little too strict since numpy just had a point release. This should (hopefully) get us to green @jbrockmendel
https://api.github.com/repos/pandas-dev/pandas/pulls/45597
2022-01-24T18:49:40Z
2022-01-24T20:43:06Z
2022-01-24T20:43:06Z
2022-02-10T17:26:10Z
REF: share IntegerArray/FloatingArray coerce_to_array
diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py index 82dc7e4454227..d55aef953b5b5 100644 --- a/pandas/core/arrays/floating.py +++ b/pandas/core/arrays/floating.py @@ -2,20 +2,9 @@ import numpy as np -from pandas._libs import ( - lib, - missing as libmissing, -) from pandas._typing import DtypeObj from pandas.util._decorators import cache_readonly -from pandas.core.dtypes.common import ( - is_bool_dtype, - is_float_dtype, - is_integer_dtype, - is_object_dtype, - is_string_dtype, -) from pandas.core.dtypes.dtypes import register_extension_dtype from pandas.core.arrays.numeric import ( @@ -34,6 +23,8 @@ class FloatingDtype(NumericDtype): The attributes name & type are set when these subclasses are created. """ + _default_np_dtype = np.dtype(np.float64) + def __repr__(self) -> str: return f"{self.name}Dtype()" @@ -66,31 +57,8 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None: return FLOAT_STR_TO_DTYPE[str(np_dtype)] return None - -def coerce_to_array( - values, dtype=None, mask=None, copy: bool = False -) -> tuple[np.ndarray, np.ndarray]: - """ - Coerce the input values array to numpy arrays with a mask. - - Parameters - ---------- - values : 1D list-like - dtype : float dtype - mask : bool 1D array, optional - copy : bool, default False - if True, copy the input - - Returns - ------- - tuple of (values, mask) - """ - # if values is floating numpy array, preserve its dtype - if dtype is None and hasattr(values, "dtype"): - if is_float_dtype(values.dtype): - dtype = values.dtype - - if dtype is not None: + @classmethod + def _standardize_dtype(cls, dtype) -> FloatingDtype: if isinstance(dtype, str) and dtype.startswith("Float"): # Avoid DeprecationWarning from NumPy about np.dtype("Float64") # https://github.com/numpy/numpy/pull/7476 @@ -101,60 +69,18 @@ def coerce_to_array( dtype = FLOAT_STR_TO_DTYPE[str(np.dtype(dtype))] except KeyError as err: raise ValueError(f"invalid dtype specified {dtype}") from err + return dtype - if isinstance(values, FloatingArray): - values, mask = values._data, values._mask - if dtype is not None: - values = values.astype(dtype.numpy_dtype, copy=False) - - if copy: - values = values.copy() - mask = mask.copy() - return values, mask - - values = np.array(values, copy=copy) - if is_object_dtype(values.dtype) or is_string_dtype(values.dtype): - inferred_type = lib.infer_dtype(values, skipna=True) - if inferred_type == "empty": - pass - elif inferred_type == "boolean": - raise TypeError(f"{values.dtype} cannot be converted to a FloatingDtype") - - elif is_bool_dtype(values) and is_float_dtype(dtype): - values = np.array(values, dtype=float, copy=copy) - - elif not (is_integer_dtype(values) or is_float_dtype(values)): - raise TypeError(f"{values.dtype} cannot be converted to a FloatingDtype") - - if values.ndim != 1: - raise TypeError("values must be a 1D list-like") - - if mask is None: - mask = libmissing.is_numeric_na(values) - - else: - assert len(mask) == len(values) - - if not mask.ndim == 1: - raise TypeError("mask must be a 1D list-like") - - # infer dtype if needed - if dtype is None: - dtype = np.dtype("float64") - else: - dtype = dtype.type - - # if we are float, let's make sure that we can - # safely cast - - # we copy as need to coerce here - # TODO should this be a safe cast? - if mask.any(): - values = values.copy() - values[mask] = np.nan - values = values.astype(dtype, copy=False) # , casting="safe") + @classmethod + def _safe_cast(cls, values: np.ndarray, dtype: np.dtype, copy: bool) -> np.ndarray: + """ + Safely cast the values to the given dtype. - return values, mask + "safe" in this context means the casting is lossless. + """ + # This is really only here for compatibility with IntegerDtype + # Here for compat with IntegerDtype + return values.astype(dtype, copy=copy) class FloatingArray(NumericArray): @@ -217,8 +143,10 @@ class FloatingArray(NumericArray): Length: 3, dtype: Float32 """ + _dtype_cls = FloatingDtype + # The value used to fill '_data' to avoid upcasting - _internal_fill_value = 0.0 + _internal_fill_value = np.nan # Fill values used for any/all _truthy_value = 1.0 _falsey_value = 0.0 @@ -239,12 +167,6 @@ def __init__(self, values: np.ndarray, mask: np.ndarray, copy: bool = False): super().__init__(values, mask, copy=copy) - @classmethod - def _coerce_to_array( - cls, value, *, dtype: DtypeObj, copy: bool = False - ) -> tuple[np.ndarray, np.ndarray]: - return coerce_to_array(value, dtype=dtype, copy=copy) - _dtype_docstring = """ An ExtensionDtype for {dtype} data. diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index c21dbde09be5b..056669f40ca87 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -2,21 +2,10 @@ import numpy as np -from pandas._libs import ( - lib, - missing as libmissing, -) from pandas._typing import DtypeObj from pandas.util._decorators import cache_readonly from pandas.core.dtypes.base import register_extension_dtype -from pandas.core.dtypes.common import ( - is_bool_dtype, - is_float_dtype, - is_integer_dtype, - is_object_dtype, - is_string_dtype, -) from pandas.core.arrays.masked import BaseMaskedDtype from pandas.core.arrays.numeric import ( @@ -35,6 +24,8 @@ class _IntegerDtype(NumericDtype): The attributes name & type are set when these subclasses are created. """ + _default_np_dtype = np.dtype(np.int64) + def __repr__(self) -> str: sign = "U" if self.is_unsigned_integer else "" return f"{sign}Int{8 * self.itemsize}Dtype()" @@ -94,49 +85,8 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None: return FLOAT_STR_TO_DTYPE[str(np_dtype)] return None - -def safe_cast(values, dtype, copy: bool): - """ - Safely cast the values to the dtype if they - are equivalent, meaning floats must be equivalent to the - ints. - """ - try: - return values.astype(dtype, casting="safe", copy=copy) - except TypeError as err: - casted = values.astype(dtype, copy=copy) - if (casted == values).all(): - return casted - - raise TypeError( - f"cannot safely cast non-equivalent {values.dtype} to {np.dtype(dtype)}" - ) from err - - -def coerce_to_array( - values, dtype, mask=None, copy: bool = False -) -> tuple[np.ndarray, np.ndarray]: - """ - Coerce the input values array to numpy arrays with a mask. - - Parameters - ---------- - values : 1D list-like - dtype : integer dtype - mask : bool 1D array, optional - copy : bool, default False - if True, copy the input - - Returns - ------- - tuple of (values, mask) - """ - # if values is integer numpy array, preserve its dtype - if dtype is None and hasattr(values, "dtype"): - if is_integer_dtype(values.dtype): - dtype = values.dtype - - if dtype is not None: + @classmethod + def _standardize_dtype(cls, dtype) -> _IntegerDtype: if isinstance(dtype, str) and ( dtype.startswith("Int") or dtype.startswith("UInt") ): @@ -149,64 +99,26 @@ def coerce_to_array( dtype = INT_STR_TO_DTYPE[str(np.dtype(dtype))] except KeyError as err: raise ValueError(f"invalid dtype specified {dtype}") from err + return dtype + + @classmethod + def _safe_cast(cls, values: np.ndarray, dtype: np.dtype, copy: bool) -> np.ndarray: + """ + Safely cast the values to the given dtype. + + "safe" in this context means the casting is lossless. e.g. if 'values' + has a floating dtype, each value must be an integer. + """ + try: + return values.astype(dtype, casting="safe", copy=copy) + except TypeError as err: + casted = values.astype(dtype, copy=copy) + if (casted == values).all(): + return casted - if isinstance(values, IntegerArray): - values, mask = values._data, values._mask - if dtype is not None: - values = values.astype(dtype.numpy_dtype, copy=False) - - if copy: - values = values.copy() - mask = mask.copy() - return values, mask - - values = np.array(values, copy=copy) - inferred_type = None - if is_object_dtype(values.dtype) or is_string_dtype(values.dtype): - inferred_type = lib.infer_dtype(values, skipna=True) - if inferred_type == "empty": - pass - elif inferred_type == "boolean": - raise TypeError(f"{values.dtype} cannot be converted to a FloatingDtype") - - elif is_bool_dtype(values) and is_integer_dtype(dtype): - values = np.array(values, dtype=int, copy=copy) - - elif not (is_integer_dtype(values) or is_float_dtype(values)): - raise TypeError(f"{values.dtype} cannot be converted to an IntegerDtype") - - if values.ndim != 1: - raise TypeError("values must be a 1D list-like") - - if mask is None: - mask = libmissing.is_numeric_na(values) - else: - assert len(mask) == len(values) - - if mask.ndim != 1: - raise TypeError("mask must be a 1D list-like") - - # infer dtype if needed - if dtype is None: - dtype = np.dtype("int64") - else: - dtype = dtype.type - - # if we are float, let's make sure that we can - # safely cast - - # we copy as need to coerce here - if mask.any(): - values = values.copy() - values[mask] = 1 - if inferred_type in ("string", "unicode"): - # casts from str are always safe since they raise - # a ValueError if the str cannot be parsed into an int - values = values.astype(dtype, copy=copy) - else: - values = safe_cast(values, dtype, copy=False) - - return values, mask + raise TypeError( + f"cannot safely cast non-equivalent {values.dtype} to {np.dtype(dtype)}" + ) from err class IntegerArray(NumericArray): @@ -277,6 +189,8 @@ class IntegerArray(NumericArray): Length: 3, dtype: UInt16 """ + _dtype_cls = _IntegerDtype + # The value used to fill '_data' to avoid upcasting _internal_fill_value = 1 # Fill values used for any/all @@ -295,12 +209,6 @@ def __init__(self, values: np.ndarray, mask: np.ndarray, copy: bool = False): ) super().__init__(values, mask, copy=copy) - @classmethod - def _coerce_to_array( - cls, value, *, dtype: DtypeObj, copy: bool = False - ) -> tuple[np.ndarray, np.ndarray]: - return coerce_to_array(value, dtype=dtype, copy=copy) - _dtype_docstring = """ An ExtensionDtype for {dtype} integer data. diff --git a/pandas/core/arrays/numeric.py b/pandas/core/arrays/numeric.py index 88bb4484909c6..3aceb76a3bba0 100644 --- a/pandas/core/arrays/numeric.py +++ b/pandas/core/arrays/numeric.py @@ -11,17 +11,25 @@ from pandas._libs import ( Timedelta, + lib, missing as libmissing, ) -from pandas._typing import Dtype +from pandas._typing import ( + Dtype, + DtypeObj, +) from pandas.compat.numpy import function as nv +from pandas.errors import AbstractMethodError from pandas.core.dtypes.common import ( + is_bool_dtype, is_float, is_float_dtype, is_integer, is_integer_dtype, is_list_like, + is_object_dtype, + is_string_dtype, pandas_dtype, ) @@ -38,6 +46,8 @@ class NumericDtype(BaseMaskedDtype): + _default_np_dtype: np.dtype + def __from_arrow__( self, array: pyarrow.Array | pyarrow.ChunkedArray ) -> BaseMaskedArray: @@ -86,12 +96,116 @@ def __from_arrow__( else: return array_class._concat_same_type(results) + @classmethod + def _standardize_dtype(cls, dtype) -> NumericDtype: + """ + Convert a string representation or a numpy dtype to NumericDtype. + """ + raise AbstractMethodError(cls) + + @classmethod + def _safe_cast(cls, values: np.ndarray, dtype: np.dtype, copy: bool) -> np.ndarray: + """ + Safely cast the values to the given dtype. + + "safe" in this context means the casting is lossless. + """ + raise AbstractMethodError(cls) + + +def _coerce_to_data_and_mask(values, mask, dtype, copy, dtype_cls, default_dtype): + if default_dtype.kind == "f": + checker = is_float_dtype + else: + checker = is_integer_dtype + + inferred_type = None + + if dtype is None and hasattr(values, "dtype"): + if checker(values.dtype): + dtype = values.dtype + + if dtype is not None: + dtype = dtype_cls._standardize_dtype(dtype) + + cls = dtype_cls.construct_array_type() + if isinstance(values, cls): + values, mask = values._data, values._mask + if dtype is not None: + values = values.astype(dtype.numpy_dtype, copy=False) + + if copy: + values = values.copy() + mask = mask.copy() + return values, mask, dtype, inferred_type + + values = np.array(values, copy=copy) + inferred_type = None + if is_object_dtype(values.dtype) or is_string_dtype(values.dtype): + inferred_type = lib.infer_dtype(values, skipna=True) + if inferred_type == "empty": + pass + elif inferred_type == "boolean": + name = dtype_cls.__name__.strip("_") + raise TypeError(f"{values.dtype} cannot be converted to {name}") + + elif is_bool_dtype(values) and checker(dtype): + values = np.array(values, dtype=default_dtype, copy=copy) + + elif not (is_integer_dtype(values) or is_float_dtype(values)): + name = dtype_cls.__name__.strip("_") + raise TypeError(f"{values.dtype} cannot be converted to {name}") + + if values.ndim != 1: + raise TypeError("values must be a 1D list-like") + + if mask is None: + mask = libmissing.is_numeric_na(values) + else: + assert len(mask) == len(values) + + if mask.ndim != 1: + raise TypeError("mask must be a 1D list-like") + + # infer dtype if needed + if dtype is None: + dtype = default_dtype + else: + dtype = dtype.type + + # we copy as need to coerce here + if mask.any(): + values = values.copy() + values[mask] = cls._internal_fill_value + if inferred_type in ("string", "unicode"): + # casts from str are always safe since they raise + # a ValueError if the str cannot be parsed into a float + values = values.astype(dtype, copy=copy) + else: + values = dtype_cls._safe_cast(values, dtype, copy=False) + + return values, mask, dtype, inferred_type + class NumericArray(BaseMaskedArray): """ Base class for IntegerArray and FloatingArray. """ + _dtype_cls: type[NumericDtype] + + @classmethod + def _coerce_to_array( + cls, value, *, dtype: DtypeObj, copy: bool = False + ) -> tuple[np.ndarray, np.ndarray]: + dtype_cls = cls._dtype_cls + default_dtype = dtype_cls._default_np_dtype + mask = None + values, mask, _, _ = _coerce_to_data_and_mask( + value, mask, dtype, copy, dtype_cls, default_dtype + ) + return values, mask + @classmethod def _from_sequence_of_strings( cls: type[T], strings, *, dtype: Dtype | None = None, copy: bool = False diff --git a/pandas/tests/arrays/floating/test_construction.py b/pandas/tests/arrays/floating/test_construction.py index ec314f6213aad..ebce80cba237d 100644 --- a/pandas/tests/arrays/floating/test_construction.py +++ b/pandas/tests/arrays/floating/test_construction.py @@ -127,7 +127,7 @@ def test_to_array_error(values): # error in converting existing arrays to FloatingArray msg = "|".join( [ - "cannot be converted to a FloatingDtype", + "cannot be converted to FloatingDtype", "values must be a 1D list-like", "Cannot pass scalar", r"float\(\) argument must be a string or a (real )?number, not 'dict'", diff --git a/pandas/tests/arrays/integer/test_construction.py b/pandas/tests/arrays/integer/test_construction.py index fa61f23fc5d64..0e415fcfc366a 100644 --- a/pandas/tests/arrays/integer/test_construction.py +++ b/pandas/tests/arrays/integer/test_construction.py @@ -135,7 +135,7 @@ def test_to_integer_array_error(values): # error in converting existing arrays to IntegerArrays msg = "|".join( [ - r"cannot be converted to an IntegerDtype", + r"cannot be converted to IntegerDtype", r"invalid literal for int\(\) with base 10:", r"values must be a 1D list-like", r"Cannot pass scalar", diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 5a97c591fd621..54300f8027860 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1240,8 +1240,8 @@ def test_setting_mismatched_na_into_nullable_fails( msg = "|".join( [ - r"timedelta64\[ns\] cannot be converted to an? (Floating|Integer)Dtype", - r"datetime64\[ns\] cannot be converted to an? (Floating|Integer)Dtype", + r"timedelta64\[ns\] cannot be converted to (Floating|Integer)Dtype", + r"datetime64\[ns\] cannot be converted to (Floating|Integer)Dtype", "'values' contains non-numeric NA", r"Invalid value '.*' for dtype (U?Int|Float)\d{1,2}", ] diff --git a/pandas/tests/frame/methods/test_astype.py b/pandas/tests/frame/methods/test_astype.py index d326ca3493977..05a1f26c565c8 100644 --- a/pandas/tests/frame/methods/test_astype.py +++ b/pandas/tests/frame/methods/test_astype.py @@ -23,7 +23,6 @@ ) import pandas._testing as tm from pandas.core.api import UInt64Index -from pandas.core.arrays.integer import coerce_to_array def _check_cast(df, v): @@ -765,7 +764,7 @@ class IntegerArrayNoCopy(pd.core.arrays.IntegerArray): @classmethod def _from_sequence(cls, scalars, *, dtype=None, copy=False): - values, mask = coerce_to_array(scalars, dtype=dtype, copy=copy) + values, mask = cls._coerce_to_array(scalars, dtype=dtype, copy=copy) return IntegerArrayNoCopy(values, mask) def copy(self):
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45596
2022-01-24T18:05:34Z
2022-01-27T00:40:29Z
2022-01-27T00:40:29Z
2022-01-27T02:17:41Z
DOC: don't suggest melt instead of lookup
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 36e698fa576d8..12f749bd2aa6f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4561,7 +4561,7 @@ def lookup( .. deprecated:: 1.2.0 DataFrame.lookup is deprecated, - use DataFrame.melt and DataFrame.loc instead. + use pandas.factorize and NumPy indexing instead. For further details see :ref:`Looking up values by index/column labels <indexing.lookup>`.
- [X] closes #45589 - [ ] tests added / passed - [X] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45592
2022-01-24T16:21:02Z
2022-01-24T17:56:01Z
2022-01-24T17:56:01Z
2022-01-24T19:25:39Z
DOC/WEB: update versions.json to include 1.4 stable docs url
diff --git a/web/pandas/versions.json b/web/pandas/versions.json index 2ad317c50fef1..3085efe02738b 100644 --- a/web/pandas/versions.json +++ b/web/pandas/versions.json @@ -5,6 +5,10 @@ }, { "name": "1.4 (stable)", + "version": "docs" + }, + { + "name": "1.4", "version": "pandas-docs/version/1.4" }, {
Small follow-up on https://github.com/pandas-dev/pandas/pull/45555
https://api.github.com/repos/pandas-dev/pandas/pulls/45590
2022-01-24T14:37:29Z
2022-01-24T17:14:11Z
2022-01-24T17:14:11Z
2022-01-24T17:14:13Z
DOC: append deprecation
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 47a087d38d146..7340f2475e1f6 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -637,11 +637,11 @@ will continue to return :class:`Int64Index`, :class:`UInt64Index` and .. _whatsnew_140.deprecations.frame_series_append: -Deprecated Frame.append and Series.append -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Deprecated DataFrame.append and Series.append +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ :meth:`DataFrame.append` and :meth:`Series.append` have been deprecated and will -be removed in Pandas 2.0. Use :func:`pandas.concat` instead (:issue:`35407`). +be removed in a future version. Use :func:`pandas.concat` instead (:issue:`35407`). *Deprecated syntax* diff --git a/pandas/core/frame.py b/pandas/core/frame.py index c5faa432cb494..082a5814c2fc7 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -9011,6 +9011,10 @@ def append( """ Append rows of `other` to the end of caller, returning a new object. + .. deprecated:: 1.4.0 + Use :func:`concat` instead. For further details see + :ref:`whatsnew_140.deprecations.frame_series_append` + Columns in `other` that are not in the caller are added as new columns. Parameters diff --git a/pandas/core/series.py b/pandas/core/series.py index e4ba9ef2825e3..ea80f9d1ea04e 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2880,6 +2880,10 @@ def append( """ Concatenate two or more Series. + .. deprecated:: 1.4.0 + Use :func:`concat` instead. For further details see + :ref:`whatsnew_140.deprecations.frame_series_append` + Parameters ---------- to_append : Series or list/tuple of Series
- [ ] adds to documentation for #35407
https://api.github.com/repos/pandas-dev/pandas/pulls/45587
2022-01-24T11:31:30Z
2022-02-11T14:30:39Z
2022-02-11T14:30:38Z
2022-02-11T14:31:08Z
BUG: fix skiprows callable infinite loop
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 919ed926f8195..baccd4b45a906 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -289,6 +289,7 @@ MultiIndex I/O ^^^ - Bug in :meth:`DataFrame.to_stata` where no error is raised if the :class:`DataFrame` contains ``-np.inf`` (:issue:`45350`) +- Bug in :func:`read_excel` results in an infinite loop with certain ``skiprows`` callables (:issue:`45585`) - Bug in :meth:`DataFrame.info` where a new line at the end of the output is omitted when called on an empty :class:`DataFrame` (:issue:`45494`) - Bug in :func:`read_csv` not recognizing line break for ``on_bad_lines="warn"`` for ``engine="c"`` (:issue:`41710`) - Bug in :func:`read_parquet` when ``engine="pyarrow"`` which caused partial write to disk when column of unsupported datatype was passed (:issue:`44914`) diff --git a/pandas/io/parsers/python_parser.py b/pandas/io/parsers/python_parser.py index 52fa3be4ff418..5698fccf84743 100644 --- a/pandas/io/parsers/python_parser.py +++ b/pandas/io/parsers/python_parser.py @@ -667,6 +667,8 @@ def _is_line_empty(self, line: list[Scalar]) -> bool: def _next_line(self) -> list[Scalar]: if isinstance(self.data, list): while self.skipfunc(self.pos): + if self.pos >= len(self.data): + break self.pos += 1 while True: diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index 1a6e7e0bf3652..1b37b62870632 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -1163,6 +1163,31 @@ def test_read_excel_skiprows(self, request, read_ext): ) tm.assert_frame_equal(actual, expected) + def test_read_excel_skiprows_callable_not_in(self, request, read_ext): + # GH 4903 + if read_ext == ".xlsb": + request.node.add_marker( + pytest.mark.xfail( + reason="Sheets containing datetimes not supported by pyxlsb" + ) + ) + + actual = pd.read_excel( + "testskiprows" + read_ext, + sheet_name="skiprows_list", + skiprows=lambda x: x not in [1, 3, 5], + ) + expected = DataFrame( + [ + [1, 2.5, pd.Timestamp("2015-01-01"), True], + # [2, 3.5, pd.Timestamp("2015-01-02"), False], + [3, 4.5, pd.Timestamp("2015-01-03"), False], + # [4, 5.5, pd.Timestamp("2015-01-04"), True], + ], + columns=["a", "b", "c", "d"], + ) + tm.assert_frame_equal(actual, expected) + def test_read_excel_nrows(self, read_ext): # GH 16645 num_rows_to_pull = 5 diff --git a/pandas/tests/io/parser/test_skiprows.py b/pandas/tests/io/parser/test_skiprows.py index e88ccf07353b6..c58e27aacfa00 100644 --- a/pandas/tests/io/parser/test_skiprows.py +++ b/pandas/tests/io/parser/test_skiprows.py @@ -241,6 +241,17 @@ def test_skip_rows_callable(all_parsers, kwargs, expected): tm.assert_frame_equal(result, expected) +def test_skip_rows_callable_not_in(all_parsers): + parser = all_parsers + data = "0,a\n1,b\n2,c\n3,d\n4,e" + expected = DataFrame([[1, "b"], [3, "d"]]) + + result = parser.read_csv( + StringIO(data), header=None, skiprows=lambda x: x not in [1, 3] + ) + tm.assert_frame_equal(result, expected) + + def test_skip_rows_skip_all(all_parsers): parser = all_parsers data = "a\n1\n2\n3\n4\n5"
- [X] closes #45585 - [X] tests added / passed - [X] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry Not sure what to do about the `whatsnew` entry. Please advise (I've read the contributing doc but could not find it mentioned).
https://api.github.com/repos/pandas-dev/pandas/pulls/45586
2022-01-24T10:40:19Z
2022-02-06T22:41:09Z
2022-02-06T22:41:08Z
2022-02-06T22:41:16Z
Backport PR #45558 on branch 1.4.x (BUG: Segfault in to_json with tzaware datetime)
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 48b62637c26b1..79dae514b77e9 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -23,7 +23,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ -- +- Fixed segfault in :meth:``DataFrame.to_json`` when dumping tz-aware datetimes in Python 3.10 (:issue:`42130`) - .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/src/datetime/np_datetime.c b/pandas/_libs/tslibs/src/datetime/np_datetime.c index 9ad2ead5f919f..0efed210a7fdf 100644 --- a/pandas/_libs/tslibs/src/datetime/np_datetime.c +++ b/pandas/_libs/tslibs/src/datetime/np_datetime.c @@ -360,6 +360,7 @@ int convert_pydatetime_to_datetimestruct(PyObject *dtobj, Py_DECREF(tmp); } else { PyObject *offset; + PyObject *tmp_int; int seconds_offset, minutes_offset; /* The utcoffset function should return a timedelta */ @@ -378,11 +379,18 @@ int convert_pydatetime_to_datetimestruct(PyObject *dtobj, if (tmp == NULL) { return -1; } - seconds_offset = PyInt_AsLong(tmp); + tmp_int = PyNumber_Long(tmp); + if (tmp_int == NULL) { + Py_DECREF(tmp); + return -1; + } + seconds_offset = PyInt_AsLong(tmp_int); if (seconds_offset == -1 && PyErr_Occurred()) { + Py_DECREF(tmp_int); Py_DECREF(tmp); return -1; } + Py_DECREF(tmp_int); Py_DECREF(tmp); /* Convert to a minutes offset and apply it */ diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 0b8548f98b03b..f3a6f1f80359c 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -11,7 +11,6 @@ from pandas.compat import ( IS64, - PY310, is_platform_windows, ) import pandas.util._test_decorators as td @@ -1177,7 +1176,6 @@ def test_sparse(self): expected = s.to_json() assert expected == ss.to_json() - @pytest.mark.skipif(PY310, reason="segfault GH 42130") @pytest.mark.parametrize( "ts", [ @@ -1195,7 +1193,6 @@ def test_tz_is_utc(self, ts): dt = ts.to_pydatetime() assert dumps(dt, iso_dates=True) == exp - @pytest.mark.skipif(PY310, reason="segfault GH 42130") @pytest.mark.parametrize( "tz_range", [
Backport PR #45558: BUG: Segfault in to_json with tzaware datetime
https://api.github.com/repos/pandas-dev/pandas/pulls/45584
2022-01-24T07:03:10Z
2022-01-24T14:00:44Z
2022-01-24T14:00:44Z
2022-01-24T14:00:44Z
REF: avoid upcast/downcast in Block.where
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index fe5b464a5a18d..216dd1e65de3a 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -87,6 +87,7 @@ ) from pandas.core.dtypes.inference import is_list_like from pandas.core.dtypes.missing import ( + array_equivalent, is_valid_na_for_dtype, isna, na_value_for_dtype, @@ -1970,7 +1971,7 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any: # in smaller int dtypes. info = np.iinfo(dtype) if info.min <= element <= info.max: - return element + return dtype.type(element) raise ValueError if tipo is not None: @@ -2026,6 +2027,15 @@ def np_can_hold_element(dtype: np.dtype, element: Any) -> Any: if element._hasna: raise ValueError return element + elif tipo.itemsize > dtype.itemsize: + if isinstance(element, np.ndarray): + # e.g. TestDataFrameIndexingWhere::test_where_alignment + casted = element.astype(dtype) + # TODO(np>=1.20): we can just use np.array_equal with equal_nan + if array_equivalent(casted, element): + return casted + raise ValueError + return element if lib.is_integer(element) or lib.is_float(element): diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 77a0d7804d27b..60faae114ed07 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -38,8 +38,8 @@ from pandas.core.dtypes.cast import ( can_hold_element, find_result_type, - maybe_downcast_numeric, maybe_downcast_to_dtype, + np_can_hold_element, soft_convert_objects, ) from pandas.core.dtypes.common import ( @@ -1188,13 +1188,19 @@ def where(self, other, cond) -> list[Block]: other = self._standardize_fill_value(other) - if not self._can_hold_element(other): + try: + # try/except here is equivalent to a self._can_hold_element check, + # but this gets us back 'casted' which we will re-use below; + # without using 'casted', expressions.where may do unwanted upcasts. + casted = np_can_hold_element(values.dtype, other) + except (ValueError, TypeError): # we cannot coerce, return a compat dtype block = self.coerce_to_target_dtype(other) blocks = block.where(orig_other, cond) return self._maybe_downcast(blocks, "infer") else: + other = casted alt = setitem_datetimelike_compat(values, icond.sum(), other) if alt is not other: if is_list_like(other) and len(other) < len(values): @@ -1224,38 +1230,13 @@ def where(self, other, cond) -> list[Block]: # Note: expressions.where may upcast. result = expressions.where(~icond, values, other) + # The np_can_hold_element check _should_ ensure that we always + # have result.dtype == self.dtype here. - if self._can_hold_na or self.ndim == 1: - - if transpose: - result = result.T - - return [self.make_block(result)] - - # might need to separate out blocks - cond = ~icond - axis = cond.ndim - 1 - cond = cond.swapaxes(axis, 0) - mask = cond.all(axis=1) - - result_blocks: list[Block] = [] - for m in [mask, ~mask]: - if m.any(): - taken = result.take(m.nonzero()[0], axis=axis) - r = maybe_downcast_numeric(taken, self.dtype) - if r.dtype != taken.dtype: - warnings.warn( - "Downcasting integer-dtype results in .where is " - "deprecated and will change in a future version. " - "To retain the old behavior, explicitly cast the results " - "to the desired dtype.", - FutureWarning, - stacklevel=find_stack_level(), - ) - nb = self.make_block(r.T, placement=self._mgr_locs[m]) - result_blocks.append(nb) + if transpose: + result = result.T - return result_blocks + return [self.make_block(result)] def _unstack( self, diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py index 3e9bb6fca5558..750672c009f0c 100644 --- a/pandas/tests/frame/indexing/test_where.py +++ b/pandas/tests/frame/indexing/test_where.py @@ -141,11 +141,7 @@ def _check_align(df, cond, other, check_dtypes=True): # check other is ndarray cond = df > 0 - warn = None - if df is mixed_int_frame: - warn = FutureWarning - with tm.assert_produces_warning(warn, match="Downcasting integer-dtype"): - _check_align(df, cond, (_safe_add(df).values)) + _check_align(df, cond, (_safe_add(df).values)) # integers are upcast, so don't check the dtypes cond = df > 0 @@ -469,44 +465,43 @@ def test_where_axis(self, using_array_manager): # GH 9736 df = DataFrame(np.random.randn(2, 2)) mask = DataFrame([[False, False], [False, False]]) - s = Series([0, 1]) + ser = Series([0, 1]) expected = DataFrame([[0, 0], [1, 1]], dtype="float64") - result = df.where(mask, s, axis="index") + result = df.where(mask, ser, axis="index") tm.assert_frame_equal(result, expected) result = df.copy() - return_value = result.where(mask, s, axis="index", inplace=True) + return_value = result.where(mask, ser, axis="index", inplace=True) assert return_value is None tm.assert_frame_equal(result, expected) expected = DataFrame([[0, 1], [0, 1]], dtype="float64") - result = df.where(mask, s, axis="columns") + result = df.where(mask, ser, axis="columns") tm.assert_frame_equal(result, expected) result = df.copy() - return_value = result.where(mask, s, axis="columns", inplace=True) + return_value = result.where(mask, ser, axis="columns", inplace=True) assert return_value is None tm.assert_frame_equal(result, expected) + def test_where_axis_with_upcast(self): # Upcast needed df = DataFrame([[1, 2], [3, 4]], dtype="int64") mask = DataFrame([[False, False], [False, False]]) - s = Series([0, np.nan]) + ser = Series([0, np.nan]) expected = DataFrame([[0, 0], [np.nan, np.nan]], dtype="float64") - result = df.where(mask, s, axis="index") + result = df.where(mask, ser, axis="index") tm.assert_frame_equal(result, expected) result = df.copy() - return_value = result.where(mask, s, axis="index", inplace=True) + return_value = result.where(mask, ser, axis="index", inplace=True) assert return_value is None tm.assert_frame_equal(result, expected) - warn = FutureWarning if using_array_manager else None expected = DataFrame([[0, np.nan], [0, np.nan]]) - with tm.assert_produces_warning(warn, match="Downcasting integer-dtype"): - result = df.where(mask, s, axis="columns") + result = df.where(mask, ser, axis="columns") tm.assert_frame_equal(result, expected) expected = DataFrame( @@ -516,7 +511,7 @@ def test_where_axis(self, using_array_manager): } ) result = df.copy() - return_value = result.where(mask, s, axis="columns", inplace=True) + return_value = result.where(mask, ser, axis="columns", inplace=True) assert return_value is None tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_clip.py b/pandas/tests/frame/methods/test_clip.py index e692948c92a26..c851e65a7ad4f 100644 --- a/pandas/tests/frame/methods/test_clip.py +++ b/pandas/tests/frame/methods/test_clip.py @@ -136,7 +136,7 @@ def test_clip_against_unordered_columns(self): tm.assert_frame_equal(result_lower, expected_lower) tm.assert_frame_equal(result_lower_upper, expected_lower_upper) - def test_clip_with_na_args(self, float_frame, using_array_manager): + def test_clip_with_na_args(self, float_frame): """Should process np.nan argument as None""" # GH#17276 tm.assert_frame_equal(float_frame.clip(np.nan), float_frame) @@ -151,9 +151,7 @@ def test_clip_with_na_args(self, float_frame, using_array_manager): ) tm.assert_frame_equal(result, expected) - warn = FutureWarning if using_array_manager else None - with tm.assert_produces_warning(warn, match="Downcasting integer-dtype"): - result = df.clip(lower=[4, 5, np.nan], axis=1) + result = df.clip(lower=[4, 5, np.nan], axis=1) expected = DataFrame( {"col_0": [4, 4, 4], "col_1": [5, 5, 6], "col_2": [7, 8, 9]} )
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry Puts us within a stone's throw of being able to share Block.where with EABackedBlock.where.
https://api.github.com/repos/pandas-dev/pandas/pulls/45582
2022-01-24T04:32:40Z
2022-01-30T23:45:56Z
2022-01-30T23:45:56Z
2022-01-31T00:10:07Z
CI: Fix actions-310 testing 3.9 instead of 3.10
diff --git a/ci/deps/actions-310.yaml b/ci/deps/actions-310.yaml index 9829380620f86..bbc468f9d8f43 100644 --- a/ci/deps/actions-310.yaml +++ b/ci/deps/actions-310.yaml @@ -2,7 +2,7 @@ name: pandas-dev channels: - conda-forge dependencies: - - python=3.9 + - python=3.10 # test dependencies - cython=0.29.24 diff --git a/pandas/tests/io/test_fsspec.py b/pandas/tests/io/test_fsspec.py index f1040c0bd30f2..172065755d4b7 100644 --- a/pandas/tests/io/test_fsspec.py +++ b/pandas/tests/io/test_fsspec.py @@ -3,6 +3,7 @@ import numpy as np import pytest +from pandas.compat import PY310 from pandas.compat._optional import VERSIONS from pandas import ( @@ -181,6 +182,7 @@ def test_arrowparquet_options(fsspectest): @td.skip_array_manager_not_yet_implemented # TODO(ArrayManager) fastparquet @td.skip_if_no("fastparquet") +@pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_fastparquet_options(fsspectest): """Regression test for writing to a not-yet-existent GCS Parquet file.""" df = DataFrame({"a": [0]}) diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 2eb8738d88b41..a1a39a1cf8881 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -13,7 +13,10 @@ from pandas._config import get_option -from pandas.compat import is_platform_windows +from pandas.compat import ( + PY310, + is_platform_windows, +) from pandas.compat.pyarrow import ( pa_version_under2p0, pa_version_under5p0, @@ -262,6 +265,7 @@ def test_options_py(df_compat, pa): check_round_trip(df_compat) +@pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_options_fp(df_compat, fp): # use the set option @@ -339,6 +343,7 @@ def test_get_engine_auto_error_message(): get_engine("auto") +@pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_cross_engine_pa_fp(df_cross_compat, pa, fp): # cross-compat with differing reading/writing engines @@ -404,7 +409,11 @@ def test_error(self, engine): msg = "to_parquet only supports IO with DataFrames" self.check_error_on_write(obj, engine, ValueError, msg) - def test_columns_dtypes(self, engine): + def test_columns_dtypes(self, request, engine): + if PY310 and engine == "fastparquet": + request.node.add_marker( + pytest.mark.xfail(reason="fastparquet failing on 3.10") + ) df = pd.DataFrame({"string": list("abc"), "int": list(range(1, 4))}) # unicode @@ -431,7 +440,7 @@ def test_columns_dtypes_invalid(self, engine): self.check_error_on_write(df, engine, ValueError, msg) @pytest.mark.parametrize("compression", [None, "gzip", "snappy", "brotli"]) - def test_compression(self, engine, compression): + def test_compression(self, engine, compression, request): if compression == "snappy": pytest.importorskip("snappy") @@ -439,11 +448,19 @@ def test_compression(self, engine, compression): elif compression == "brotli": pytest.importorskip("brotli") + if PY310 and engine == "fastparquet": + request.node.add_marker( + pytest.mark.xfail(reason="fastparquet failing on 3.10") + ) df = pd.DataFrame({"A": [1, 2, 3]}) check_round_trip(df, engine, write_kwargs={"compression": compression}) - def test_read_columns(self, engine): + def test_read_columns(self, engine, request): # GH18154 + if PY310 and engine == "fastparquet": + request.node.add_marker( + pytest.mark.xfail(reason="fastparquet failing on 3.10") + ) df = pd.DataFrame({"string": list("abc"), "int": list(range(1, 4))}) expected = pd.DataFrame({"string": list("abc")}) @@ -451,7 +468,11 @@ def test_read_columns(self, engine): df, engine, expected=expected, read_kwargs={"columns": ["string"]} ) - def test_write_index(self, engine): + def test_write_index(self, engine, request): + if PY310 and engine == "fastparquet": + request.node.add_marker( + pytest.mark.xfail(reason="fastparquet failing on 3.10") + ) check_names = engine != "fastparquet" df = pd.DataFrame({"A": [1, 2, 3]}) @@ -500,9 +521,13 @@ def test_multiindex_with_columns(self, pa): df, engine, read_kwargs={"columns": ["A", "B"]}, expected=df[["A", "B"]] ) - def test_write_ignoring_index(self, engine): + def test_write_ignoring_index(self, engine, request): # ENH 20768 # Ensure index=False omits the index from the written Parquet file. + if PY310 and engine == "fastparquet": + request.node.add_marker( + pytest.mark.xfail(reason="fastparquet failing on 3.10") + ) df = pd.DataFrame({"a": [1, 2, 3], "b": ["q", "r", "s"]}) write_kwargs = {"compression": None, "index": False} @@ -986,6 +1011,7 @@ def test_read_parquet_manager(self, pa, using_array_manager): class TestParquetFastParquet(Base): + @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_basic(self, fp, df_full): df = df_full @@ -1003,6 +1029,7 @@ def test_duplicate_columns(self, fp): msg = "Cannot create parquet dataset with duplicate column names" self.check_error_on_write(df, fp, ValueError, msg) + @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_bool_with_none(self, fp): df = pd.DataFrame({"a": [True, None, False]}) expected = pd.DataFrame({"a": [1.0, np.nan, 0.0]}, dtype="float16") @@ -1022,10 +1049,12 @@ def test_unsupported(self, fp): msg = "Can't infer object conversion type" self.check_error_on_write(df, fp, ValueError, msg) + @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_categorical(self, fp): df = pd.DataFrame({"a": pd.Categorical(list("abc"))}) check_round_trip(df, fp) + @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_filter_row_groups(self, fp): d = {"a": list(range(0, 3))} df = pd.DataFrame(d) @@ -1044,6 +1073,7 @@ def test_s3_roundtrip(self, df_compat, s3_resource, fp, s3so): write_kwargs={"compression": None, "storage_options": s3so}, ) + @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_partition_cols_supported(self, fp, df_full): # GH #23283 partition_cols = ["bool", "int"] @@ -1061,6 +1091,7 @@ def test_partition_cols_supported(self, fp, df_full): actual_partition_cols = fastparquet.ParquetFile(path, False).cats assert len(actual_partition_cols) == 2 + @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_partition_cols_string(self, fp, df_full): # GH #27117 partition_cols = "bool" @@ -1078,6 +1109,7 @@ def test_partition_cols_string(self, fp, df_full): actual_partition_cols = fastparquet.ParquetFile(path, False).cats assert len(actual_partition_cols) == 1 + @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_partition_on_supported(self, fp, df_full): # GH #23283 partition_cols = ["bool", "int"] @@ -1113,6 +1145,7 @@ def test_error_on_using_partition_cols_and_partition_on(self, fp, df_full): partition_cols=partition_cols, ) + @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_empty_dataframe(self, fp): # GH #27339 df = pd.DataFrame() @@ -1120,6 +1153,7 @@ def test_empty_dataframe(self, fp): expected.index.name = "index" check_round_trip(df, fp, expected=expected) + @pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10") def test_timezone_aware_index(self, fp, timezone_aware_date_list): idx = 5 * [timezone_aware_date_list] diff --git a/pandas/tests/io/test_user_agent.py b/pandas/tests/io/test_user_agent.py index fb6128bd514f9..3d4c157e5f09e 100644 --- a/pandas/tests/io/test_user_agent.py +++ b/pandas/tests/io/test_user_agent.py @@ -11,6 +11,7 @@ import pytest +from pandas.compat import PY310 import pandas.util._test_decorators as td import pandas as pd @@ -241,7 +242,10 @@ def responder(request): pd.read_parquet, "fastparquet", # TODO(ArrayManager) fastparquet - marks=td.skip_array_manager_not_yet_implemented, + marks=[ + td.skip_array_manager_not_yet_implemented, + pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10"), + ], ), (PickleUserAgentResponder, pd.read_pickle, None), (StataUserAgentResponder, pd.read_stata, None), @@ -276,7 +280,10 @@ def test_server_and_default_headers(responder, read_method, parquet_engine): pd.read_parquet, "fastparquet", # TODO(ArrayManager) fastparquet - marks=td.skip_array_manager_not_yet_implemented, + marks=[ + td.skip_array_manager_not_yet_implemented, + pytest.mark.xfail(PY310, reason="fastparquet failing on 3.10"), + ], ), (PickleUserAgentResponder, pd.read_pickle, None), (StataUserAgentResponder, pd.read_stata, None),
- [x] tests added / passed
https://api.github.com/repos/pandas-dev/pandas/pulls/45581
2022-01-24T03:49:53Z
2022-01-25T02:56:14Z
2022-01-25T02:56:14Z
2022-02-01T11:03:33Z
REF: Use more context managers to close files
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index c51e91336b023..34f10c1b3ec28 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -839,9 +839,8 @@ The simplest case is to just pass in ``parse_dates=True``: .. ipython:: python :suppress: - f = open("foo.csv", "w") - f.write("date,A,B,C\n20090101,a,1,2\n20090102,b,3,4\n20090103,c,4,5") - f.close() + with open("foo.csv", mode="w") as f: + f.write("date,A,B,C\n20090101,a,1,2\n20090102,b,3,4\n20090103,c,4,5") .. ipython:: python @@ -1452,7 +1451,6 @@ a different usage of the ``delimiter`` parameter: .. ipython:: python :suppress: - f = open("bar.csv", "w") data1 = ( "id8141 360.242940 149.910199 11950.7\n" "id1594 444.953632 166.985655 11788.4\n" @@ -1460,8 +1458,8 @@ a different usage of the ``delimiter`` parameter: "id1230 413.836124 184.375703 11916.8\n" "id1948 502.953953 173.237159 12468.3" ) - f.write(data1) - f.close() + with open("bar.csv", "w") as f: + f.write(data1) Consider a typical fixed-width data file: @@ -1604,9 +1602,8 @@ of multi-columns indices. :suppress: data = ",a,a,a,b,c,c\n,q,r,s,t,u,v\none,1,2,3,4,5,6\ntwo,7,8,9,10,11,12" - fh = open("mi2.csv", "w") - fh.write(data) - fh.close() + with open("mi2.csv", "w") as fh: + fh.write(data) .. ipython:: python diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index f159228b94545..3e1df9325713b 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -535,11 +535,16 @@ def load_workbook(self, filepath_or_buffer): pass def close(self) -> None: - if hasattr(self, "book") and hasattr(self.book, "close"): - # pyxlsb: opens a TemporaryFile - # openpyxl: https://stackoverflow.com/questions/31416842/ - # openpyxl-does-not-close-excel-workbook-in-read-only-mode - self.book.close() + if hasattr(self, "book"): + if hasattr(self.book, "close"): + # pyxlsb: opens a TemporaryFile + # openpyxl: https://stackoverflow.com/questions/31416842/ + # openpyxl-does-not-close-excel-workbook-in-read-only-mode + self.book.close() + elif hasattr(self.book, "release_resources"): + # xlrd + # https://github.com/python-excel/xlrd/blob/2.0.1/xlrd/book.py#L548 + self.book.release_resources() self.handles.close() @property @@ -1266,11 +1271,12 @@ def inspect_excel_format( elif not peek.startswith(ZIP_SIGNATURE): return None - zf = zipfile.ZipFile(stream) - - # Workaround for some third party files that use forward slashes and - # lower case names. - component_names = [name.replace("\\", "/").lower() for name in zf.namelist()] + with zipfile.ZipFile(stream) as zf: + # Workaround for some third party files that use forward slashes and + # lower case names. + component_names = [ + name.replace("\\", "/").lower() for name in zf.namelist() + ] if "xl/workbook.xml" in component_names: return "xlsx" diff --git a/pandas/tests/io/excel/test_openpyxl.py b/pandas/tests/io/excel/test_openpyxl.py index e0d4a0c12ecdf..9f6e1ed9c08d9 100644 --- a/pandas/tests/io/excel/test_openpyxl.py +++ b/pandas/tests/io/excel/test_openpyxl.py @@ -1,3 +1,4 @@ +import contextlib from pathlib import Path import re @@ -159,12 +160,12 @@ def test_write_append_mode(ext, mode, expected): with ExcelWriter(f, engine="openpyxl", mode=mode) as writer: df.to_excel(writer, sheet_name="baz", index=False) - wb2 = openpyxl.load_workbook(f) - result = [sheet.title for sheet in wb2.worksheets] - assert result == expected + with contextlib.closing(openpyxl.load_workbook(f)) as wb2: + result = [sheet.title for sheet in wb2.worksheets] + assert result == expected - for index, cell_value in enumerate(expected): - assert wb2.worksheets[index]["A1"].value == cell_value + for index, cell_value in enumerate(expected): + assert wb2.worksheets[index]["A1"].value == cell_value @pytest.mark.parametrize( @@ -187,15 +188,14 @@ def test_if_sheet_exists_append_modes(ext, if_sheet_exists, num_sheets, expected ) as writer: df2.to_excel(writer, sheet_name="foo", index=False) - wb = openpyxl.load_workbook(f) - assert len(wb.sheetnames) == num_sheets - assert wb.sheetnames[0] == "foo" - result = pd.read_excel(wb, "foo", engine="openpyxl") - assert list(result["fruit"]) == expected - if len(wb.sheetnames) == 2: - result = pd.read_excel(wb, wb.sheetnames[1], engine="openpyxl") - tm.assert_frame_equal(result, df2) - wb.close() + with contextlib.closing(openpyxl.load_workbook(f)) as wb: + assert len(wb.sheetnames) == num_sheets + assert wb.sheetnames[0] == "foo" + result = pd.read_excel(wb, "foo", engine="openpyxl") + assert list(result["fruit"]) == expected + if len(wb.sheetnames) == 2: + result = pd.read_excel(wb, wb.sheetnames[1], engine="openpyxl") + tm.assert_frame_equal(result, df2) @pytest.mark.parametrize( @@ -279,9 +279,10 @@ def test_to_excel_with_openpyxl_engine(ext): def test_read_workbook(datapath, ext, read_only): # GH 39528 filename = datapath("io", "data", "excel", "test1" + ext) - wb = openpyxl.load_workbook(filename, read_only=read_only) - result = pd.read_excel(wb, engine="openpyxl") - wb.close() + with contextlib.closing( + openpyxl.load_workbook(filename, read_only=read_only) + ) as wb: + result = pd.read_excel(wb, engine="openpyxl") expected = pd.read_excel(filename) tm.assert_frame_equal(result, expected) @@ -313,9 +314,10 @@ def test_read_with_bad_dimension( if read_only is None: result = pd.read_excel(path, header=header) else: - wb = openpyxl.load_workbook(path, read_only=read_only) - result = pd.read_excel(wb, engine="openpyxl", header=header) - wb.close() + with contextlib.closing( + openpyxl.load_workbook(path, read_only=read_only) + ) as wb: + result = pd.read_excel(wb, engine="openpyxl", header=header) expected = DataFrame(expected_data) tm.assert_frame_equal(result, expected) @@ -349,9 +351,10 @@ def test_read_with_empty_trailing_rows(datapath, ext, read_only, request): if read_only is None: result = pd.read_excel(path) else: - wb = openpyxl.load_workbook(path, read_only=read_only) - result = pd.read_excel(wb, engine="openpyxl") - wb.close() + with contextlib.closing( + openpyxl.load_workbook(path, read_only=read_only) + ) as wb: + result = pd.read_excel(wb, engine="openpyxl") expected = DataFrame( { "Title": [np.nan, "A", 1, 2, 3], @@ -370,8 +373,9 @@ def test_read_empty_with_blank_row(datapath, ext, read_only): if read_only is None: result = pd.read_excel(path) else: - wb = openpyxl.load_workbook(path, read_only=read_only) - result = pd.read_excel(wb, engine="openpyxl") - wb.close() + with contextlib.closing( + openpyxl.load_workbook(path, read_only=read_only) + ) as wb: + result = pd.read_excel(wb, engine="openpyxl") expected = DataFrame() tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/excel/test_style.py b/pandas/tests/io/excel/test_style.py index 8a142aebd719d..1a92cc9672bfa 100644 --- a/pandas/tests/io/excel/test_style.py +++ b/pandas/tests/io/excel/test_style.py @@ -1,3 +1,5 @@ +import contextlib + import numpy as np import pytest @@ -37,13 +39,13 @@ def test_styler_to_excel_unstyled(engine): df.style.to_excel(writer, sheet_name="unstyled") openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl - wb = openpyxl.load_workbook(path) + with contextlib.closing(openpyxl.load_workbook(path)) as wb: - for col1, col2 in zip(wb["dataframe"].columns, wb["unstyled"].columns): - assert len(col1) == len(col2) - for cell1, cell2 in zip(col1, col2): - assert cell1.value == cell2.value - assert_equal_cell_styles(cell1, cell2) + for col1, col2 in zip(wb["dataframe"].columns, wb["unstyled"].columns): + assert len(col1) == len(col2) + for cell1, cell2 in zip(col1, col2): + assert cell1.value == cell2.value + assert_equal_cell_styles(cell1, cell2) shared_style_params = [ @@ -87,11 +89,11 @@ def test_styler_to_excel_basic(engine, css, attrs, expected): styler.to_excel(writer, sheet_name="styled") openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl - wb = openpyxl.load_workbook(path) + with contextlib.closing(openpyxl.load_workbook(path)) as wb: - # test unstyled data cell does not have expected styles - # test styled cell has expected styles - u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2) + # test unstyled data cell does not have expected styles + # test styled cell has expected styles + u_cell, s_cell = wb["dataframe"].cell(2, 2), wb["styled"].cell(2, 2) for attr in attrs: u_cell, s_cell = getattr(u_cell, attr), getattr(s_cell, attr) @@ -127,12 +129,12 @@ def test_styler_to_excel_basic_indexes(engine, css, attrs, expected): styler.to_excel(writer, sheet_name="styled") openpyxl = pytest.importorskip("openpyxl") # test loading only with openpyxl - wb = openpyxl.load_workbook(path) + with contextlib.closing(openpyxl.load_workbook(path)) as wb: - # test null styled index cells does not have expected styles - # test styled cell has expected styles - ui_cell, si_cell = wb["null_styled"].cell(2, 1), wb["styled"].cell(2, 1) - uc_cell, sc_cell = wb["null_styled"].cell(1, 2), wb["styled"].cell(1, 2) + # test null styled index cells does not have expected styles + # test styled cell has expected styles + ui_cell, si_cell = wb["null_styled"].cell(2, 1), wb["styled"].cell(2, 1) + uc_cell, sc_cell = wb["null_styled"].cell(1, 2), wb["styled"].cell(1, 2) for attr in attrs: ui_cell, si_cell = getattr(ui_cell, attr), getattr(si_cell, attr) uc_cell, sc_cell = getattr(uc_cell, attr), getattr(sc_cell, attr) @@ -163,5 +165,5 @@ def custom_converter(css): writer, sheet_name="custom" ) - wb = openpyxl.load_workbook(path) - assert wb["custom"].cell(2, 2).font.color.value == "00111222" + with contextlib.closing(openpyxl.load_workbook(path)) as wb: + assert wb["custom"].cell(2, 2).font.color.value == "00111222" diff --git a/pandas/tests/io/excel/test_xlrd.py b/pandas/tests/io/excel/test_xlrd.py index 2309187b8e9af..f2ae668dee5a3 100644 --- a/pandas/tests/io/excel/test_xlrd.py +++ b/pandas/tests/io/excel/test_xlrd.py @@ -45,13 +45,14 @@ def test_read_xlrd_book(read_ext_xlrd, frame): with tm.ensure_clean(read_ext_xlrd) as pth: df.to_excel(pth, sheet_name) - book = xlrd.open_workbook(pth) - - with ExcelFile(book, engine=engine) as xl: - result = pd.read_excel(xl, sheet_name=sheet_name, index_col=0) - tm.assert_frame_equal(df, result) - - result = pd.read_excel(book, sheet_name=sheet_name, engine=engine, index_col=0) + with xlrd.open_workbook(pth) as book: + with ExcelFile(book, engine=engine) as xl: + result = pd.read_excel(xl, sheet_name=sheet_name, index_col=0) + tm.assert_frame_equal(df, result) + + result = pd.read_excel( + book, sheet_name=sheet_name, engine=engine, index_col=0 + ) tm.assert_frame_equal(df, result) diff --git a/pandas/tests/io/excel/test_xlsxwriter.py b/pandas/tests/io/excel/test_xlsxwriter.py index 79d2f55a9b8ff..b5c1b47775089 100644 --- a/pandas/tests/io/excel/test_xlsxwriter.py +++ b/pandas/tests/io/excel/test_xlsxwriter.py @@ -1,3 +1,4 @@ +import contextlib import re import warnings @@ -34,12 +35,12 @@ def test_column_format(ext): col_format = write_workbook.add_format({"num_format": num_format}) write_worksheet.set_column("B:B", None, col_format) - read_workbook = openpyxl.load_workbook(path) - try: - read_worksheet = read_workbook["Sheet1"] - except TypeError: - # compat - read_worksheet = read_workbook.get_sheet_by_name(name="Sheet1") + with contextlib.closing(openpyxl.load_workbook(path)) as read_workbook: + try: + read_worksheet = read_workbook["Sheet1"] + except TypeError: + # compat + read_worksheet = read_workbook.get_sheet_by_name(name="Sheet1") # Get the number format from the cell. try: diff --git a/pandas/tests/io/parser/test_c_parser_only.py b/pandas/tests/io/parser/test_c_parser_only.py index 5df4470635af5..83cccdb37b343 100644 --- a/pandas/tests/io/parser/test_c_parser_only.py +++ b/pandas/tests/io/parser/test_c_parser_only.py @@ -592,11 +592,9 @@ def test_file_handles_mmap(c_parser_only, csv1): parser = c_parser_only with open(csv1) as f: - m = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) - parser.read_csv(m) - - assert not m.closed - m.close() + with mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ) as m: + parser.read_csv(m) + assert not m.closed def test_file_binary_mode(c_parser_only): diff --git a/pandas/tests/io/parser/test_python_parser_only.py b/pandas/tests/io/parser/test_python_parser_only.py index 73a6c8226b554..999a6217efb68 100644 --- a/pandas/tests/io/parser/test_python_parser_only.py +++ b/pandas/tests/io/parser/test_python_parser_only.py @@ -167,9 +167,8 @@ def test_decompression_regex_sep(python_parser_only, csv1, compression, klass): klass = getattr(module, klass) with tm.ensure_clean() as path: - tmp = klass(path, mode="wb") - tmp.write(data) - tmp.close() + with klass(path, mode="wb") as tmp: + tmp.write(data) result = parser.read_csv(path, sep="::", compression=compression) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/io/sas/test_sas7bdat.py b/pandas/tests/io/sas/test_sas7bdat.py index 5477559262cb8..1847d3634a550 100644 --- a/pandas/tests/io/sas/test_sas7bdat.py +++ b/pandas/tests/io/sas/test_sas7bdat.py @@ -1,3 +1,4 @@ +import contextlib from datetime import datetime import io import os @@ -135,9 +136,8 @@ def test_encoding_options(datapath): from pandas.io.sas.sas7bdat import SAS7BDATReader - rdr = SAS7BDATReader(fname, convert_header_text=False) - df3 = rdr.read() - rdr.close() + with contextlib.closing(SAS7BDATReader(fname, convert_header_text=False)) as rdr: + df3 = rdr.read() for x, y in zip(df1.columns, df3.columns): assert x == y.decode() diff --git a/pandas/tests/io/test_common.py b/pandas/tests/io/test_common.py index b458f3351c860..7b7918a323c99 100644 --- a/pandas/tests/io/test_common.py +++ b/pandas/tests/io/test_common.py @@ -415,8 +415,8 @@ def test_constructor_bad_file(self, mmap_file): with pytest.raises(err, match=msg): icom._MMapWrapper(non_file) - target = open(mmap_file) - target.close() + with open(mmap_file) as target: + pass msg = "I/O operation on closed file" with pytest.raises(ValueError, match=msg):
- [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/45579
2022-01-24T01:26:18Z
2022-01-24T04:03:45Z
2022-01-24T04:03:45Z
2022-01-24T04:03:48Z
TST: Change test_groupby_copy to apply_mutate.py
diff --git a/pandas/tests/groupby/test_apply_mutate.py b/pandas/tests/groupby/test_apply_mutate.py index 05c1f5b716f40..01fe7512c0fe9 100644 --- a/pandas/tests/groupby/test_apply_mutate.py +++ b/pandas/tests/groupby/test_apply_mutate.py @@ -4,6 +4,20 @@ import pandas._testing as tm +def test_group_by_copy(): + # GH#44803 + df = pd.DataFrame( + { + "name": ["Alice", "Bob", "Carl"], + "age": [20, 21, 20], + } + ).set_index("name") + + grp_by_same_value = df.groupby(["age"]).apply(lambda group: group) + grp_by_copy = df.groupby(["age"]).apply(lambda group: group.copy()) + tm.assert_frame_equal(grp_by_same_value, grp_by_copy) + + def test_mutate_groups(): # GH3380 diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 03c09112be1fe..fb2b9f0632f0d 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -32,20 +32,6 @@ from pandas.core.groupby.base import maybe_normalize_deprecated_kernels -def test_group_by_copy(): - # GH#44803 - df = DataFrame( - { - "name": ["Alice", "Bob", "Carl"], - "age": [20, 21, 20], - } - ).set_index("name") - - grp_by_same_value = df.groupby(["age"]).apply(lambda group: group) - grp_by_copy = df.groupby(["age"]).apply(lambda group: group.copy()) - tm.assert_frame_equal(grp_by_same_value, grp_by_copy) - - def test_repr(): # GH18203 result = repr(Grouper(key="A", level="B"))
Pending tasks from #45509 In line with issue #44803 Change test_groupby_copy from `pandas/tests/groupby/test_groupby.py` to `pandas/tests/groupby/test_apply_mutate.py` - [X] Already closed #44803 via #45509
https://api.github.com/repos/pandas-dev/pandas/pulls/45578
2022-01-23T22:56:39Z
2022-01-24T21:26:29Z
2022-01-24T21:26:29Z
2022-01-25T13:52:45Z
BUG: frame.mask(foo, bar, inplace=True) with EAs incorrectly raising
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 4e73ea348dfde..1f846cd867fad 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -263,6 +263,7 @@ Indexing - Bug when setting a value too large for a :class:`Series` dtype failing to coerce to a common type (:issue:`26049`, :issue:`32878`) - Bug in :meth:`Series.__setitem__` when setting ``boolean`` dtype values containing ``NA`` incorrectly raising instead of casting to ``boolean`` dtype (:issue:`45462`) - Bug in :meth:`Series.__setitem__` where setting :attr:`NA` into a numeric-dtpye :class:`Series` would incorrectly upcast to object-dtype rather than treating the value as ``np.nan`` (:issue:`44199`) +- Bug in :meth:`DataFrame.mask` with ``inplace=True`` and ``ExtensionDtype`` columns incorrectly raising (:issue:`45577`) - Bug in getting a column from a DataFrame with an object-dtype row index with datetime-like values: the resulting Series now preserves the exact object-dtype Index from the parent DataFrame (:issue:`42950`) - diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 3d4f53530b89c..ff56ed80f36f1 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1436,6 +1436,7 @@ def putmask(self, mask, new) -> list[Block]: values = self.values + new = self._maybe_squeeze_arg(new) mask = self._maybe_squeeze_arg(mask) try: diff --git a/pandas/tests/extension/base/methods.py b/pandas/tests/extension/base/methods.py index f5a18037d97eb..3fd50c08f5cc4 100644 --- a/pandas/tests/extension/base/methods.py +++ b/pandas/tests/extension/base/methods.py @@ -443,7 +443,8 @@ def test_where_series(self, data, na_value, as_frame): cls = type(data) a, b = data[:2] - ser = pd.Series(cls._from_sequence([a, a, b, b], dtype=data.dtype)) + orig = pd.Series(cls._from_sequence([a, a, b, b], dtype=data.dtype)) + ser = orig.copy() cond = np.array([True, True, False, False]) if as_frame: @@ -459,7 +460,13 @@ def test_where_series(self, data, na_value, as_frame): expected = expected.to_frame(name="a") self.assert_equal(result, expected) + ser.mask(~cond, inplace=True) + self.assert_equal(ser, expected) + # array other + ser = orig.copy() + if as_frame: + ser = ser.to_frame(name="a") cond = np.array([True, False, True, True]) other = cls._from_sequence([a, b, a, b], dtype=data.dtype) if as_frame: @@ -471,6 +478,9 @@ def test_where_series(self, data, na_value, as_frame): expected = expected.to_frame(name="a") self.assert_equal(result, expected) + ser.mask(~cond, other, inplace=True) + self.assert_equal(ser, expected) + @pytest.mark.parametrize("repeats", [0, 1, 2, [1, 2, 3]]) def test_repeat(self, data, repeats, as_series, use_numpy): arr = type(data)._from_sequence(data[:3], dtype=data.dtype) diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py index 399318a6d6118..3e9bb6fca5558 100644 --- a/pandas/tests/frame/indexing/test_where.py +++ b/pandas/tests/frame/indexing/test_where.py @@ -812,6 +812,12 @@ def test_where_string_dtype(frame_or_series): ) tm.assert_equal(result, expected) + result = obj.mask(~filter_ser, filtered_obj) + tm.assert_equal(result, expected) + + obj.mask(~filter_ser, filtered_obj, inplace=True) + tm.assert_equal(result, expected) + def test_where_bool_comparison(): # GH 10336
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45577
2022-01-23T20:30:06Z
2022-01-28T00:27:12Z
2022-01-28T00:27:12Z
2022-01-28T00:33:23Z
CI: Use xsel instead of xclip for numpydev
diff --git a/.github/workflows/posix.yml b/.github/workflows/posix.yml index 135ca0703de8b..1cc8188919980 100644 --- a/.github/workflows/posix.yml +++ b/.github/workflows/posix.yml @@ -35,7 +35,7 @@ jobs: [actions-pypy-38.yaml, "not slow and not clipboard", "", "", "", "", "--max-worker-restart 0"], [actions-39.yaml, "slow", "", "", "", "", ""], [actions-39.yaml, "not slow and not clipboard", "", "", "", "", ""], - [actions-310-numpydev.yaml, "not slow and not network", "xclip", "", "", "deprecate", "-W error"], + [actions-310-numpydev.yaml, "not slow and not network", "xsel", "", "", "deprecate", "-W error"], [actions-310.yaml, "not slow and not clipboard", "", "", "", "", ""], [actions-310.yaml, "slow", "", "", "", "", ""], ] diff --git a/pandas/tests/io/test_clipboard.py b/pandas/tests/io/test_clipboard.py index 40b2eb1f4114b..4a53705193e99 100644 --- a/pandas/tests/io/test_clipboard.py +++ b/pandas/tests/io/test_clipboard.py @@ -307,6 +307,11 @@ def test_round_trip_valid_encodings(self, enc, df): @pytest.mark.single @pytest.mark.clipboard @pytest.mark.parametrize("data", ["\U0001f44d...", "Ωœ∑´...", "abcd..."]) +@pytest.mark.xfail( + reason="Flaky test in multi-process CI environment: GH 44584", + raises=AssertionError, + strict=False, +) def test_raw_roundtrip(data): # PR #25040 wide unicode wasn't copied correctly on PY3 on windows clipboard_set(data)
Hopefully fixes this flaky clipboard test ``` _________________________ test_raw_roundtrip[abcd...] __________________________ [gw1] linux -- Python 3.10.0 /usr/share/miniconda/envs/pandas-dev/bin/python data = 'abcd...' @pytest.mark.single @pytest.mark.clipboard @pytest.mark.parametrize("data", ["\U0001f44d...", "Ωœ∑´...", "abcd..."]) def test_raw_roundtrip(data): # PR #25040 wide unicode wasn't copied correctly on PY3 on windows clipboard_set(data) > assert data == clipboard_get() E AssertionError: assert 'abcd...' == 'Ωœ∑´...' E - Ωœ∑´... E + abcd... pandas/tests/io/test_clipboard.py:313: AssertionError ```
https://api.github.com/repos/pandas-dev/pandas/pulls/45576
2022-01-23T20:13:33Z
2022-01-24T22:27:40Z
2022-01-24T22:27:40Z
2022-01-24T22:51:55Z
PERF: faster groupby diff
diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index 74bdf7cccff70..cf6f3f92068e8 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -18,6 +18,7 @@ method_blocklist = { "object": { + "diff", "median", "prod", "sem", @@ -405,7 +406,7 @@ class GroupByMethods: param_names = ["dtype", "method", "application", "ncols"] params = [ - ["int", "float", "object", "datetime", "uint"], + ["int", "int16", "float", "object", "datetime", "uint"], [ "all", "any", @@ -417,6 +418,7 @@ class GroupByMethods: "cumprod", "cumsum", "describe", + "diff", "ffill", "first", "head", @@ -478,7 +480,7 @@ def setup(self, dtype, method, application, ncols): values = rng.take(taker, axis=0) if dtype == "int": key = np.random.randint(0, size, size=size) - elif dtype == "uint": + elif dtype in ("int16", "uint"): key = np.random.randint(0, size, size=size, dtype=dtype) elif dtype == "float": key = np.concatenate( diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 86444d0b24002..af1535041d363 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -287,6 +287,7 @@ Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Performance improvement in :meth:`.GroupBy.transform` for some user-defined DataFrame -> Series functions (:issue:`45387`) - Performance improvement in :meth:`DataFrame.duplicated` when subset consists of only one column (:issue:`45236`) +- Performance improvement in :meth:`.GroupBy.diff` (:issue:`16706`) - Performance improvement in :meth:`.GroupBy.transform` when broadcasting values for user-defined functions (:issue:`45708`) - Performance improvement in :meth:`.GroupBy.transform` for user-defined functions when only a single group exists (:issue:`44977`) - Performance improvement in :meth:`MultiIndex.get_locs` (:issue:`45681`, :issue:`46040`) diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index a91c88722593c..65e8b238cd476 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -3456,6 +3456,47 @@ def shift(self, periods=1, freq=None, axis=0, fill_value=None): ) return res + @final + @Substitution(name="groupby") + @Appender(_common_see_also) + def diff(self, periods: int = 1, axis: int = 0) -> Series | DataFrame: + """ + First discrete difference of element. + + Calculates the difference of each element compared with another + element in the group (default is element in previous row). + + Parameters + ---------- + periods : int, default 1 + Periods to shift for calculating difference, accepts negative values. + axis : axis to shift, default 0 + Take difference over rows (0) or columns (1). + + Returns + ------- + Series or DataFrame + First differences. + """ + if axis != 0: + return self.apply(lambda x: x.diff(periods=periods, axis=axis)) + + obj = self._obj_with_exclusions + shifted = self.shift(periods=periods, axis=axis) + + # GH45562 - to retain existing behavior and match behavior of Series.diff(), + # int8 and int16 are coerced to float32 rather than float64. + dtypes_to_f32 = ["int8", "int16"] + if obj.ndim == 1: + if obj.dtype in dtypes_to_f32: + shifted = shifted.astype("float32") + else: + to_coerce = [c for c, dtype in obj.dtypes.items() if dtype in dtypes_to_f32] + if len(to_coerce): + shifted = shifted.astype({c: "float32" for c in to_coerce}) + + return obj - shifted + @final @Substitution(name="groupby") @Appender(_common_see_also) diff --git a/pandas/tests/groupby/test_groupby_shift_diff.py b/pandas/tests/groupby/test_groupby_shift_diff.py index c989c0e0c94cd..7ffee412e3cdf 100644 --- a/pandas/tests/groupby/test_groupby_shift_diff.py +++ b/pandas/tests/groupby/test_groupby_shift_diff.py @@ -69,7 +69,7 @@ def test_group_shift_lose_timezone(): tm.assert_series_equal(result, expected) -def test_group_diff_real(any_real_numpy_dtype): +def test_group_diff_real_series(any_real_numpy_dtype): df = DataFrame( {"a": [1, 2, 3, 3, 2], "b": [1, 2, 3, 4, 5]}, dtype=any_real_numpy_dtype, @@ -82,6 +82,29 @@ def test_group_diff_real(any_real_numpy_dtype): tm.assert_series_equal(result, expected) +def test_group_diff_real_frame(any_real_numpy_dtype): + df = DataFrame( + { + "a": [1, 2, 3, 3, 2], + "b": [1, 2, 3, 4, 5], + "c": [1, 2, 3, 4, 6], + }, + dtype=any_real_numpy_dtype, + ) + result = df.groupby("a").diff() + exp_dtype = "float" + if any_real_numpy_dtype in ["int8", "int16", "float32"]: + exp_dtype = "float32" + expected = DataFrame( + { + "b": [np.nan, np.nan, np.nan, 1.0, 3.0], + "c": [np.nan, np.nan, np.nan, 1.0, 4.0], + }, + dtype=exp_dtype, + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( "data", [
- [x] closes #16706 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry As @jreback suggests in the original issue, there is a large perf improvement to groupby.diff if implemented directly as a groupby method. The int8/int16 type coercion feels a bit odd, but was needed to retain existing behavior as well as pass existing unit tests that explicitly test those dtypes. Separate issue to discuss that: #45562 ``` before after ratio [2db3b0a0] [6edfb839] <faster-groupby-diff> - 1.98±0.02ms 1.35±0.02ms 0.68 groupby.GroupByMethods.time_dtype_as_group('object', 'diff', 'transformation', 5) - 799±9μs 472±6μs 0.59 groupby.GroupByMethods.time_dtype_as_group('object', 'diff', 'transformation', 1) - 461±5μs 166±0.8μs 0.36 groupby.GroupByMethods.time_dtype_as_group('object', 'diff', 'direct', 1) - 94.0±4ms 2.22±0.9ms 0.02 groupby.GroupByMethods.time_dtype_as_group('uint', 'diff', 'transformation', 5) - 69.1±1ms 1.51±0.02ms 0.02 groupby.GroupByMethods.time_dtype_as_field('uint', 'diff', 'transformation', 5) - 69.3±2ms 1.48±0.01ms 0.02 groupby.GroupByMethods.time_dtype_as_field('float', 'diff', 'transformation', 5) - 78.5±4ms 1.45±0.01ms 0.02 groupby.GroupByMethods.time_dtype_as_field('int', 'diff', 'transformation', 5) - 94.0±6ms 1.46±0.01ms 0.02 groupby.GroupByMethods.time_dtype_as_group('int', 'diff', 'transformation', 5) - 122±3ms 1.55±0.01ms 0.01 groupby.GroupByMethods.time_dtype_as_field('datetime', 'diff', 'transformation', 5) - 140±2ms 1.45±0ms 0.01 groupby.GroupByMethods.time_dtype_as_group('float', 'diff', 'transformation', 5) - 140±2ms 1.41±0.02ms 0.01 groupby.GroupByMethods.time_dtype_as_group('datetime', 'diff', 'transformation', 5) - 66.0±0.7ms 502±5μs 0.01 groupby.GroupByMethods.time_dtype_as_field('uint', 'diff', 'transformation', 1) - 64.3±0.5ms 488±10μs 0.01 groupby.GroupByMethods.time_dtype_as_field('float', 'diff', 'transformation', 1) - 106±8ms 767±200μs 0.01 groupby.GroupByMethods.time_dtype_as_group('uint', 'diff', 'transformation', 1) - 75.9±2ms 497±20μs 0.01 groupby.GroupByMethods.time_dtype_as_field('int', 'diff', 'transformation', 1) - 89.8±3ms 587±200μs 0.01 groupby.GroupByMethods.time_dtype_as_group('uint', 'diff', 'direct', 5) - 88.5±1ms 526±5μs 0.01 groupby.GroupByMethods.time_dtype_as_group('int', 'diff', 'direct', 5) - 102±2ms 552±10μs 0.01 groupby.GroupByMethods.time_dtype_as_group('int', 'diff', 'transformation', 1) - 120±2ms 614±4μs 0.01 groupby.GroupByMethods.time_dtype_as_field('datetime', 'diff', 'transformation', 1) - 161±0.6ms 604±7μs 0.00 groupby.GroupByMethods.time_dtype_as_group('float', 'diff', 'transformation', 1) - 138±3ms 500±3μs 0.00 groupby.GroupByMethods.time_dtype_as_group('float', 'diff', 'direct', 5) - 139±3ms 498±5μs 0.00 groupby.GroupByMethods.time_dtype_as_group('datetime', 'diff', 'direct', 5) - 165±1ms 502±3μs 0.00 groupby.GroupByMethods.time_dtype_as_group('datetime', 'diff', 'transformation', 1) - 66.5±1ms 192±3μs 0.00 groupby.GroupByMethods.time_dtype_as_field('uint', 'diff', 'direct', 1) - 71.2±1ms 201±3μs 0.00 groupby.GroupByMethods.time_dtype_as_field('uint', 'diff', 'direct', 5) - 124±3ms 326±2μs 0.00 groupby.GroupByMethods.time_dtype_as_field('datetime', 'diff', 'direct', 5) - 119±2ms 306±3μs 0.00 groupby.GroupByMethods.time_dtype_as_field('datetime', 'diff', 'direct', 1) - 78.6±1ms 196±5μs 0.00 groupby.GroupByMethods.time_dtype_as_field('int', 'diff', 'direct', 5) - 70.1±0.8ms 170±5μs 0.00 groupby.GroupByMethods.time_dtype_as_field('float', 'diff', 'direct', 5) - 67.4±4ms 159±2μs 0.00 groupby.GroupByMethods.time_dtype_as_field('float', 'diff', 'direct', 1) - 78.4±1ms 183±2μs 0.00 groupby.GroupByMethods.time_dtype_as_field('int', 'diff', 'direct', 1) - 108±8ms 249±80μs 0.00 groupby.GroupByMethods.time_dtype_as_group('uint', 'diff', 'direct', 1) - 102±3ms 182±2μs 0.00 groupby.GroupByMethods.time_dtype_as_group('int', 'diff', 'direct', 1) - 160±2ms 170±3μs 0.00 groupby.GroupByMethods.time_dtype_as_group('float', 'diff', 'direct', 1) - 165±3ms 171±2μs 0.00 groupby.GroupByMethods.time_dtype_as_group('datetime', 'diff', 'direct', 1) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/45575
2022-01-23T20:01:51Z
2022-02-28T13:41:08Z
2022-02-28T13:41:08Z
2022-05-07T03:12:25Z
DEPR: datetimelike.astype(int_other_than_i8) return requested dtype
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 571bcb7a6d2b2..f2acd0eb3f47a 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -192,6 +192,7 @@ Other Deprecations - Deprecated behavior of :meth:`DatetimeIndex.intersection` and :meth:`DatetimeIndex.symmetric_difference` (``union`` behavior was already deprecated in version 1.3.0) with mixed timezones; in a future version both will be cast to UTC instead of object dtype (:issue:`39328`, :issue:`45357`) - Deprecated :meth:`DataFrame.iteritems`, :meth:`Series.iteritems`, :meth:`HDFStore.iteritems` in favor of :meth:`DataFrame.items`, :meth:`Series.items`, :meth:`HDFStore.items` (:issue:`45321`) - Deprecated :meth:`Series.is_monotonic` and :meth:`Index.is_monotonic` in favor of :meth:`Series.is_monotonic_increasing` and :meth:`Index.is_monotonic_increasing` (:issue:`45422`, :issue:`21335`) +- Deprecated behavior of :meth:`DatetimeIndex.astype`, :meth:`TimedeltaIndex.astype`, :meth:`PeriodIndex.astype` when converting to an integer dtype other than ``int64``. In a future version, these will convert to exactly the specified dtype (instead of always ``int64``) and will raise if the conversion overflows (:issue:`45034`) - Deprecated the ``__array_wrap__`` method of DataFrame and Series, rely on standard numpy ufuncs instead (:issue:`45451`) - Deprecated the behavior of :meth:`Series.fillna` and :meth:`DataFrame.fillna` with ``timedelta64[ns]`` dtype and incompatible fill value; in a future version this will cast to a common dtype (usually object) instead of raising, matching the behavior of other dtypes (:issue:`45746`) - diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 3259ee7d28bbe..483878706db75 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -446,6 +446,36 @@ def astype(self, dtype, copy: bool = True): if is_unsigned_integer_dtype(dtype): # Again, we ignore int32 vs. int64 values = values.view("uint64") + if dtype != np.uint64: + # GH#45034 + warnings.warn( + f"The behavior of .astype from {self.dtype} to {dtype} is " + "deprecated. In a future version, this astype will return " + "exactly the specified dtype instead of uint64, and will " + "raise if that conversion overflows.", + FutureWarning, + stacklevel=find_stack_level(), + ) + elif (self.asi8 < 0).any(): + # GH#45034 + warnings.warn( + f"The behavior of .astype from {self.dtype} to {dtype} is " + "deprecated. In a future version, this astype will " + "raise if the conversion overflows, as it did in this " + "case with negative int64 values.", + FutureWarning, + stacklevel=find_stack_level(), + ) + elif dtype != np.int64: + # GH#45034 + warnings.warn( + f"The behavior of .astype from {self.dtype} to {dtype} is " + "deprecated. In a future version, this astype will return " + "exactly the specified dtype instead of int64, and will " + "raise if that conversion overflows.", + FutureWarning, + stacklevel=find_stack_level(), + ) if copy: values = values.copy() diff --git a/pandas/tests/arrays/period/test_astype.py b/pandas/tests/arrays/period/test_astype.py index f05265c910e1c..e9245c9ca786b 100644 --- a/pandas/tests/arrays/period/test_astype.py +++ b/pandas/tests/arrays/period/test_astype.py @@ -9,18 +9,29 @@ @pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"]) -def test_astype(dtype): +def test_astype_int(dtype): # We choose to ignore the sign and size of integers for # Period/Datetime/Timedelta astype arr = period_array(["2000", "2001", None], freq="D") - result = arr.astype(dtype) if np.dtype(dtype).kind == "u": expected_dtype = np.dtype("uint64") + warn1 = FutureWarning else: expected_dtype = np.dtype("int64") - - expected = arr.astype(expected_dtype) + warn1 = None + + msg_overflow = "will raise if the conversion overflows" + with tm.assert_produces_warning(warn1, match=msg_overflow): + expected = arr.astype(expected_dtype) + + warn = None if dtype == expected_dtype else FutureWarning + msg = " will return exactly the specified dtype" + if warn is None and warn1 is not None: + warn = warn1 + msg = msg_overflow + with tm.assert_produces_warning(warn, match=msg): + result = arr.astype(dtype) assert result.dtype == expected_dtype tm.assert_numpy_array_equal(result, expected) diff --git a/pandas/tests/arrays/test_datetimes.py b/pandas/tests/arrays/test_datetimes.py index ad75c137ec703..9ea87be2a5468 100644 --- a/pandas/tests/arrays/test_datetimes.py +++ b/pandas/tests/arrays/test_datetimes.py @@ -77,7 +77,6 @@ def test_astype_copies(self, dtype, other): @pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"]) def test_astype_int(self, dtype): arr = DatetimeArray._from_sequence([pd.Timestamp("2000"), pd.Timestamp("2001")]) - result = arr.astype(dtype) if np.dtype(dtype).kind == "u": expected_dtype = np.dtype("uint64") @@ -85,6 +84,13 @@ def test_astype_int(self, dtype): expected_dtype = np.dtype("int64") expected = arr.astype(expected_dtype) + warn = None + if dtype != expected_dtype: + warn = FutureWarning + msg = " will return exactly the specified dtype" + with tm.assert_produces_warning(warn, match=msg): + result = arr.astype(dtype) + assert result.dtype == expected_dtype tm.assert_numpy_array_equal(result, expected) diff --git a/pandas/tests/arrays/test_timedeltas.py b/pandas/tests/arrays/test_timedeltas.py index 675c6ac8c9233..bf3491496ab3a 100644 --- a/pandas/tests/arrays/test_timedeltas.py +++ b/pandas/tests/arrays/test_timedeltas.py @@ -11,7 +11,6 @@ class TestTimedeltaArray: @pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"]) def test_astype_int(self, dtype): arr = TimedeltaArray._from_sequence([Timedelta("1H"), Timedelta("2H")]) - result = arr.astype(dtype) if np.dtype(dtype).kind == "u": expected_dtype = np.dtype("uint64") @@ -19,6 +18,13 @@ def test_astype_int(self, dtype): expected_dtype = np.dtype("int64") expected = arr.astype(expected_dtype) + warn = None + if dtype != expected_dtype: + warn = FutureWarning + msg = " will return exactly the specified dtype" + with tm.assert_produces_warning(warn, match=msg): + result = arr.astype(dtype) + assert result.dtype == expected_dtype tm.assert_numpy_array_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/methods/test_astype.py b/pandas/tests/indexes/datetimes/methods/test_astype.py index 9002371f25012..e7823f0c90b1a 100644 --- a/pandas/tests/indexes/datetimes/methods/test_astype.py +++ b/pandas/tests/indexes/datetimes/methods/test_astype.py @@ -52,7 +52,11 @@ def test_astype_uint(self): name="idx", ) tm.assert_index_equal(arr.astype("uint64"), expected) - tm.assert_index_equal(arr.astype("uint32"), expected) + + msg = "will return exactly the specified dtype instead of uint64" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = arr.astype("uint32") + tm.assert_index_equal(res, expected) def test_astype_with_tz(self): diff --git a/pandas/tests/indexes/interval/test_astype.py b/pandas/tests/indexes/interval/test_astype.py index 94b7ccd618cba..c253a745ef5a2 100644 --- a/pandas/tests/indexes/interval/test_astype.py +++ b/pandas/tests/indexes/interval/test_astype.py @@ -205,10 +205,18 @@ def index(self, request): @pytest.mark.parametrize("subtype", ["int64", "uint64"]) def test_subtype_integer(self, index, subtype): dtype = IntervalDtype(subtype, "right") - result = index.astype(dtype) - expected = IntervalIndex.from_arrays( - index.left.astype(subtype), index.right.astype(subtype), closed=index.closed - ) + + warn = None + if index.isna().any() and subtype == "uint64": + warn = FutureWarning + msg = "In a future version, this astype will raise if the conversion overflows" + + with tm.assert_produces_warning(warn, match=msg): + result = index.astype(dtype) + new_left = index.left.astype(subtype) + new_right = index.right.astype(subtype) + + expected = IntervalIndex.from_arrays(new_left, new_right, closed=index.closed) tm.assert_index_equal(result, expected) def test_subtype_float(self, index): diff --git a/pandas/tests/indexes/period/methods/test_astype.py b/pandas/tests/indexes/period/methods/test_astype.py index c3ea72c908459..fbc1d3702115e 100644 --- a/pandas/tests/indexes/period/methods/test_astype.py +++ b/pandas/tests/indexes/period/methods/test_astype.py @@ -58,7 +58,11 @@ def test_astype_uint(self): arr = period_range("2000", periods=2, name="idx") expected = UInt64Index(np.array([10957, 10958], dtype="uint64"), name="idx") tm.assert_index_equal(arr.astype("uint64"), expected) - tm.assert_index_equal(arr.astype("uint32"), expected) + + msg = "will return exactly the specified dtype instead of uint64" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = arr.astype("uint32") + tm.assert_index_equal(res, expected) def test_astype_object(self): idx = PeriodIndex([], freq="M") diff --git a/pandas/tests/indexes/timedeltas/methods/test_astype.py b/pandas/tests/indexes/timedeltas/methods/test_astype.py index 276b0dbf246cc..aa2f7b7af8d98 100644 --- a/pandas/tests/indexes/timedeltas/methods/test_astype.py +++ b/pandas/tests/indexes/timedeltas/methods/test_astype.py @@ -79,7 +79,11 @@ def test_astype_uint(self): np.array([3600000000000, 90000000000000], dtype="uint64") ) tm.assert_index_equal(arr.astype("uint64"), expected) - tm.assert_index_equal(arr.astype("uint32"), expected) + + msg = "will return exactly the specified dtype instead of uint64" + with tm.assert_produces_warning(FutureWarning, match=msg): + res = arr.astype("uint32") + tm.assert_index_equal(res, expected) def test_astype_timedelta64(self): # GH 13149, GH 13209
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry xref #45034 this should be just non-controversial parts of that discussion cc @jorisvandenbossche
https://api.github.com/repos/pandas-dev/pandas/pulls/45574
2022-01-23T18:45:58Z
2022-02-14T08:22:21Z
2022-02-14T08:22:21Z
2022-02-14T16:31:24Z
DEPR: treating float data as wall-times in DTA._from_sequence
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 71394a858aefe..d5b092e21a596 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -240,6 +240,7 @@ Other Deprecations - Deprecated :meth:`Series.is_monotonic` and :meth:`Index.is_monotonic` in favor of :meth:`Series.is_monotonic_increasing` and :meth:`Index.is_monotonic_increasing` (:issue:`45422`, :issue:`21335`) - Deprecated behavior of :meth:`DatetimeIndex.astype`, :meth:`TimedeltaIndex.astype`, :meth:`PeriodIndex.astype` when converting to an integer dtype other than ``int64``. In a future version, these will convert to exactly the specified dtype (instead of always ``int64``) and will raise if the conversion overflows (:issue:`45034`) - Deprecated the ``__array_wrap__`` method of DataFrame and Series, rely on standard numpy ufuncs instead (:issue:`45451`) +- Deprecated treating float-dtype data as wall-times when passed with a timezone to :class:`Series` or :class:`DatetimeIndex` (:issue:`45573`) - Deprecated the behavior of :meth:`Series.fillna` and :meth:`DataFrame.fillna` with ``timedelta64[ns]`` dtype and incompatible fill value; in a future version this will cast to a common dtype (usually object) instead of raising, matching the behavior of other dtypes (:issue:`45746`) - Deprecated the ``warn`` parameter in :func:`infer_freq` (:issue:`45947`) diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index f652e0b870ae7..e21f2e9d7b46e 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -2066,7 +2066,7 @@ def _sequence_to_dt64ns( inferred_freq = data.freq # By this point we are assured to have either a numpy array or Index - data, copy = maybe_convert_dtype(data, copy) + data, copy = maybe_convert_dtype(data, copy, tz=tz) data_dtype = getattr(data, "dtype", None) if ( @@ -2246,7 +2246,7 @@ def objects_to_datetime64ns( raise TypeError(result) -def maybe_convert_dtype(data, copy: bool): +def maybe_convert_dtype(data, copy: bool, tz: tzinfo | None = None): """ Convert data based on dtype conventions, issuing deprecation warnings or errors where appropriate. @@ -2255,6 +2255,7 @@ def maybe_convert_dtype(data, copy: bool): ---------- data : np.ndarray or pd.Index copy : bool + tz : tzinfo or None, default None Returns ------- @@ -2274,8 +2275,23 @@ def maybe_convert_dtype(data, copy: bool): # as wall-times instead of UTC timestamps. data = data.astype(DT64NS_DTYPE) copy = False - # TODO: deprecate this behavior to instead treat symmetrically - # with integer dtypes. See discussion in GH#23675 + if ( + tz is not None + and len(data) > 0 + and not timezones.is_utc(timezones.maybe_get_tz(tz)) + ): + # GH#23675, GH#45573 deprecate to treat symmetrically with integer dtypes + warnings.warn( + "The behavior of DatetimeArray._from_sequence with a timezone-aware " + "dtype and floating-dtype data is deprecated. In a future version, " + "this data will be interpreted as nanosecond UTC timestamps " + "instead of wall-times, matching the behavior with integer dtypes. " + "To retain the old behavior, explicitly cast to 'datetime64[ns]' " + "before passing the data to pandas. To get the future behavior, " + "first cast to 'int64'.", + FutureWarning, + stacklevel=find_stack_level(), + ) elif is_timedelta64_dtype(data.dtype) or is_bool_dtype(data.dtype): # GH#29794 enforcing deprecation introduced in GH#23539 diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 3f0a5deb97548..33ed64c7ae364 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -27,6 +27,7 @@ iNaT, nat_strings, parsing, + timezones, ) from pandas._libs.tslibs.parsing import ( # noqa:F401 DateParseError, @@ -364,7 +365,7 @@ def _convert_listlike_datetimes( # NB: this must come after unit transformation orig_arg = arg try: - arg, _ = maybe_convert_dtype(arg, copy=False) + arg, _ = maybe_convert_dtype(arg, copy=False, tz=timezones.maybe_get_tz(tz)) except TypeError: if errors == "coerce": npvalues = np.array(["NaT"], dtype="datetime64[ns]").repeat(len(arg)) diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index 1917fc615118a..a986e8d659202 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -415,23 +415,28 @@ def test_array_equivalent(dtype_equal): TimedeltaIndex([1, np.nan]), dtype_equal=dtype_equal, ) + + msg = "will be interpreted as nanosecond UTC timestamps instead of wall-times" + with tm.assert_produces_warning(FutureWarning, match=msg): + dti1 = DatetimeIndex([0, np.nan], tz="US/Eastern") + dti2 = DatetimeIndex([0, np.nan], tz="CET") + dti3 = DatetimeIndex([1, np.nan], tz="US/Eastern") + assert array_equivalent( - DatetimeIndex([0, np.nan], tz="US/Eastern"), - DatetimeIndex([0, np.nan], tz="US/Eastern"), + dti1, + dti1, dtype_equal=dtype_equal, ) assert not array_equivalent( - DatetimeIndex([0, np.nan], tz="US/Eastern"), - DatetimeIndex([1, np.nan], tz="US/Eastern"), + dti1, + dti3, dtype_equal=dtype_equal, ) # The rest are not dtype_equal + assert not array_equivalent(DatetimeIndex([0, np.nan]), dti1) assert not array_equivalent( - DatetimeIndex([0, np.nan]), DatetimeIndex([0, np.nan], tz="US/Eastern") - ) - assert not array_equivalent( - DatetimeIndex([0, np.nan], tz="CET"), - DatetimeIndex([0, np.nan], tz="US/Eastern"), + dti2, + dti1, ) assert not array_equivalent(DatetimeIndex([0, np.nan]), TimedeltaIndex([0, np.nan])) diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index f286dc4a09cb2..eda902d34bff5 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -140,7 +140,7 @@ def create_block(typestr, placement, item_shape=None, num_offset=0, maker=new_bl assert m is not None, f"incompatible typestr -> {typestr}" tz = m.groups()[0] assert num_items == 1, "must have only 1 num items for a tz-aware" - values = DatetimeIndex(np.arange(N) * 1e9, tz=tz)._data + values = DatetimeIndex(np.arange(N) * 10**9, tz=tz)._data values = ensure_block_shape(values, ndim=len(shape)) elif typestr in ("timedelta", "td", "m8[ns]"): values = (mat * 1).astype("m8[ns]") diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index ff9bb3edeedb1..630f4cc3194f4 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -381,7 +381,12 @@ def test_astype_nan_to_bool(self): ) def test_astype_ea_to_datetimetzdtype(self, dtype): # GH37553 - result = Series([4, 0, 9], dtype=dtype).astype(DatetimeTZDtype(tz="US/Pacific")) + ser = Series([4, 0, 9], dtype=dtype) + warn = FutureWarning if ser.dtype.kind == "f" else None + msg = "with a timezone-aware dtype and floating-dtype data" + with tm.assert_produces_warning(warn, match=msg): + result = ser.astype(DatetimeTZDtype(tz="US/Pacific")) + expected = Series( { 0: Timestamp("1969-12-31 16:00:00.000000004-08:00", tz="US/Pacific"),
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45573
2022-01-23T18:28:11Z
2022-02-19T01:14:37Z
2022-02-19T01:14:37Z
2022-02-19T03:00:43Z
PERF: TimedeltaArray.astype(object)
diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index c845d9c8cdbde..2f26f6cc22f80 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -37,6 +37,7 @@ delta_to_nanoseconds, iNaT, ints_to_pydatetime, + ints_to_pytimedelta, to_offset, ) from pandas._libs.tslibs.fields import ( @@ -421,6 +422,11 @@ def astype(self, dtype, copy: bool = True): ) return converted.reshape(self.shape) + elif self.dtype.kind == "m": + i8data = self.asi8.ravel() + converted = ints_to_pytimedelta(i8data, box=True) + return converted.reshape(self.shape) + return self._box_values(self.asi8.ravel()).reshape(self.shape) elif isinstance(dtype, ExtensionDtype):
``` In [2]: tdi = pd.timedelta_range("1 second", periods=10**5, freq="s") In [5]: %timeit tdi.astype(object) 388 ms ± 43.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # <- PR 588 ms ± 63.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) # <- main ```
https://api.github.com/repos/pandas-dev/pandas/pulls/45571
2022-01-23T16:24:19Z
2022-01-23T19:53:45Z
2022-01-23T19:53:45Z
2022-01-23T20:53:51Z
Fixes mypy attribute issue in io/parquet by adding a hasattr check
diff --git a/pandas/io/parquet.py b/pandas/io/parquet.py index c5bfbd2b6b35d..1b8526275c155 100644 --- a/pandas/io/parquet.py +++ b/pandas/io/parquet.py @@ -180,8 +180,12 @@ def write( mode="wb", is_dir=partition_cols is not None, ) - if isinstance(path_or_handle, io.BufferedWriter): - path_or_handle = path_or_handle.raw.name + if ( + isinstance(path_or_handle, io.BufferedWriter) + and hasattr(path_or_handle, "name") + and isinstance(path_or_handle.name, (str, bytes)) + ): + path_or_handle = path_or_handle.name try: if partition_cols is not None: diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 93cc2fd5100c8..2eb8738d88b41 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -13,6 +13,7 @@ from pandas._config import get_option +from pandas.compat import is_platform_windows from pandas.compat.pyarrow import ( pa_version_under2p0, pa_version_under5p0, @@ -728,6 +729,13 @@ def test_unsupported_float16(self, pa): df = pd.DataFrame(data=data, columns=["fp16"]) self.check_external_error_on_write(df, pa, pyarrow.ArrowException) + @pytest.mark.xfail( + is_platform_windows(), + reason=( + "PyArrow does not cleanup of partial files dumps when unsupported " + "dtypes are passed to_parquet function in windows" + ), + ) @pytest.mark.parametrize("path_type", [str, pathlib.Path]) def test_unsupported_float16_cleanup(self, pa, path_type): # #44847, #44914
- [x] closes #45480, #44914 - [x] Passes tests in pytest - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/45570
2022-01-23T15:43:26Z
2022-01-23T23:35:37Z
2022-01-23T23:35:37Z
2022-01-23T23:35:54Z
BUG: Series[Interval[int]][1] = np.nan incorrect coercion/raising
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index 4e73ea348dfde..da42b2c228ec6 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -259,6 +259,7 @@ Indexing ^^^^^^^^ - Bug in :meth:`loc.__getitem__` with a list of keys causing an internal inconsistency that could lead to a disconnect between ``frame.at[x, y]`` vs ``frame[y].loc[x]`` (:issue:`22372`) - Bug in :meth:`DataFrame.iloc` where indexing a single row on a :class:`DataFrame` with a single ExtensionDtype column gave a copy instead of a view on the underlying data (:issue:`45241`) +- Bug in setting a NA value (``None`` or ``np.nan``) into a :class:`Series` with int-based :class:`IntervalDtype` incorrectly casting to object dtype instead of a float-based :class:`IntervalDtype` (:issue:`45568`) - Bug in :meth:`Series.__setitem__` with a non-integer :class:`Index` when using an integer key to set a value that cannot be set inplace where a ``ValueError`` was raised insead of casting to a common dtype (:issue:`45070`) - Bug when setting a value too large for a :class:`Series` dtype failing to coerce to a common type (:issue:`26049`, :issue:`32878`) - Bug in :meth:`Series.__setitem__` when setting ``boolean`` dtype values containing ``NA`` incorrectly raising instead of casting to ``boolean`` dtype (:issue:`45462`) diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 9ceded00bf159..33732bcaca733 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -18,10 +18,7 @@ from pandas._config import get_option -from pandas._libs import ( - NaT, - lib, -) +from pandas._libs import lib from pandas._libs.interval import ( VALID_CLOSED, Interval, @@ -44,8 +41,6 @@ from pandas.core.dtypes.common import ( is_categorical_dtype, - is_datetime64_dtype, - is_datetime64tz_dtype, is_dtype_equal, is_float_dtype, is_integer_dtype, @@ -54,7 +49,6 @@ is_object_dtype, is_scalar, is_string_dtype, - is_timedelta64_dtype, needs_i8_conversion, pandas_dtype, ) @@ -1103,7 +1097,7 @@ def _validate_scalar(self, value): # TODO: check subdtype match like _validate_setitem_value? elif is_valid_na_for_dtype(value, self.left.dtype): # GH#18295 - left = right = value + left = right = self.left._na_value else: raise TypeError( "can only insert Interval objects and NA into an IntervalArray" @@ -1111,22 +1105,15 @@ def _validate_scalar(self, value): return left, right def _validate_setitem_value(self, value): - needs_float_conversion = False if is_valid_na_for_dtype(value, self.left.dtype): # na value: need special casing to set directly on numpy arrays + value = self.left._na_value if is_integer_dtype(self.dtype.subtype): # can't set NaN on a numpy integer array - needs_float_conversion = True - elif is_datetime64_dtype(self.dtype.subtype): - # need proper NaT to set directly on the numpy array - value = np.datetime64("NaT") - elif is_datetime64tz_dtype(self.dtype.subtype): - # need proper NaT to set directly on the DatetimeArray array - value = NaT - elif is_timedelta64_dtype(self.dtype.subtype): - # need proper NaT to set directly on the numpy array - value = np.timedelta64("NaT") + # GH#45484 TypeError, not ValueError, matches what we get with + # non-NA un-holdable value. + raise TypeError("Cannot set float NaN to integer-backed IntervalArray") value_left, value_right = value, value elif isinstance(value, Interval): @@ -1139,10 +1126,6 @@ def _validate_setitem_value(self, value): else: return self._validate_listlike(value) - if needs_float_conversion: - # GH#45484 TypeError, not ValueError, matches what we get with - # non-NA un-holdable value. - raise TypeError("Cannot set float NaN to integer-backed IntervalArray") return value_left, value_right def value_counts(self, dropna: bool = True): diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 92f3cfdc589ff..fe5b464a5a18d 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -470,8 +470,13 @@ def ensure_dtype_can_hold_na(dtype: DtypeObj) -> DtypeObj: If we have a dtype that cannot hold NA values, find the best match that can. """ if isinstance(dtype, ExtensionDtype): - # TODO: ExtensionDtype.can_hold_na? - return dtype + if dtype._can_hold_na: + return dtype + elif isinstance(dtype, IntervalDtype): + # TODO(GH#45349): don't special-case IntervalDtype, allow + # overriding instead of returning object below. + return IntervalDtype(np.float64, closed=dtype.closed) + return _dtype_obj elif dtype.kind == "b": return _dtype_obj elif dtype.kind in ["i", "u"]: @@ -1470,6 +1475,10 @@ def find_result_type(left: ArrayLike, right: Any) -> DtypeObj: new_dtype = np.result_type(left, right) + elif is_valid_na_for_dtype(right, left.dtype): + # e.g. IntervalDtype[int] and None/np.nan + new_dtype = ensure_dtype_can_hold_na(left.dtype) + else: dtype, _ = infer_dtype_from(right, pandas_dtype=True) diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index e74d73b84e94b..9a6d4748380a6 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -1117,6 +1117,18 @@ def __new__(cls, subtype=None, closed: str_type | None = None): cls._cache_dtypes[key] = u return u + @cache_readonly + def _can_hold_na(self) -> bool: + subtype = self._subtype + if subtype is None: + # partially-initialized + raise NotImplementedError( + "_can_hold_na is not defined for partially-initialized IntervalDtype" + ) + if subtype.kind in ["i", "u"]: + return False + return True + @property def closed(self): return self._closed diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 26ddf89adaea2..ab2413dd06a45 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -70,6 +70,7 @@ from pandas.core.dtypes.cast import ( can_hold_element, common_dtype_categorical_compat, + ensure_dtype_can_hold_na, find_common_type, infer_dtype_from, maybe_cast_pointwise_result, @@ -178,7 +179,6 @@ from pandas import ( CategoricalIndex, DataFrame, - IntervalIndex, MultiIndex, Series, ) @@ -6087,10 +6087,15 @@ def _find_common_type_compat(self, target) -> DtypeObj: Implementation of find_common_type that adjusts for Index-specific special cases. """ - if is_interval_dtype(self.dtype) and is_valid_na_for_dtype(target, self.dtype): + if is_valid_na_for_dtype(target, self.dtype): # e.g. setting NA value into IntervalArray[int64] - self = cast("IntervalIndex", self) - return IntervalDtype(np.float64, closed=self.closed) + dtype = ensure_dtype_can_hold_na(self.dtype) + if is_dtype_equal(self.dtype, dtype): + raise NotImplementedError( + "This should not be reached. Please report a bug at " + "github.com/pandas-dev/pandas" + ) + return dtype target_dtype, _ = infer_dtype_from(target, pandas_dtype=True) diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 8501c7146f371..9d1ee70c265e8 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -24,6 +24,7 @@ array, concat, date_range, + interval_range, period_range, timedelta_range, ) @@ -740,6 +741,17 @@ def test_index_putmask(self, obj, key, expected, val): @pytest.mark.parametrize( "obj,expected,key", [ + pytest.param( + # GH#45568 setting a valid NA value into IntervalDtype[int] should + # cast to IntervalDtype[float] + Series(interval_range(1, 5)), + Series( + [Interval(1, 2), np.nan, Interval(3, 4), Interval(4, 5)], + dtype="interval[float64]", + ), + 1, + id="interval_int_na_value", + ), pytest.param( # these induce dtype changes Series([2, 3, 4, 5, 6, 7, 8, 9, 10]), diff --git a/pandas/tests/series/methods/test_convert_dtypes.py b/pandas/tests/series/methods/test_convert_dtypes.py index 3a5fcf5c2929c..25cbcf2a84490 100644 --- a/pandas/tests/series/methods/test_convert_dtypes.py +++ b/pandas/tests/series/methods/test_convert_dtypes.py @@ -3,8 +3,6 @@ import numpy as np import pytest -from pandas.core.dtypes.common import is_interval_dtype - import pandas as pd import pandas._testing as tm @@ -203,12 +201,8 @@ def test_convert_dtypes( # Test that it is a copy copy = series.copy(deep=True) - if is_interval_dtype(result.dtype) and result.dtype.subtype.kind in ["i", "u"]: - msg = "Cannot set float NaN to integer-backed IntervalArray" - with pytest.raises(TypeError, match=msg): - result[result.notna()] = np.nan - else: - result[result.notna()] = np.nan + + result[result.notna()] = np.nan # Make sure original not changed tm.assert_series_equal(series, copy)
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45568
2022-01-23T05:14:56Z
2022-01-28T02:07:27Z
2022-01-28T02:07:27Z
2022-01-28T02:39:28Z
TST: Update error msg for Python 3.10
diff --git a/pandas/tests/io/json/test_ujson.py b/pandas/tests/io/json/test_ujson.py index b4ae54d48dc68..d2fb25ed6ea91 100644 --- a/pandas/tests/io/json/test_ujson.py +++ b/pandas/tests/io/json/test_ujson.py @@ -15,7 +15,6 @@ import pandas._libs.json as ujson from pandas.compat import ( IS64, - PY310, is_platform_windows, ) @@ -253,14 +252,8 @@ def test_double_precision(self): [ 20, -1, - pytest.param( - "9", - marks=pytest.mark.xfail(PY310, reason="Failing on Python 3.10 GH41940"), - ), - pytest.param( - None, - marks=pytest.mark.xfail(PY310, reason="Failing on Python 3.10 GH41940"), - ), + "9", + None, ], ) def test_invalid_double_precision(self, invalid_val): @@ -268,7 +261,8 @@ def test_invalid_double_precision(self, invalid_val): expected_exception = ValueError if isinstance(invalid_val, int) else TypeError msg = ( r"Invalid value '.*' for option 'double_precision', max is '15'|" - r"an integer is required \(got type " + r"an integer is required \(got type |" + r"object cannot be interpreted as an integer" ) with pytest.raises(expected_exception, match=msg): ujson.encode(double_input, double_precision=invalid_val)
- [ ] closes #41940 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45567
2022-01-23T03:38:25Z
2022-01-23T19:50:01Z
2022-01-23T19:50:01Z
2022-01-23T22:26:53Z
REGR: check_flags not respected in assert_frame_equal
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 21aab5058d25b..d0a58a19df92f 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -15,6 +15,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ - Regression in :meth:`Series.mask` with ``inplace=True`` and ``PeriodDtype`` and an incompatible ``other`` coercing to a common dtype instead of raising (:issue:`45546`) +- Regression in :func:`.assert_frame_equal` not respecting ``check_flags=False`` (:issue:`45554`) - Regression in :meth:`Series.fillna` with ``downcast=False`` incorrectly downcasting ``object`` dtype (:issue:`45603`) - Regression in :meth:`DataFrame.loc.__setitem__` losing :class:`Index` name if :class:`DataFrame` was empty before (:issue:`45621`) - diff --git a/pandas/_testing/asserters.py b/pandas/_testing/asserters.py index 84360403fe9c8..d850dcdb1f458 100644 --- a/pandas/_testing/asserters.py +++ b/pandas/_testing/asserters.py @@ -1344,6 +1344,7 @@ def assert_frame_equal( rtol=rtol, atol=atol, check_index=False, + check_flags=False, ) diff --git a/pandas/tests/util/test_assert_frame_equal.py b/pandas/tests/util/test_assert_frame_equal.py index faea0a54dc330..6ff1a1c17b179 100644 --- a/pandas/tests/util/test_assert_frame_equal.py +++ b/pandas/tests/util/test_assert_frame_equal.py @@ -323,9 +323,22 @@ def test_frame_equal_mixed_dtypes(frame_or_series, any_numeric_ea_dtype, indexer tm.assert_equal(obj1, obj2, check_exact=True, check_dtype=False) -def test_assert_series_equal_check_like_different_indexes(): +def test_assert_frame_equal_check_like_different_indexes(): # GH#39739 df1 = DataFrame(index=pd.Index([], dtype="object")) df2 = DataFrame(index=pd.RangeIndex(start=0, stop=0, step=1)) with pytest.raises(AssertionError, match="DataFrame.index are different"): tm.assert_frame_equal(df1, df2, check_like=True) + + +def test_assert_frame_equal_checking_allow_dups_flag(): + # GH#45554 + left = DataFrame([[1, 2], [3, 4]]) + left.flags.allows_duplicate_labels = False + + right = DataFrame([[1, 2], [3, 4]]) + right.flags.allows_duplicate_labels = True + tm.assert_frame_equal(left, right, check_flags=False) + + with pytest.raises(AssertionError, match="allows_duplicate_labels"): + tm.assert_frame_equal(left, right, check_flags=True)
- [x] closes #45554 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/45565
2022-01-23T03:20:09Z
2022-01-28T01:59:52Z
2022-01-28T01:59:51Z
2022-01-28T10:04:22Z
BUG: align not adding levels only on one side if intersection is equal
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index ea5258cf1537d..1084bcc1eeeb5 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -316,6 +316,7 @@ Indexing ^^^^^^^^ - Bug in :meth:`loc.__getitem__` with a list of keys causing an internal inconsistency that could lead to a disconnect between ``frame.at[x, y]`` vs ``frame[y].loc[x]`` (:issue:`22372`) - Bug in :meth:`DataFrame.iloc` where indexing a single row on a :class:`DataFrame` with a single ExtensionDtype column gave a copy instead of a view on the underlying data (:issue:`45241`) +- Bug in :meth:`Series.align` does not create :class:`MultiIndex` with union of levels when both MultiIndexes intersections are identical (:issue:`45224`) - Bug in setting a NA value (``None`` or ``np.nan``) into a :class:`Series` with int-based :class:`IntervalDtype` incorrectly casting to object dtype instead of a float-based :class:`IntervalDtype` (:issue:`45568`) - Bug in :meth:`Series.__setitem__` with a non-integer :class:`Index` when using an integer key to set a value that cannot be set inplace where a ``ValueError`` was raised instead of casting to a common dtype (:issue:`45070`) - Bug in :meth:`Series.__setitem__` when setting incompatible values into a ``PeriodDtype`` or ``IntervalDtype`` :class:`Series` raising when indexing with a boolean mask but coercing when indexing with otherwise-equivalent indexers; these now consistently coerce, along with :meth:`Series.mask` and :meth:`Series.where` (:issue:`45768`) diff --git a/pandas/core/series.py b/pandas/core/series.py index ea80f9d1ea04e..efbf8ecf74f1f 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4502,7 +4502,9 @@ def _reindex_indexer( ) -> Series: # Note: new_index is None iff indexer is None # if not None, indexer is np.intp - if indexer is None: + if indexer is None and ( + new_index is None or new_index.names == self.index.names + ): if copy: return self.copy() return self diff --git a/pandas/tests/series/methods/test_align.py b/pandas/tests/series/methods/test_align.py index 8769ab048a136..33e2b1ccecf2d 100644 --- a/pandas/tests/series/methods/test_align.py +++ b/pandas/tests/series/methods/test_align.py @@ -184,3 +184,41 @@ def test_align_periodindex(join_type): # TODO: assert something? ts.align(ts[::2], join=join_type) + + +def test_align_left_fewer_levels(): + # GH#45224 + left = Series([2], index=pd.MultiIndex.from_tuples([(1, 3)], names=["a", "c"])) + right = Series( + [1], index=pd.MultiIndex.from_tuples([(1, 2, 3)], names=["a", "b", "c"]) + ) + result_left, result_right = left.align(right) + + expected_right = Series( + [1], index=pd.MultiIndex.from_tuples([(1, 3, 2)], names=["a", "c", "b"]) + ) + expected_left = Series( + [2], index=pd.MultiIndex.from_tuples([(1, 3, 2)], names=["a", "c", "b"]) + ) + tm.assert_series_equal(result_left, expected_left) + tm.assert_series_equal(result_right, expected_right) + + +def test_align_left_different_named_levels(): + # GH#45224 + left = Series( + [2], index=pd.MultiIndex.from_tuples([(1, 4, 3)], names=["a", "d", "c"]) + ) + right = Series( + [1], index=pd.MultiIndex.from_tuples([(1, 2, 3)], names=["a", "b", "c"]) + ) + result_left, result_right = left.align(right) + + expected_left = Series( + [2], index=pd.MultiIndex.from_tuples([(1, 3, 4, 2)], names=["a", "c", "d", "b"]) + ) + expected_right = Series( + [1], index=pd.MultiIndex.from_tuples([(1, 3, 4, 2)], names=["a", "c", "d", "b"]) + ) + tm.assert_series_equal(result_left, expected_left) + tm.assert_series_equal(result_right, expected_right) diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index f2b561c77d246..1ffdb10369134 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -885,8 +885,8 @@ def test_series_varied_multiindex_alignment(): expected = Series( [1000, 2001, 3002, 4003], index=pd.MultiIndex.from_tuples( - [("a", "x", 1), ("a", "x", 2), ("a", "y", 1), ("a", "y", 2)], - names=["ab", "xy", "num"], + [("x", 1, "a"), ("x", 2, "a"), ("y", 1, "a"), ("y", 2, "a")], + names=["xy", "num", "ab"], ), ) tm.assert_series_equal(result, expected)
- [x] closes #45224 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry This is now consistent with the case when both sides do not have the same intersection of indexes
https://api.github.com/repos/pandas-dev/pandas/pulls/45564
2022-01-23T03:07:36Z
2022-02-15T01:02:31Z
2022-02-15T01:02:31Z
2022-02-15T12:49:30Z
Backport PR #45503 on branch 1.4.x (BLD: Fix pydata-sphix-theme version GH45374)
diff --git a/environment.yml b/environment.yml index 15dd329f80deb..9b8eec70a30e0 100644 --- a/environment.yml +++ b/environment.yml @@ -120,6 +120,6 @@ dependencies: - tabulate>=0.8.3 # DataFrame.to_markdown - natsort # DataFrame.sort_values - pip: - - git+https://github.com/pydata/pydata-sphinx-theme.git@master + - pydata-sphinx-theme - pandas-dev-flaker==0.2.0 - pytest-cython diff --git a/requirements-dev.txt b/requirements-dev.txt index f199d084371d9..45feaed939510 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -83,7 +83,7 @@ cftime pyreadstat tabulate>=0.8.3 natsort -git+https://github.com/pydata/pydata-sphinx-theme.git@master +pydata-sphinx-theme pandas-dev-flaker==0.2.0 pytest-cython setuptools>=51.0.0
Backport PR #45503: BLD: Fix pydata-sphix-theme version GH45374
https://api.github.com/repos/pandas-dev/pandas/pulls/45563
2022-01-23T02:30:23Z
2022-01-23T12:08:54Z
2022-01-23T12:08:54Z
2022-01-23T12:08:54Z
Backport PR #45546 on branch 1.4.x (REGR: changed behavior in series[period].mask(foo, bar, inplace=True))
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index f321aabc0a8a5..48b62637c26b1 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -14,7 +14,7 @@ including other versions of pandas. Fixed regressions ~~~~~~~~~~~~~~~~~ -- +- Regression in :meth:`Series.mask` with ``inplace=True`` and ``PeriodDtype`` and an incompatible ``other`` coercing to a common dtype instead of raising (:issue:`45546`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index aed7a6b84683a..1bc27c80ef58e 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1376,8 +1376,6 @@ def where(self, other, cond) -> list[Block]: # isinstance(values, NDArrayBackedExtensionArray) if isinstance(self.dtype, PeriodDtype): # TODO: don't special-case - # Note: this is the main place where the fallback logic - # is different from EABackedBlock.putmask. raise blk = self.coerce_to_target_dtype(other) nbs = blk.where(other, cond) @@ -1418,6 +1416,9 @@ def putmask(self, mask, new) -> list[Block]: elif isinstance(self, NDArrayBackedExtensionBlock): # NB: not (yet) the same as # isinstance(values, NDArrayBackedExtensionArray) + if isinstance(self.dtype, PeriodDtype): + # TODO: don't special-case + raise blk = self.coerce_to_target_dtype(new) return blk.putmask(mask, new) diff --git a/pandas/tests/frame/indexing/test_where.py b/pandas/tests/frame/indexing/test_where.py index 197c3ac9bd225..f0d66d040a35c 100644 --- a/pandas/tests/frame/indexing/test_where.py +++ b/pandas/tests/frame/indexing/test_where.py @@ -892,6 +892,9 @@ def test_where_period_invalid_na(frame_or_series, as_cat, request): with pytest.raises(TypeError, match=msg): obj.mask(mask, tdnat) + with pytest.raises(TypeError, match=msg): + obj.mask(mask, tdnat, inplace=True) + def test_where_nullable_invalid_na(frame_or_series, any_numeric_ea_dtype): # GH#44697
Backport PR #45546: REGR: changed behavior in series[period].mask(foo, bar, inplace=True)
https://api.github.com/repos/pandas-dev/pandas/pulls/45560
2022-01-23T00:06:22Z
2022-01-23T03:14:46Z
2022-01-23T03:14:46Z
2022-01-23T03:14:46Z
Backport PR #45507 on branch 1.4.x (CI: Troubleshoot)
diff --git a/pandas/tests/io/parser/test_unsupported.py b/pandas/tests/io/parser/test_unsupported.py index 0d383cc4bde8f..e223378b600e0 100644 --- a/pandas/tests/io/parser/test_unsupported.py +++ b/pandas/tests/io/parser/test_unsupported.py @@ -12,6 +12,7 @@ import pytest +from pandas.compat import is_platform_windows from pandas.errors import ParserError import pandas._testing as tm @@ -173,6 +174,9 @@ def test_close_file_handle_on_invalide_usecols(all_parsers): if parser.engine == "pyarrow": pyarrow = pytest.importorskip("pyarrow") error = pyarrow.lib.ArrowKeyError + if is_platform_windows(): + # GH#45547 causes timeouts on windows builds + pytest.skip("GH#45547 causing timeouts on windows builds 2022-01-22") with tm.ensure_clean("test.csv") as fname: Path(fname).write_text("col1,col2\na,b\n1,2")
Backport PR #45507: CI: Troubleshoot
https://api.github.com/repos/pandas-dev/pandas/pulls/45559
2022-01-22T22:34:56Z
2022-01-22T23:46:15Z
2022-01-22T23:46:15Z
2022-01-22T23:46:15Z
BUG: Segfault in to_json with tzaware datetime
diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst index 48b62637c26b1..79dae514b77e9 100644 --- a/doc/source/whatsnew/v1.4.1.rst +++ b/doc/source/whatsnew/v1.4.1.rst @@ -23,7 +23,7 @@ Fixed regressions Bug fixes ~~~~~~~~~ -- +- Fixed segfault in :meth:``DataFrame.to_json`` when dumping tz-aware datetimes in Python 3.10 (:issue:`42130`) - .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/src/datetime/np_datetime.c b/pandas/_libs/tslibs/src/datetime/np_datetime.c index 9ad2ead5f919f..0efed210a7fdf 100644 --- a/pandas/_libs/tslibs/src/datetime/np_datetime.c +++ b/pandas/_libs/tslibs/src/datetime/np_datetime.c @@ -360,6 +360,7 @@ int convert_pydatetime_to_datetimestruct(PyObject *dtobj, Py_DECREF(tmp); } else { PyObject *offset; + PyObject *tmp_int; int seconds_offset, minutes_offset; /* The utcoffset function should return a timedelta */ @@ -378,11 +379,18 @@ int convert_pydatetime_to_datetimestruct(PyObject *dtobj, if (tmp == NULL) { return -1; } - seconds_offset = PyInt_AsLong(tmp); + tmp_int = PyNumber_Long(tmp); + if (tmp_int == NULL) { + Py_DECREF(tmp); + return -1; + } + seconds_offset = PyInt_AsLong(tmp_int); if (seconds_offset == -1 && PyErr_Occurred()) { + Py_DECREF(tmp_int); Py_DECREF(tmp); return -1; } + Py_DECREF(tmp_int); Py_DECREF(tmp); /* Convert to a minutes offset and apply it */ diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 0b8548f98b03b..f3a6f1f80359c 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -11,7 +11,6 @@ from pandas.compat import ( IS64, - PY310, is_platform_windows, ) import pandas.util._test_decorators as td @@ -1177,7 +1176,6 @@ def test_sparse(self): expected = s.to_json() assert expected == ss.to_json() - @pytest.mark.skipif(PY310, reason="segfault GH 42130") @pytest.mark.parametrize( "ts", [ @@ -1195,7 +1193,6 @@ def test_tz_is_utc(self, ts): dt = ts.to_pydatetime() assert dumps(dt, iso_dates=True) == exp - @pytest.mark.skipif(PY310, reason="segfault GH 42130") @pytest.mark.parametrize( "tz_range", [
- [ ] closes #42130 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry Basically, timedelta.total_seconds returns a float. PyInt_AsLong(actually PyLong_AsLong) wants an int, but would cast using __int__ for Pythons < 3.10. This stopped happening in python 3.10. (https://docs.python.org/3/c-api/long.html#c.PyLong_AsLong). IMO, it probably is fine to cast the result from float to int, as I don't think that any timezone has an offset from UTC that contains fractions of a second. But, I could be wrong given that I don't use timezones and are not too familiar with them.
https://api.github.com/repos/pandas-dev/pandas/pulls/45558
2022-01-22T21:29:22Z
2022-01-24T07:02:37Z
2022-01-24T07:02:37Z
2022-01-24T14:22:00Z
Backport PR #45555 on branch 1.4.x (WEB: update web/pandas/versions.json for docs dropdown menu)
diff --git a/web/pandas/versions.json b/web/pandas/versions.json index 76c06210e2238..2ad317c50fef1 100644 --- a/web/pandas/versions.json +++ b/web/pandas/versions.json @@ -4,13 +4,9 @@ "version": "docs/dev" }, { - "name": "1.4 (rc)", + "name": "1.4 (stable)", "version": "pandas-docs/version/1.4" }, - { - "name": "1.3 (stable)", - "version": "docs" - }, { "name": "1.3", "version": "pandas-docs/version/1.3"
Backport PR #45555: WEB: update web/pandas/versions.json for docs dropdown menu
https://api.github.com/repos/pandas-dev/pandas/pulls/45556
2022-01-22T21:12:58Z
2022-01-22T23:46:43Z
2022-01-22T23:46:43Z
2022-01-22T23:46:43Z
WEB: update web/pandas/versions.json for docs dropdown menu
diff --git a/web/pandas/versions.json b/web/pandas/versions.json index 76c06210e2238..2ad317c50fef1 100644 --- a/web/pandas/versions.json +++ b/web/pandas/versions.json @@ -4,13 +4,9 @@ "version": "docs/dev" }, { - "name": "1.4 (rc)", + "name": "1.4 (stable)", "version": "pandas-docs/version/1.4" }, - { - "name": "1.3 (stable)", - "version": "docs" - }, { "name": "1.3", "version": "pandas-docs/version/1.3"
I don't think the milestone is relevant for web updates so backport not needed?
https://api.github.com/repos/pandas-dev/pandas/pulls/45555
2022-01-22T19:55:47Z
2022-01-22T21:12:49Z
2022-01-22T21:12:49Z
2022-01-24T14:37:58Z
Backport PR #45550 on branch 1.4.x (DOC: start v1.4.1 release notes)
diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst index df33174804a33..a3214834fb764 100644 --- a/doc/source/whatsnew/index.rst +++ b/doc/source/whatsnew/index.rst @@ -16,6 +16,7 @@ Version 1.4 .. toctree:: :maxdepth: 2 + v1.4.1 v1.4.0 Version 1.3 diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 363d4b57544a9..47a087d38d146 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -1090,4 +1090,4 @@ Other Contributors ~~~~~~~~~~~~ -.. contributors:: v1.3.5..v1.4.0|HEAD +.. contributors:: v1.3.5..v1.4.0 diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst new file mode 100644 index 0000000000000..f321aabc0a8a5 --- /dev/null +++ b/doc/source/whatsnew/v1.4.1.rst @@ -0,0 +1,45 @@ +.. _whatsnew_141: + +What's new in 1.4.1 (February ??, 2022) +--------------------------------------- + +These are the changes in pandas 1.4.1. See :ref:`release` for a full changelog +including other versions of pandas. + +{{ header }} + +.. --------------------------------------------------------------------------- + +.. _whatsnew_141.regressions: + +Fixed regressions +~~~~~~~~~~~~~~~~~ +- +- + +.. --------------------------------------------------------------------------- + +.. _whatsnew_141.bug_fixes: + +Bug fixes +~~~~~~~~~ +- +- + +.. --------------------------------------------------------------------------- + +.. _whatsnew_141.other: + +Other +~~~~~ +- +- + +.. --------------------------------------------------------------------------- + +.. _whatsnew_141.contributors: + +Contributors +~~~~~~~~~~~~ + +.. contributors:: v1.4.0..v1.4.1|HEAD
Backport PR #45550: DOC: start v1.4.1 release notes
https://api.github.com/repos/pandas-dev/pandas/pulls/45552
2022-01-22T12:39:37Z
2022-01-22T13:53:36Z
2022-01-22T13:53:36Z
2022-01-22T13:53:36Z
DOC: start v1.4.1 release notes
diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst index 026d998613b16..cb38166fcbc70 100644 --- a/doc/source/whatsnew/index.rst +++ b/doc/source/whatsnew/index.rst @@ -24,6 +24,7 @@ Version 1.4 .. toctree:: :maxdepth: 2 + v1.4.1 v1.4.0 Version 1.3 diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 363d4b57544a9..47a087d38d146 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -1090,4 +1090,4 @@ Other Contributors ~~~~~~~~~~~~ -.. contributors:: v1.3.5..v1.4.0|HEAD +.. contributors:: v1.3.5..v1.4.0 diff --git a/doc/source/whatsnew/v1.4.1.rst b/doc/source/whatsnew/v1.4.1.rst new file mode 100644 index 0000000000000..f321aabc0a8a5 --- /dev/null +++ b/doc/source/whatsnew/v1.4.1.rst @@ -0,0 +1,45 @@ +.. _whatsnew_141: + +What's new in 1.4.1 (February ??, 2022) +--------------------------------------- + +These are the changes in pandas 1.4.1. See :ref:`release` for a full changelog +including other versions of pandas. + +{{ header }} + +.. --------------------------------------------------------------------------- + +.. _whatsnew_141.regressions: + +Fixed regressions +~~~~~~~~~~~~~~~~~ +- +- + +.. --------------------------------------------------------------------------- + +.. _whatsnew_141.bug_fixes: + +Bug fixes +~~~~~~~~~ +- +- + +.. --------------------------------------------------------------------------- + +.. _whatsnew_141.other: + +Other +~~~~~ +- +- + +.. --------------------------------------------------------------------------- + +.. _whatsnew_141.contributors: + +Contributors +~~~~~~~~~~~~ + +.. contributors:: v1.4.0..v1.4.1|HEAD
null
https://api.github.com/repos/pandas-dev/pandas/pulls/45550
2022-01-22T11:35:48Z
2022-01-22T12:39:09Z
2022-01-22T12:39:09Z
2022-01-22T12:39:12Z
DOC: Shared doc string in render methods
diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 6293ad6ae3ddf..432e12f303919 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -97,6 +97,15 @@ def _mpl(func: Callable): color = """color : str, default 'yellow' Background color to use for highlighting.""" +buf = """buf : str, path object, file-like object, optional + String, path object (implementing ``os.PathLike[str]``), or file-like + object implementing a string ``write()`` function. If ``None``, the result is + returned as a string.""" + +encoding = """encoding : str, optional + Character encoding setting for file output (and meta tags if available). + Defaults to ``pandas.options.styler.render.encoding`` value of "utf-8".""" + # ### @@ -1053,6 +1062,7 @@ def to_latex( latex, buf=buf, encoding=None if buf is None else encoding ) + @Substitution(buf=buf, encoding=encoding) def to_html( self, buf: FilePath | WriteBuffer[str] | None = None, @@ -1077,10 +1087,7 @@ def to_html( Parameters ---------- - buf : str, path object, file-like object, or None, default None - String, path object (implementing ``os.PathLike[str]``), or file-like - object implementing a string ``write()`` function. If None, the result is - returned as a string. + %(buf)s table_uuid : str, optional Id attribute assigned to the <table> HTML element in the format: @@ -1127,9 +1134,7 @@ def to_html( which is 262144 (18 bit browser rendering). .. versionadded:: 1.4.0 - encoding : str, optional - Character encoding setting for file output, and HTML meta tags. - Defaults to ``pandas.options.styler.render.encoding`` value of "utf-8". + %(encoding)s doctype_html : bool, default False Whether to output a fully structured HTML file including all HTML elements, or just the core ``<style>`` and ``<table>`` elements. @@ -1189,6 +1194,7 @@ def to_html( html, buf=buf, encoding=(encoding if buf is not None else None) ) + @Substitution(buf=buf, encoding=encoding) def to_string( self, buf=None, @@ -1207,11 +1213,8 @@ def to_string( Parameters ---------- - buf : str, Path, or StringIO-like, optional, default None - Buffer to write to. If ``None``, the output is returned as a string. - encoding : str, optional - Character encoding setting for file output. - Defaults to ``pandas.options.styler.render.encoding`` value of "utf-8". + %(buf)s + %(encoding)s sparse_index : bool, optional Whether to sparsify the display of a hierarchical index. Setting to False will display each explicit level element in a hierarchical key for each row.
null
https://api.github.com/repos/pandas-dev/pandas/pulls/45548
2022-01-22T08:19:38Z
2022-01-25T17:32:36Z
2022-01-25T17:32:35Z
2022-02-21T06:21:29Z
CLN: clean setup.py
diff --git a/setup.py b/setup.py index 9a9d12ce4d2ba..78a789c808efb 100755 --- a/setup.py +++ b/setup.py @@ -7,6 +7,7 @@ """ import argparse +from distutils.command.build import build from distutils.sysconfig import get_config_vars from distutils.version import LooseVersion import multiprocessing @@ -16,10 +17,10 @@ import shutil import sys -import pkg_resources -from setuptools import Command, find_packages, setup +import numpy +from setuptools import Command, Extension, find_packages, setup +from setuptools.command.build_ext import build_ext as _build_ext -# versioning import versioneer cmdclass = versioneer.get_cmdclass() @@ -37,9 +38,7 @@ def is_platform_mac(): min_cython_ver = "0.29.21" # note: sync with pyproject.toml try: - import Cython - - _CYTHON_VERSION = Cython.__version__ + from Cython import Tempita, __version__ as _CYTHON_VERSION from Cython.Build import cythonize _CYTHON_INSTALLED = _CYTHON_VERSION >= LooseVersion(min_cython_ver) @@ -48,22 +47,6 @@ def is_platform_mac(): _CYTHON_INSTALLED = False cythonize = lambda x, *args, **kwargs: x # dummy func -# The import of Extension must be after the import of Cython, otherwise -# we do not get the appropriately patched class. -# See https://cython.readthedocs.io/en/latest/src/userguide/source_files_and_compilation.html # noqa -from distutils.extension import Extension # isort:skip -from distutils.command.build import build # isort:skip - -if _CYTHON_INSTALLED: - from Cython.Distutils.old_build_ext import old_build_ext as _build_ext - - cython = True - from Cython import Tempita as tempita -else: - from distutils.command.build_ext import build_ext as _build_ext - - cython = False - _pxi_dep_template = { "algos": ["_libs/algos_common_helper.pxi.in", "_libs/algos_take_helper.pxi.in"], @@ -101,7 +84,7 @@ def render_templates(cls, pxifiles): with open(pxifile) as f: tmpl = f.read() - pyxcontent = tempita.sub(tmpl) + pyxcontent = Tempita.sub(tmpl) with open(outfile, "w") as f: f.write(pyxcontent) @@ -109,7 +92,7 @@ def render_templates(cls, pxifiles): def build_extensions(self): # if building from c files, don't need to # generate template output - if cython: + if _CYTHON_INSTALLED: self.render_templates(_pxifiles) super().build_extensions() @@ -404,7 +387,7 @@ def run(self): cmdclass.update({"clean": CleanCommand, "build": build}) cmdclass["build_ext"] = CheckingBuildExt -if cython: +if _CYTHON_INSTALLED: suffix = ".pyx" cmdclass["cython"] = CythonCommand else: @@ -477,18 +460,10 @@ def run(self): directives["linetrace"] = True macros = [("CYTHON_TRACE", "1"), ("CYTHON_TRACE_NOGIL", "1")] -# in numpy>=1.16.0, silence build warnings about deprecated API usage -# we can't do anything about these warnings because they stem from -# cython+numpy version mismatches. +# silence build warnings about deprecated API usage +# we can't do anything about these warnings because they stem from +# cython+numpy version mismatches. macros.append(("NPY_NO_DEPRECATED_API", "0")) -if "-Werror" in extra_compile_args: - try: - import numpy as np - except ImportError: - pass - else: - if np.__version__ < LooseVersion("1.16.0"): - extra_compile_args.remove("-Werror") # ---------------------------------------------------------------------- @@ -507,7 +482,7 @@ def maybe_cythonize(extensions, *args, **kwargs): # See https://github.com/cython/cython/issues/1495 return extensions - elif not cython: + elif not _CYTHON_INSTALLED: # GH#28836 raise a helfpul error message if _CYTHON_VERSION: raise RuntimeError( @@ -516,25 +491,12 @@ def maybe_cythonize(extensions, *args, **kwargs): ) raise RuntimeError("Cannot cythonize without Cython installed.") - numpy_incl = pkg_resources.resource_filename("numpy", "core/include") - # TODO: Is this really necessary here? - for ext in extensions: - if hasattr(ext, "include_dirs") and numpy_incl not in ext.include_dirs: - ext.include_dirs.append(numpy_incl) - # reuse any parallel arguments provided for compilation to cythonize parser = argparse.ArgumentParser() - parser.add_argument("-j", type=int) - parser.add_argument("--parallel", type=int) + parser.add_argument("--parallel", "-j", type=int, default=1) parsed, _ = parser.parse_known_args() - nthreads = 0 - if parsed.parallel: - nthreads = parsed.parallel - elif parsed.j: - nthreads = parsed.j - - kwargs["nthreads"] = nthreads + kwargs["nthreads"] = parsed.parallel build_ext.render_templates(_pxifiles) return cythonize(extensions, *args, **kwargs) @@ -679,7 +641,8 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): sources.extend(data.get("sources", [])) - include = data.get("include") + include = data.get("include", []) + include.append(numpy.get_include()) obj = Extension( f"pandas.{name}", @@ -728,6 +691,7 @@ def srcpath(name=None, suffix=".pyx", subdir="src"): "pandas/_libs/src/ujson/python", "pandas/_libs/src/ujson/lib", "pandas/_libs/src/datetime", + numpy.get_include(), ], extra_compile_args=(["-D_GNU_SOURCE"] + extra_compile_args), extra_link_args=extra_link_args,
an attempt to clean setup.py
https://api.github.com/repos/pandas-dev/pandas/pulls/37732
2020-11-10T04:04:44Z
2020-11-14T16:53:31Z
2020-11-14T16:53:30Z
2021-01-09T17:10:58Z
REF: use extract_array in DataFrame.combine_first
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 80743f8cc924b..4fa0b59808a52 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -114,7 +114,6 @@ is_object_dtype, is_scalar, is_sequence, - needs_i8_conversion, pandas_dtype, ) from pandas.core.dtypes.missing import isna, notna @@ -6369,29 +6368,11 @@ def combine_first(self, other: DataFrame) -> DataFrame: """ import pandas.core.computation.expressions as expressions - def extract_values(arr): - # Does two things: - # 1. maybe gets the values from the Series / Index - # 2. convert datelike to i8 - # TODO: extract_array? - if isinstance(arr, (Index, Series)): - arr = arr._values - - if needs_i8_conversion(arr.dtype): - if is_extension_array_dtype(arr.dtype): - arr = arr.asi8 - else: - arr = arr.view("i8") - return arr - def combiner(x, y): - mask = isna(x) - # TODO: extract_array? - if isinstance(mask, (Index, Series)): - mask = mask._values + mask = extract_array(isna(x)) - x_values = extract_values(x) - y_values = extract_values(y) + x_values = extract_array(x, extract_numpy=True) + y_values = extract_array(y, extract_numpy=True) # If the column y in other DataFrame is not in first DataFrame, # just return y_values.
- [ ] 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/37731
2020-11-10T03:03:16Z
2020-11-11T00:58:34Z
2020-11-11T00:58:34Z
2020-11-11T00:58:38Z
TST/REF: collect/parametrize tests from tests.generic
diff --git a/pandas/tests/frame/test_alter_axes.py b/pandas/tests/frame/test_alter_axes.py index 4bd1d5fa56468..862f5b87785f5 100644 --- a/pandas/tests/frame/test_alter_axes.py +++ b/pandas/tests/frame/test_alter_axes.py @@ -1,6 +1,8 @@ from datetime import datetime import numpy as np +import pytest +import pytz from pandas.core.dtypes.common import ( is_categorical_dtype, @@ -17,19 +19,16 @@ Timestamp, cut, date_range, - to_datetime, ) import pandas._testing as tm class TestDataFrameAlterAxes: - def test_convert_dti_to_series(self): - # don't cast a DatetimeIndex WITH a tz, leave as object - # GH 6032 - idx = DatetimeIndex( - to_datetime(["2013-1-1 13:00", "2013-1-2 14:00"]), name="B" - ).tz_localize("US/Pacific") - df = DataFrame(np.random.randn(2, 1), columns=["A"]) + @pytest.fixture + def idx_expected(self): + idx = DatetimeIndex(["2013-1-1 13:00", "2013-1-2 14:00"], name="B").tz_localize( + "US/Pacific" + ) expected = Series( np.array( @@ -41,49 +40,76 @@ def test_convert_dti_to_series(self): ), name="B", ) + assert expected.dtype == idx.dtype + return idx, expected - # convert index to series - result = Series(idx) - tm.assert_series_equal(result, expected) - - # assign to frame - df["B"] = idx - result = df["B"] - tm.assert_series_equal(result, expected) - + def test_to_series_keep_tz_deprecated_true(self, idx_expected): # convert to series while keeping the timezone + idx, expected = idx_expected + msg = "stop passing 'keep_tz'" with tm.assert_produces_warning(FutureWarning) as m: result = idx.to_series(keep_tz=True, index=[0, 1]) + assert msg in str(m[0].message) + tm.assert_series_equal(result, expected) + + def test_to_series_keep_tz_deprecated_false(self, idx_expected): + idx, expected = idx_expected + + with tm.assert_produces_warning(FutureWarning) as m: + result = idx.to_series(keep_tz=False, index=[0, 1]) + tm.assert_series_equal(result, expected.dt.tz_convert(None)) + msg = "do 'idx.tz_convert(None)' before calling" assert msg in str(m[0].message) + def test_setitem_dt64series(self, idx_expected): # convert to utc + idx, expected = idx_expected + df = DataFrame(np.random.randn(2, 1), columns=["A"]) + df["B"] = idx + with tm.assert_produces_warning(FutureWarning) as m: df["B"] = idx.to_series(keep_tz=False, index=[0, 1]) - result = df["B"] - comp = Series(DatetimeIndex(expected.values).tz_localize(None), name="B") - tm.assert_series_equal(result, comp) msg = "do 'idx.tz_convert(None)' before calling" assert msg in str(m[0].message) - result = idx.to_series(index=[0, 1]) + result = df["B"] + comp = Series(idx.tz_convert("UTC").tz_localize(None), name="B") + tm.assert_series_equal(result, comp) + + def test_setitem_datetimeindex(self, idx_expected): + # setting a DataFrame column with a tzaware DTI retains the dtype + idx, expected = idx_expected + df = DataFrame(np.random.randn(2, 1), columns=["A"]) + + # assign to frame + df["B"] = idx + result = df["B"] tm.assert_series_equal(result, expected) - with tm.assert_produces_warning(FutureWarning) as m: - result = idx.to_series(keep_tz=False, index=[0, 1]) - tm.assert_series_equal(result, expected.dt.tz_convert(None)) - msg = "do 'idx.tz_convert(None)' before calling" - assert msg in str(m[0].message) + def test_setitem_object_array_of_tzaware_datetimes(self, idx_expected): + # setting a DataFrame column with a tzaware DTI retains the dtype + idx, expected = idx_expected + df = DataFrame(np.random.randn(2, 1), columns=["A"]) - # list of datetimes with a tz + # object array of datetimes with a tz df["B"] = idx.to_pydatetime() result = df["B"] tm.assert_series_equal(result, expected) + def test_constructor_from_tzaware_datetimeindex(self, idx_expected): + # don't cast a DatetimeIndex WITH a tz, leave as object + # GH 6032 + idx, expected = idx_expected + + # convert index to series + result = Series(idx) + tm.assert_series_equal(result, expected) + + def test_set_axis_setattr_index(self): # GH 6785 # set the index manually - import pytz df = DataFrame([{"ts": datetime(2014, 4, 1, tzinfo=pytz.utc), "foo": 1}]) expected = df.set_index("ts") @@ -102,6 +128,7 @@ def test_dti_set_index_reindex(self): df = df.reindex(idx2) tm.assert_index_equal(df.index, idx2) + def test_dti_set_index_reindex_with_tz(self): # GH 11314 # with tz index = date_range( @@ -130,16 +157,16 @@ class TestIntervalIndex: def test_setitem(self): df = DataFrame({"A": range(10)}) - s = cut(df.A, 5) - assert isinstance(s.cat.categories, IntervalIndex) + ser = cut(df["A"], 5) + assert isinstance(ser.cat.categories, IntervalIndex) # B & D end up as Categoricals # the remainer are converted to in-line objects # contining an IntervalIndex.values - df["B"] = s - df["C"] = np.array(s) - df["D"] = s.values - df["E"] = np.array(s.values) + df["B"] = ser + df["C"] = np.array(ser) + df["D"] = ser.values + df["E"] = np.array(ser.values) assert is_categorical_dtype(df["B"].dtype) assert is_interval_dtype(df["B"].cat.categories) @@ -152,17 +179,17 @@ def test_setitem(self): # they compare equal as Index # when converted to numpy objects c = lambda x: Index(np.array(x)) - tm.assert_index_equal(c(df.B), c(df.B), check_names=False) + tm.assert_index_equal(c(df.B), c(df.B)) tm.assert_index_equal(c(df.B), c(df.C), check_names=False) tm.assert_index_equal(c(df.B), c(df.D), check_names=False) - tm.assert_index_equal(c(df.B), c(df.D), check_names=False) + tm.assert_index_equal(c(df.C), c(df.D), check_names=False) # B & D are the same Series - tm.assert_series_equal(df["B"], df["B"], check_names=False) + tm.assert_series_equal(df["B"], df["B"]) tm.assert_series_equal(df["B"], df["D"], check_names=False) # C & E are the same Series - tm.assert_series_equal(df["C"], df["C"], check_names=False) + tm.assert_series_equal(df["C"], df["C"]) tm.assert_series_equal(df["C"], df["E"], check_names=False) def test_set_reset_index(self): diff --git a/pandas/tests/frame/test_logical_ops.py b/pandas/tests/frame/test_logical_ops.py index fb7a6e586c460..efabc666993ee 100644 --- a/pandas/tests/frame/test_logical_ops.py +++ b/pandas/tests/frame/test_logical_ops.py @@ -11,6 +11,42 @@ class TestDataFrameLogicalOperators: # &, |, ^ + @pytest.mark.parametrize( + "left, right, op, expected", + [ + ( + [True, False, np.nan], + [True, False, True], + operator.and_, + [True, False, False], + ), + ( + [True, False, True], + [True, False, np.nan], + operator.and_, + [True, False, False], + ), + ( + [True, False, np.nan], + [True, False, True], + operator.or_, + [True, False, False], + ), + ( + [True, False, True], + [True, False, np.nan], + operator.or_, + [True, False, True], + ), + ], + ) + def test_logical_operators_nans(self, left, right, op, expected, frame_or_series): + # GH#13896 + result = op(frame_or_series(left), frame_or_series(right)) + expected = frame_or_series(expected) + + tm.assert_equal(result, expected) + def test_logical_ops_empty_frame(self): # GH#5808 # empty frames, non-mixed dtype diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index 1c54855ee7bce..109561a5acb23 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -6,13 +6,15 @@ import pandas._testing as tm +def check(result, expected=None): + if expected is not None: + tm.assert_frame_equal(result, expected) + result.dtypes + str(result) + + class TestDataFrameNonuniqueIndexes: def test_column_dups_operations(self): - def check(result, expected=None): - if expected is not None: - tm.assert_frame_equal(result, expected) - result.dtypes - str(result) # assignment # GH 3687 @@ -308,13 +310,7 @@ def test_column_dups2(self): result = df.dropna(subset=["A", "C"], how="all") tm.assert_frame_equal(result, expected) - def test_column_dups_indexing(self): - def check(result, expected=None): - if expected is not None: - tm.assert_frame_equal(result, expected) - result.dtypes - str(result) - + def test_getitem_boolean_series_with_duplicate_columns(self): # boolean indexing # GH 4879 dups = ["A", "A", "C", "D"] @@ -327,22 +323,32 @@ def check(result, expected=None): result = df[df.C > 6] check(result, expected) + def test_getitem_boolean_frame_with_duplicate_columns(self): + dups = ["A", "A", "C", "D"] + # where df = DataFrame( np.arange(12).reshape(3, 4), columns=["A", "B", "C", "D"], dtype="float64" ) + # `df > 6` is a DataFrame with the same shape+alignment as df expected = df[df > 6] expected.columns = dups df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype="float64") result = df[df > 6] check(result, expected) + def test_getitem_boolean_frame_unaligned_with_duplicate_columns(self): + # `df.A > 6` is a DataFrame with a different shape from df + dups = ["A", "A", "C", "D"] + # boolean with the duplicate raises df = DataFrame(np.arange(12).reshape(3, 4), columns=dups, dtype="float64") msg = "cannot reindex from a duplicate axis" with pytest.raises(ValueError, match=msg): df[df.A > 6] + def test_column_dups_indexing(self): + # dup aligning operations should work # GH 5185 df1 = DataFrame([1, 2, 3, 4, 5], index=[1, 2, 1, 2, 3]) diff --git a/pandas/tests/generic/test_generic.py b/pandas/tests/generic/test_generic.py index 7fde448bb36dc..6a18810700205 100644 --- a/pandas/tests/generic/test_generic.py +++ b/pandas/tests/generic/test_generic.py @@ -383,20 +383,22 @@ def test_transpose(self): for df in [tm.makeTimeDataFrame()]: tm.assert_frame_equal(df.transpose().transpose(), df) - def test_numpy_transpose(self): - msg = "the 'axes' parameter is not supported" + def test_numpy_transpose(self, frame_or_series): - s = tm.makeFloatSeries() - tm.assert_series_equal(np.transpose(s), s) + obj = tm.makeTimeDataFrame() + if frame_or_series is Series: + obj = obj["A"] - with pytest.raises(ValueError, match=msg): - np.transpose(s, axes=1) + if frame_or_series is Series: + # 1D -> np.transpose is no-op + tm.assert_series_equal(np.transpose(obj), obj) - df = tm.makeTimeDataFrame() - tm.assert_frame_equal(np.transpose(np.transpose(df)), df) + # round-trip preserved + tm.assert_equal(np.transpose(np.transpose(obj)), obj) + msg = "the 'axes' parameter is not supported" with pytest.raises(ValueError, match=msg): - np.transpose(df, axes=1) + np.transpose(obj, axes=1) def test_take(self): indices = [1, 5, -2, 6, 3, -1] @@ -415,23 +417,24 @@ def test_take(self): ) tm.assert_frame_equal(out, expected) - def test_take_invalid_kwargs(self): + def test_take_invalid_kwargs(self, frame_or_series): indices = [-3, 2, 0, 1] - s = tm.makeFloatSeries() - df = tm.makeTimeDataFrame() - for obj in (s, df): - msg = r"take\(\) got an unexpected keyword argument 'foo'" - with pytest.raises(TypeError, match=msg): - obj.take(indices, foo=2) + obj = tm.makeTimeDataFrame() + if frame_or_series is Series: + obj = obj["A"] + + msg = r"take\(\) got an unexpected keyword argument 'foo'" + with pytest.raises(TypeError, match=msg): + obj.take(indices, foo=2) - msg = "the 'out' parameter is not supported" - with pytest.raises(ValueError, match=msg): - obj.take(indices, out=indices) + msg = "the 'out' parameter is not supported" + with pytest.raises(ValueError, match=msg): + obj.take(indices, out=indices) - msg = "the 'mode' parameter is not supported" - with pytest.raises(ValueError, match=msg): - obj.take(indices, mode="clip") + msg = "the 'mode' parameter is not supported" + with pytest.raises(ValueError, match=msg): + obj.take(indices, mode="clip") @pytest.mark.parametrize("is_copy", [True, False]) def test_depr_take_kwarg_is_copy(self, is_copy, frame_or_series): @@ -473,21 +476,19 @@ def test_axis_numbers_deprecated(self, frame_or_series): obj._AXIS_NUMBERS def test_flags_identity(self, frame_or_series): - s = Series([1, 2]) + obj = Series([1, 2]) if frame_or_series is DataFrame: - s = s.to_frame() + obj = obj.to_frame() - assert s.flags is s.flags - s2 = s.copy() - assert s2.flags is not s.flags + assert obj.flags is obj.flags + obj2 = obj.copy() + assert obj2.flags is not obj.flags - def test_slice_shift_deprecated(self): + def test_slice_shift_deprecated(self, frame_or_series): # GH 37601 - df = DataFrame({"A": [1, 2, 3, 4]}) - s = Series([1, 2, 3, 4]) - - with tm.assert_produces_warning(FutureWarning): - df["A"].slice_shift() + obj = DataFrame({"A": [1, 2, 3, 4]}) + if frame_or_series is DataFrame: + obj = obj["A"] with tm.assert_produces_warning(FutureWarning): - s.slice_shift() + obj.slice_shift() diff --git a/pandas/tests/generic/test_logical_ops.py b/pandas/tests/generic/test_logical_ops.py deleted file mode 100644 index 58185cbd9a40f..0000000000000 --- a/pandas/tests/generic/test_logical_ops.py +++ /dev/null @@ -1,49 +0,0 @@ -""" -Shareable tests for &, |, ^ -""" -import operator - -import numpy as np -import pytest - -from pandas import DataFrame, Series -import pandas._testing as tm - - -class TestLogicalOps: - @pytest.mark.parametrize( - "left, right, op, expected", - [ - ( - [True, False, np.nan], - [True, False, True], - operator.and_, - [True, False, False], - ), - ( - [True, False, True], - [True, False, np.nan], - operator.and_, - [True, False, False], - ), - ( - [True, False, np.nan], - [True, False, True], - operator.or_, - [True, False, False], - ), - ( - [True, False, True], - [True, False, np.nan], - operator.or_, - [True, False, True], - ), - ], - ) - @pytest.mark.parametrize("klass", [Series, DataFrame]) - def test_logical_operators_nans(self, left, right, op, expected, klass): - # GH#13896 - result = op(klass(left), klass(right)) - expected = klass(expected) - - tm.assert_equal(result, expected) diff --git a/pandas/tests/generic/test_to_xarray.py b/pandas/tests/generic/test_to_xarray.py index a85d7ddc1ea53..a6aa45406305c 100644 --- a/pandas/tests/generic/test_to_xarray.py +++ b/pandas/tests/generic/test_to_xarray.py @@ -3,34 +3,35 @@ import pandas.util._test_decorators as td -import pandas as pd -from pandas import DataFrame, Series +from pandas import Categorical, DataFrame, MultiIndex, Series, date_range import pandas._testing as tm class TestDataFrameToXArray: - @td.skip_if_no("xarray", "0.10.0") - def test_to_xarray_index_types(self, index): - if isinstance(index, pd.MultiIndex): - pytest.skip("MultiIndex is tested separately") - if len(index) == 0: - pytest.skip("Test doesn't make sense for empty index") - - from xarray import Dataset - - df = DataFrame( + @pytest.fixture + def df(self): + return DataFrame( { "a": list("abc"), "b": list(range(1, 4)), "c": np.arange(3, 6).astype("u1"), "d": np.arange(4.0, 7.0, dtype="float64"), "e": [True, False, True], - "f": pd.Categorical(list("abc")), - "g": pd.date_range("20130101", periods=3), - "h": pd.date_range("20130101", periods=3, tz="US/Eastern"), + "f": Categorical(list("abc")), + "g": date_range("20130101", periods=3), + "h": date_range("20130101", periods=3, tz="US/Eastern"), } ) + @td.skip_if_no("xarray", "0.10.0") + def test_to_xarray_index_types(self, index, df): + if isinstance(index, MultiIndex): + pytest.skip("MultiIndex is tested separately") + if len(index) == 0: + pytest.skip("Test doesn't make sense for empty index") + + from xarray import Dataset + df.index = index[:3] df.index.name = "foo" df.columns.name = "bar" @@ -50,30 +51,21 @@ def test_to_xarray_index_types(self, index): tm.assert_frame_equal(result.to_dataframe(), expected) @td.skip_if_no("xarray", min_version="0.7.0") - def test_to_xarray(self): + def test_to_xarray_empty(self, df): from xarray import Dataset - df = DataFrame( - { - "a": list("abc"), - "b": list(range(1, 4)), - "c": np.arange(3, 6).astype("u1"), - "d": np.arange(4.0, 7.0, dtype="float64"), - "e": [True, False, True], - "f": pd.Categorical(list("abc")), - "g": pd.date_range("20130101", periods=3), - "h": pd.date_range("20130101", periods=3, tz="US/Eastern"), - } - ) - df.index.name = "foo" result = df[0:0].to_xarray() assert result.dims["foo"] == 0 assert isinstance(result, Dataset) + @td.skip_if_no("xarray", min_version="0.7.0") + def test_to_xarray_with_multiindex(self, df): + from xarray import Dataset + # available in 0.7.1 # MultiIndex - df.index = pd.MultiIndex.from_product([["a"], range(3)], names=["one", "two"]) + df.index = MultiIndex.from_product([["a"], range(3)], names=["one", "two"]) result = df.to_xarray() assert result.dims["one"] == 1 assert result.dims["two"] == 3 @@ -86,20 +78,20 @@ def test_to_xarray(self): expected = df.copy() expected["f"] = expected["f"].astype(object) expected.columns.name = None - tm.assert_frame_equal(result, expected, check_index_type=False) + tm.assert_frame_equal(result, expected) class TestSeriesToXArray: @td.skip_if_no("xarray", "0.10.0") def test_to_xarray_index_types(self, index): - if isinstance(index, pd.MultiIndex): + if isinstance(index, MultiIndex): pytest.skip("MultiIndex is tested separately") from xarray import DataArray - s = Series(range(len(index)), index=index, dtype="int64") - s.index.name = "foo" - result = s.to_xarray() + ser = Series(range(len(index)), index=index, dtype="int64") + ser.index.name = "foo" + result = ser.to_xarray() repr(result) assert len(result) == len(index) assert len(result.coords) == 1 @@ -107,27 +99,29 @@ def test_to_xarray_index_types(self, index): assert isinstance(result, DataArray) # idempotency - tm.assert_series_equal(result.to_series(), s, check_index_type=False) + tm.assert_series_equal(result.to_series(), ser) @td.skip_if_no("xarray", min_version="0.7.0") - def test_to_xarray(self): + def test_to_xarray_empty(self): from xarray import DataArray - s = Series([], dtype=object) - s.index.name = "foo" - result = s.to_xarray() + ser = Series([], dtype=object) + ser.index.name = "foo" + result = ser.to_xarray() assert len(result) == 0 assert len(result.coords) == 1 tm.assert_almost_equal(list(result.coords.keys()), ["foo"]) assert isinstance(result, DataArray) - s = Series(range(6), dtype="int64") - s.index.name = "foo" - s.index = pd.MultiIndex.from_product( - [["a", "b"], range(3)], names=["one", "two"] - ) - result = s.to_xarray() + @td.skip_if_no("xarray", min_version="0.7.0") + def test_to_xarray_with_multiindex(self): + from xarray import DataArray + + mi = MultiIndex.from_product([["a", "b"], range(3)], names=["one", "two"]) + ser = Series(range(6), dtype="int64", index=mi) + result = ser.to_xarray() assert len(result) == 2 tm.assert_almost_equal(list(result.coords.keys()), ["one", "two"]) assert isinstance(result, DataArray) - tm.assert_series_equal(result.to_series(), s) + res = result.to_series() + tm.assert_series_equal(res, ser) diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py index f5c3623fb9986..46c41efc09fdf 100644 --- a/pandas/tests/series/test_dtypes.py +++ b/pandas/tests/series/test_dtypes.py @@ -53,24 +53,16 @@ def test_astype_from_categorical(self): tm.assert_series_equal(res, exp) def test_astype_categorical_to_other(self): + cat = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)]) + ser = Series(np.random.RandomState(0).randint(0, 10000, 100)).sort_values() + ser = pd.cut(ser, range(0, 10500, 500), right=False, labels=cat) - value = np.random.RandomState(0).randint(0, 10000, 100) - df = DataFrame({"value": value}) - labels = [f"{i} - {i + 499}" for i in range(0, 10000, 500)] - cat_labels = Categorical(labels, labels) - - df = df.sort_values(by=["value"], ascending=True) - df["value_group"] = pd.cut( - df.value, range(0, 10500, 500), right=False, labels=cat_labels - ) - - s = df["value_group"] - expected = s - tm.assert_series_equal(s.astype("category"), expected) - tm.assert_series_equal(s.astype(CategoricalDtype()), expected) + expected = ser + tm.assert_series_equal(ser.astype("category"), expected) + tm.assert_series_equal(ser.astype(CategoricalDtype()), expected) msg = r"could not convert string to float|invalid literal for float\(\)" with pytest.raises(ValueError, match=msg): - s.astype("float64") + ser.astype("float64") cat = Series(Categorical(["a", "b", "b", "a", "a", "c", "c", "c"])) exp = Series(["a", "b", "b", "a", "a", "c", "c", "c"]) @@ -84,25 +76,38 @@ def test_astype_categorical_to_other(self): def cmp(a, b): tm.assert_almost_equal(np.sort(np.unique(a)), np.sort(np.unique(b))) - expected = Series(np.array(s.values), name="value_group") - cmp(s.astype("object"), expected) - cmp(s.astype(np.object_), expected) + expected = Series(np.array(ser.values), name="value_group") + cmp(ser.astype("object"), expected) + cmp(ser.astype(np.object_), expected) # array conversion - tm.assert_almost_equal(np.array(s), np.array(s.values)) + tm.assert_almost_equal(np.array(ser), np.array(ser.values)) - tm.assert_series_equal(s.astype("category"), s) - tm.assert_series_equal(s.astype(CategoricalDtype()), s) + tm.assert_series_equal(ser.astype("category"), ser) + tm.assert_series_equal(ser.astype(CategoricalDtype()), ser) - roundtrip_expected = s.cat.set_categories( - s.cat.categories.sort_values() + roundtrip_expected = ser.cat.set_categories( + ser.cat.categories.sort_values() ).cat.remove_unused_categories() - tm.assert_series_equal( - s.astype("object").astype("category"), roundtrip_expected - ) - tm.assert_series_equal( - s.astype("object").astype(CategoricalDtype()), roundtrip_expected + result = ser.astype("object").astype("category") + tm.assert_series_equal(result, roundtrip_expected) + result = ser.astype("object").astype(CategoricalDtype()) + tm.assert_series_equal(result, roundtrip_expected) + + def test_astype_categorical_invalid_conversions(self): + # invalid conversion (these are NOT a dtype) + cat = Categorical([f"{i} - {i + 499}" for i in range(0, 10000, 500)]) + ser = Series(np.random.RandomState(0).randint(0, 10000, 100)).sort_values() + ser = pd.cut(ser, range(0, 10500, 500), right=False, labels=cat) + + msg = ( + "dtype '<class 'pandas.core.arrays.categorical.Categorical'>' " + "not understood" ) + with pytest.raises(TypeError, match=msg): + ser.astype(Categorical) + with pytest.raises(TypeError, match=msg): + ser.astype("object").astype(Categorical) def test_series_to_categorical(self): # see gh-16524: test conversion of Series to Categorical
For some of these its just breaking up big tests and giving them meaningful names.
https://api.github.com/repos/pandas-dev/pandas/pulls/37730
2020-11-10T01:16:38Z
2020-11-13T05:10:22Z
2020-11-13T05:10:22Z
2020-11-13T05:14:00Z
TST/REF: collect indexing tests by method
diff --git a/pandas/tests/frame/indexing/test_getitem.py b/pandas/tests/frame/indexing/test_getitem.py index 079cc12389835..2e65770d7afad 100644 --- a/pandas/tests/frame/indexing/test_getitem.py +++ b/pandas/tests/frame/indexing/test_getitem.py @@ -7,11 +7,13 @@ CategoricalIndex, DataFrame, MultiIndex, + Series, Timestamp, get_dummies, period_range, ) import pandas._testing as tm +from pandas.core.arrays import SparseArray class TestGetitem: @@ -50,6 +52,21 @@ def test_getitem_list_of_labels_categoricalindex_cols(self): result = dummies[list(dummies.columns)] tm.assert_frame_equal(result, expected) + def test_getitem_sparse_column_return_type_and_dtype(self): + # https://github.com/pandas-dev/pandas/issues/23559 + data = SparseArray([0, 1]) + df = DataFrame({"A": data}) + expected = Series(data, name="A") + result = df["A"] + tm.assert_series_equal(result, expected) + + # Also check iloc and loc while we're here + result = df.iloc[:, 0] + tm.assert_series_equal(result, expected) + + result = df.loc[:, "A"] + tm.assert_series_equal(result, expected) + class TestGetitemCallable: def test_getitem_callable(self, float_frame): diff --git a/pandas/tests/frame/indexing/test_sparse.py b/pandas/tests/frame/indexing/test_sparse.py deleted file mode 100644 index 47e4ae1f9f9e1..0000000000000 --- a/pandas/tests/frame/indexing/test_sparse.py +++ /dev/null @@ -1,19 +0,0 @@ -import pandas as pd -import pandas._testing as tm -from pandas.arrays import SparseArray - - -class TestSparseDataFrameIndexing: - def test_getitem_sparse_column(self): - # https://github.com/pandas-dev/pandas/issues/23559 - data = SparseArray([0, 1]) - df = pd.DataFrame({"A": data}) - expected = pd.Series(data, name="A") - result = df["A"] - tm.assert_series_equal(result, expected) - - result = df.iloc[:, 0] - tm.assert_series_equal(result, expected) - - result = df.loc[:, "A"] - tm.assert_series_equal(result, expected) diff --git a/pandas/tests/indexing/test_at.py b/pandas/tests/indexing/test_at.py index 46299fadf7789..d410a4137554b 100644 --- a/pandas/tests/indexing/test_at.py +++ b/pandas/tests/indexing/test_at.py @@ -17,6 +17,16 @@ def test_at_timezone(): tm.assert_frame_equal(result, expected) +class TestAtSetItem: + def test_at_setitem_mixed_index_assignment(self): + # GH#19860 + ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2]) + ser.at["a"] = 11 + assert ser.iat[0] == 11 + ser.at[1] = 22 + assert ser.iat[3] == 22 + + class TestAtWithDuplicates: def test_at_with_duplicate_axes_requires_scalar_lookup(self): # GH#33041 check that falling back to loc doesn't allow non-scalar @@ -108,3 +118,11 @@ def test_at_frame_raises_key_error2(self): df.at["a", 0] with pytest.raises(KeyError, match="^0$"): df.loc["a", 0] + + def test_at_getitem_mixed_index_no_fallback(self): + # GH#19860 + ser = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2]) + with pytest.raises(KeyError, match="^0$"): + ser.at[0] + with pytest.raises(KeyError, match="^4$"): + ser.at[4] diff --git a/pandas/tests/indexing/test_floats.py b/pandas/tests/indexing/test_floats.py index c48e0a129e161..1b78ba6defd69 100644 --- a/pandas/tests/indexing/test_floats.py +++ b/pandas/tests/indexing/test_floats.py @@ -1,17 +1,9 @@ -import re - import numpy as np import pytest from pandas import DataFrame, Float64Index, Index, Int64Index, RangeIndex, Series import pandas._testing as tm -# We pass through the error message from numpy -_slice_iloc_msg = re.escape( - "only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) " - "and integer or boolean arrays are valid indices" -) - def gen_obj(klass, index): if klass is Series: @@ -40,24 +32,6 @@ def check(self, result, original, indexer, getitem): tm.assert_almost_equal(result, expected) - def test_scalar_error(self, series_with_simple_index): - - # GH 4892 - # float_indexers should raise exceptions - # on appropriate Index types & accessors - # this duplicates the code below - # but is specifically testing for the error - # message - - s = series_with_simple_index - - msg = "Cannot index by location index with a non-integer key" - with pytest.raises(TypeError, match=msg): - s.iloc[3.0] - - with pytest.raises(IndexError, match=_slice_iloc_msg): - s.iloc[3.0] = 0 - @pytest.mark.parametrize( "index_func", [ @@ -69,40 +43,32 @@ def test_scalar_error(self, series_with_simple_index): tm.makePeriodIndex, ], ) - @pytest.mark.parametrize("klass", [Series, DataFrame]) - def test_scalar_non_numeric(self, index_func, klass): + def test_scalar_non_numeric(self, index_func, frame_or_series): # GH 4892 # float_indexers should raise exceptions # on appropriate Index types & accessors i = index_func(5) - s = gen_obj(klass, i) + s = gen_obj(frame_or_series, i) # getting with pytest.raises(KeyError, match="^3.0$"): s[3.0] - msg = "Cannot index by location index with a non-integer key" - with pytest.raises(TypeError, match=msg): - s.iloc[3.0] - with pytest.raises(KeyError, match="^3.0$"): s.loc[3.0] # contains assert 3.0 not in s - # setting with a float fails with iloc - with pytest.raises(IndexError, match=_slice_iloc_msg): - s.iloc[3.0] = 0 - # setting with an indexer if s.index.inferred_type in ["categorical"]: # Value or Type Error pass elif s.index.inferred_type in ["datetime64", "timedelta64", "period"]: + # FIXME: dont leave commented-out # these should prob work # and are inconsistent between series/dataframe ATM # for idxr in [lambda x: x]: @@ -151,10 +117,6 @@ def test_scalar_with_mixed(self): with pytest.raises(KeyError, match="^1.0$"): s2[1.0] - msg = "Cannot index by location index with a non-integer key" - with pytest.raises(TypeError, match=msg): - s2.iloc[1.0] - with pytest.raises(KeyError, match=r"^1\.0$"): s2.loc[1.0] @@ -171,9 +133,6 @@ def test_scalar_with_mixed(self): expected = 2 assert result == expected - msg = "Cannot index by location index with a non-integer key" - with pytest.raises(TypeError, match=msg): - s3.iloc[1.0] with pytest.raises(KeyError, match=r"^1\.0$"): s3.loc[1.0] @@ -182,14 +141,13 @@ def test_scalar_with_mixed(self): assert result == expected @pytest.mark.parametrize("index_func", [tm.makeIntIndex, tm.makeRangeIndex]) - @pytest.mark.parametrize("klass", [Series, DataFrame]) - def test_scalar_integer(self, index_func, klass): + def test_scalar_integer(self, index_func, frame_or_series): # test how scalar float indexers work on int indexes # integer index i = index_func(5) - obj = gen_obj(klass, i) + obj = gen_obj(frame_or_series, i) # coerce to equal int for idxr, getitem in [(lambda x: x.loc, False), (lambda x: x, True)]: @@ -226,12 +184,11 @@ def compare(x, y): # coerce to equal int assert 3.0 in obj - @pytest.mark.parametrize("klass", [Series, DataFrame]) - def test_scalar_float(self, klass): + def test_scalar_float(self, frame_or_series): # scalar float indexers work on a float index index = Index(np.arange(5.0)) - s = gen_obj(klass, index) + s = gen_obj(frame_or_series, index) # assert all operations except for iloc are ok indexer = index[3] @@ -262,14 +219,6 @@ def test_scalar_float(self, klass): result = s2.iloc[3] self.check(result, s, 3, False) - # iloc raises with a float - msg = "Cannot index by location index with a non-integer key" - with pytest.raises(TypeError, match=msg): - s.iloc[3.0] - - with pytest.raises(IndexError, match=_slice_iloc_msg): - s2.iloc[3.0] = 0 - @pytest.mark.parametrize( "index_func", [ @@ -281,15 +230,14 @@ def test_scalar_float(self, klass): ], ) @pytest.mark.parametrize("l", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)]) - @pytest.mark.parametrize("klass", [Series, DataFrame]) - def test_slice_non_numeric(self, index_func, l, klass): + def test_slice_non_numeric(self, index_func, l, frame_or_series): # GH 4892 # float_indexers should raise exceptions # on appropriate Index types & accessors index = index_func(5) - s = gen_obj(klass, index) + s = gen_obj(frame_or_series, index) # getitem msg = ( @@ -509,12 +457,11 @@ def test_float_slice_getitem_with_integer_index_raises(self, l, index_func): s[l] @pytest.mark.parametrize("l", [slice(3.0, 4), slice(3, 4.0), slice(3.0, 4.0)]) - @pytest.mark.parametrize("klass", [Series, DataFrame]) - def test_slice_float(self, l, klass): + def test_slice_float(self, l, frame_or_series): # same as above, but for floats index = Index(np.arange(5.0)) + 0.1 - s = gen_obj(klass, index) + s = gen_obj(frame_or_series, index) expected = s.iloc[3:4] for idxr in [lambda x: x.loc, lambda x: x]: diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index f5f2ac0225bd4..0360d7e01e62d 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -1,18 +1,34 @@ """ test positional based indexing with iloc """ from datetime import datetime +import re from warnings import catch_warnings, simplefilter import numpy as np import pytest -import pandas as pd -from pandas import CategoricalDtype, DataFrame, Series, concat, date_range, isna +from pandas import ( + Categorical, + CategoricalDtype, + DataFrame, + Index, + NaT, + Series, + concat, + date_range, + isna, +) import pandas._testing as tm from pandas.api.types import is_scalar from pandas.core.indexing import IndexingError from pandas.tests.indexing.common import Base +# We pass through the error message from numpy +_slice_iloc_msg = re.escape( + "only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) " + "and integer or boolean arrays are valid indices" +) + class TestiLoc(Base): def test_iloc_getitem_int(self): @@ -50,7 +66,7 @@ class TestiLoc2: def test_is_scalar_access(self): # GH#32085 index with duplicates doesnt matter for _is_scalar_access - index = pd.Index([1, 2, 1]) + index = Index([1, 2, 1]) ser = Series(range(3), index=index) assert ser.iloc._is_scalar_access((1,)) @@ -337,7 +353,7 @@ def test_iloc_setitem_pandas_object(self): tm.assert_series_equal(s, expected) s = s_orig.copy() - s.iloc[pd.Index([1, 2])] = [-1, -2] + s.iloc[Index([1, 2])] = [-1, -2] tm.assert_series_equal(s, expected) def test_iloc_setitem_dups(self): @@ -710,13 +726,13 @@ def test_series_indexing_zerodim_np_array(self): @pytest.mark.xfail(reason="https://github.com/pandas-dev/pandas/issues/33457") def test_iloc_setitem_categorical_updates_inplace(self): # Mixed dtype ensures we go through take_split_path in setitem_with_indexer - cat = pd.Categorical(["A", "B", "C"]) + cat = Categorical(["A", "B", "C"]) df = DataFrame({1: cat, 2: [1, 2, 3]}) # This should modify our original values in-place df.iloc[:, 0] = cat[::-1] - expected = pd.Categorical(["C", "B", "A"]) + expected = Categorical(["C", "B", "A"]) tm.assert_categorical_equal(cat, expected) def test_iloc_with_boolean_operation(self): @@ -740,9 +756,9 @@ def test_iloc_with_boolean_operation(self): def test_iloc_getitem_singlerow_slice_categoricaldtype_gives_series(self): # GH#29521 - df = DataFrame({"x": pd.Categorical("a b c d e".split())}) + df = DataFrame({"x": Categorical("a b c d e".split())}) result = df.iloc[0] - raw_cat = pd.Categorical(["a"], categories=["a", "b", "c", "d", "e"]) + raw_cat = Categorical(["a"], categories=["a", "b", "c", "d", "e"]) expected = Series(raw_cat, index=["x"], name=0, dtype="category") tm.assert_series_equal(result, expected) @@ -768,13 +784,53 @@ def test_iloc_getitem_categorical_values(self): expected = Series([1]).astype(CategoricalDtype([1, 2, 3])) tm.assert_series_equal(result, expected) + @pytest.mark.parametrize("value", [None, NaT, np.nan]) + def test_iloc_setitem_td64_values_cast_na(self, value): + # GH#18586 + series = Series([0, 1, 2], dtype="timedelta64[ns]") + series.iloc[0] = value + expected = Series([NaT, 1, 2], dtype="timedelta64[ns]") + tm.assert_series_equal(series, expected) + + def test_iloc_setitem_empty_frame_raises_with_3d_ndarray(self): + idx = Index([]) + obj = DataFrame(np.random.randn(len(idx), len(idx)), index=idx, columns=idx) + nd3 = np.random.randint(5, size=(2, 2, 2)) + + msg = f"Cannot set values with ndim > {obj.ndim}" + with pytest.raises(ValueError, match=msg): + obj.iloc[nd3] = 0 + + +class TestILocErrors: + # NB: this test should work for _any_ Series we can pass as + # series_with_simple_index + def test_iloc_float_raises(self, series_with_simple_index, frame_or_series): + # GH#4892 + # float_indexers should raise exceptions + # on appropriate Index types & accessors + # this duplicates the code below + # but is specifically testing for the error + # message + + obj = series_with_simple_index + if frame_or_series is DataFrame: + obj = obj.to_frame() + + msg = "Cannot index by location index with a non-integer key" + with pytest.raises(TypeError, match=msg): + obj.iloc[3.0] + + with pytest.raises(IndexError, match=_slice_iloc_msg): + obj.iloc[3.0] = 0 + class TestILocSetItemDuplicateColumns: def test_iloc_setitem_scalar_duplicate_columns(self): # GH#15686, duplicate columns and mixed dtype df1 = DataFrame([{"A": None, "B": 1}, {"A": 2, "B": 2}]) df2 = DataFrame([{"A": 3, "B": 3}, {"A": 4, "B": 4}]) - df = pd.concat([df1, df2], axis=1) + df = concat([df1, df2], axis=1) df.iloc[0, 0] = -1 assert df.iloc[0, 0] == -1 diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 06bd8a5f300bb..472b29981e78c 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -15,6 +15,8 @@ from pandas.core.indexing import maybe_numeric_slice, non_reducing_slice from pandas.tests.indexing.common import _mklbl +from .test_floats import gen_obj + # ------------------------------------------------------------------------ # Indexing test cases @@ -56,14 +58,6 @@ def test_setitem_ndarray_1d(self): with pytest.raises(ValueError, match=msg): df[2:5] = np.arange(1, 4) * 1j - @pytest.mark.parametrize( - "obj", - [ - lambda i: Series(np.arange(len(i)), index=i), - lambda i: DataFrame(np.random.randn(len(i), len(i)), index=i, columns=i), - ], - ids=["Series", "DataFrame"], - ) @pytest.mark.parametrize( "idxr, idxr_id", [ @@ -72,9 +66,9 @@ def test_setitem_ndarray_1d(self): (lambda x: x.iloc, "iloc"), ], ) - def test_getitem_ndarray_3d(self, index, obj, idxr, idxr_id): + def test_getitem_ndarray_3d(self, index, frame_or_series, idxr, idxr_id): # GH 25567 - obj = obj(index) + obj = gen_obj(frame_or_series, index) idxr = idxr(obj) nd3 = np.random.randint(5, size=(2, 2, 2)) @@ -94,14 +88,6 @@ def test_getitem_ndarray_3d(self, index, obj, idxr, idxr_id): with tm.assert_produces_warning(DeprecationWarning, check_stacklevel=False): idxr[nd3] - @pytest.mark.parametrize( - "obj", - [ - lambda i: Series(np.arange(len(i)), index=i), - lambda i: DataFrame(np.random.randn(len(i), len(i)), index=i, columns=i), - ], - ids=["Series", "DataFrame"], - ) @pytest.mark.parametrize( "idxr, idxr_id", [ @@ -110,9 +96,9 @@ def test_getitem_ndarray_3d(self, index, obj, idxr, idxr_id): (lambda x: x.iloc, "iloc"), ], ) - def test_setitem_ndarray_3d(self, index, obj, idxr, idxr_id): + def test_setitem_ndarray_3d(self, index, frame_or_series, idxr, idxr_id): # GH 25567 - obj = obj(index) + obj = gen_obj(frame_or_series, index) idxr = idxr(obj) nd3 = np.random.randint(5, size=(2, 2, 2)) @@ -135,15 +121,6 @@ def test_setitem_ndarray_3d(self, index, obj, idxr, idxr_id): with pytest.raises(err, match=msg): idxr[nd3] = 0 - def test_setitem_ndarray_3d_does_not_fail_for_iloc_empty_dataframe(self): - i = Index([]) - obj = DataFrame(np.random.randn(len(i), len(i)), index=i, columns=i) - nd3 = np.random.randint(5, size=(2, 2, 2)) - - msg = f"Cannot set values with ndim > {obj.ndim}" - with pytest.raises(ValueError, match=msg): - obj.iloc[nd3] = 0 - def test_inf_upcast(self): # GH 16957 # We should be able to use np.inf as a key @@ -617,7 +594,8 @@ def test_astype_assignment(self): expected = DataFrame({"A": [1, 2, 3, 4]}) tm.assert_frame_equal(df, expected) - def test_index_type_coercion(self): + @pytest.mark.parametrize("indexer", [lambda x: x.loc, lambda x: x]) + def test_index_type_coercion(self, indexer): # GH 11836 # if we have an index type and set it with something that looks @@ -630,41 +608,38 @@ def test_index_type_coercion(self): assert s.index.is_integer() - for indexer in [lambda x: x.loc, lambda x: x]: - s2 = s.copy() - indexer(s2)[0.1] = 0 - assert s2.index.is_floating() - assert indexer(s2)[0.1] == 0 + s2 = s.copy() + indexer(s2)[0.1] = 0 + assert s2.index.is_floating() + assert indexer(s2)[0.1] == 0 - s2 = s.copy() - indexer(s2)[0.0] = 0 - exp = s.index - if 0 not in s: - exp = Index(s.index.tolist() + [0]) - tm.assert_index_equal(s2.index, exp) + s2 = s.copy() + indexer(s2)[0.0] = 0 + exp = s.index + if 0 not in s: + exp = Index(s.index.tolist() + [0]) + tm.assert_index_equal(s2.index, exp) - s2 = s.copy() - indexer(s2)["0"] = 0 - assert s2.index.is_object() + s2 = s.copy() + indexer(s2)["0"] = 0 + assert s2.index.is_object() for s in [Series(range(5), index=np.arange(5.0))]: assert s.index.is_floating() - for idxr in [lambda x: x.loc, lambda x: x]: - - s2 = s.copy() - idxr(s2)[0.1] = 0 - assert s2.index.is_floating() - assert idxr(s2)[0.1] == 0 + s2 = s.copy() + indexer(s2)[0.1] = 0 + assert s2.index.is_floating() + assert indexer(s2)[0.1] == 0 - s2 = s.copy() - idxr(s2)[0.0] = 0 - tm.assert_index_equal(s2.index, s.index) + s2 = s.copy() + indexer(s2)[0.0] = 0 + tm.assert_index_equal(s2.index, s.index) - s2 = s.copy() - idxr(s2)["0"] = 0 - assert s2.index.is_object() + s2 = s.copy() + indexer(s2)["0"] = 0 + assert s2.index.is_object() class TestMisc: @@ -693,22 +668,6 @@ def test_float_index_at_iat(self): for i in range(len(s)): assert s.iat[i] == i + 1 - def test_mixed_index_assignment(self): - # GH 19860 - s = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2]) - s.at["a"] = 11 - assert s.iat[0] == 11 - s.at[1] = 22 - assert s.iat[3] == 22 - - def test_mixed_index_no_fallback(self): - # GH 19860 - s = Series([1, 2, 3, 4, 5], index=["a", "b", "c", 1, 2]) - with pytest.raises(KeyError, match="^0$"): - s.at[0] - with pytest.raises(KeyError, match="^4$"): - s.at[4] - def test_rhs_alignment(self): # GH8258, tests that both rows & columns are aligned to what is # assigned to. covers both uniform data-type & multi-type cases diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 26c9e127bcc10..0d40b5f38e48a 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -22,6 +22,7 @@ date_range, timedelta_range, to_datetime, + to_timedelta, ) import pandas._testing as tm from pandas.api.types import is_scalar @@ -1099,6 +1100,32 @@ def test_loc_setitem_int_label_with_float64index(self): tm.assert_series_equal(ser, tmp) + @pytest.mark.parametrize( + "indexer, expected", + [ + # The test name is a misnomer in the 0 case as df.index[indexer] + # is a scalar. + (0, [20, 1, 2, 3, 4, 5, 6, 7, 8, 9]), + (slice(4, 8), [0, 1, 2, 3, 20, 20, 20, 20, 8, 9]), + ([3, 5], [0, 1, 2, 20, 4, 20, 6, 7, 8, 9]), + ], + ) + def test_loc_setitem_listlike_with_timedelta64index(self, indexer, expected): + # GH#16637 + tdi = to_timedelta(range(10), unit="s") + df = DataFrame({"x": range(10)}, dtype="int64", index=tdi) + + df.loc[df.index[indexer], "x"] = 20 + + expected = DataFrame( + expected, + index=tdi, + columns=["x"], + dtype="int64", + ) + + tm.assert_frame_equal(expected, df) + class TestLocWithMultiIndex: @pytest.mark.parametrize( @@ -1454,6 +1481,13 @@ def test_loc_getitem_partial_string_slicing_with_timedeltaindex(self): tm.assert_series_equal(result, expected) + def test_loc_getitem_str_timedeltaindex(self): + # GH#16896 + df = DataFrame({"x": range(3)}, index=to_timedelta(range(3), unit="days")) + expected = df.iloc[0] + sliced = df.loc["0 days"] + tm.assert_series_equal(sliced, expected) + class TestLabelSlicing: def test_loc_getitem_label_slice_across_dst(self): @@ -1514,8 +1548,45 @@ def test_loc_getitem_float_slice_float64index(self): assert len(ser.loc[12.0:]) == 8 assert len(ser.loc[12.5:]) == 7 + @pytest.mark.parametrize( + "start,stop, expected_slice", + [ + [np.timedelta64(0, "ns"), None, slice(0, 11)], + [np.timedelta64(1, "D"), np.timedelta64(6, "D"), slice(1, 7)], + [None, np.timedelta64(4, "D"), slice(0, 5)], + ], + ) + def test_loc_getitem_slice_label_td64obj(self, start, stop, expected_slice): + # GH#20393 + ser = Series(range(11), timedelta_range("0 days", "10 days")) + result = ser.loc[slice(start, stop)] + expected = ser.iloc[expected_slice] + tm.assert_series_equal(result, expected) + class TestLocBooleanMask: + def test_loc_setitem_bool_mask_timedeltaindex(self): + # GH#14946 + df = DataFrame({"x": range(10)}) + df.index = to_timedelta(range(10), unit="s") + conditions = [df["x"] > 3, df["x"] == 3, df["x"] < 3] + expected_data = [ + [0, 1, 2, 3, 10, 10, 10, 10, 10, 10], + [0, 1, 2, 10, 4, 5, 6, 7, 8, 9], + [10, 10, 10, 3, 4, 5, 6, 7, 8, 9], + ] + for cond, data in zip(conditions, expected_data): + result = df.copy() + result.loc[cond, "x"] = 10 + + expected = DataFrame( + data, + index=to_timedelta(range(10), unit="s"), + columns=["x"], + dtype="int64", + ) + tm.assert_frame_equal(expected, result) + def test_loc_setitem_mask_with_datetimeindex_tz(self): # GH#16889 # support .loc with alignment and tz-aware DatetimeIndex @@ -1558,6 +1629,21 @@ def test_loc_setitem_mask_and_label_with_datetimeindex(self): df.loc[mask, "C"] = df.loc[mask].index tm.assert_frame_equal(df, expected) + def test_loc_setitem_mask_td64_series_value(self): + # GH#23462 key list of bools, value is a Series + td1 = Timedelta(0) + td2 = Timedelta(28767471428571405) + df = DataFrame({"col": Series([td1, td2])}) + df_copy = df.copy() + ser = Series([td1]) + + expected = df["col"].iloc[1].value + df.loc[[True, False]] = ser + result = df["col"].iloc[1].value + + assert expected == result + tm.assert_frame_equal(df, df_copy) + def test_series_loc_getitem_label_list_missing_values(): # gh-11428 diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py index 127d00c217a15..230725d8ee11d 100644 --- a/pandas/tests/indexing/test_scalar.py +++ b/pandas/tests/indexing/test_scalar.py @@ -178,7 +178,7 @@ def test_at_with_tz(self): result = df.at[0, "date"] assert result == expected - def test_series_set_tz_timestamp(self, tz_naive_fixture): + def test_at_setitem_expansion_series_dt64tz_value(self, tz_naive_fixture): # GH 25506 ts = Timestamp("2017-08-05 00:00:00+0100", tz=tz_naive_fixture) result = Series(ts) diff --git a/pandas/tests/indexing/test_timedelta.py b/pandas/tests/indexing/test_timedelta.py deleted file mode 100644 index 9461bb74b2a87..0000000000000 --- a/pandas/tests/indexing/test_timedelta.py +++ /dev/null @@ -1,106 +0,0 @@ -import numpy as np -import pytest - -import pandas as pd -import pandas._testing as tm - - -class TestTimedeltaIndexing: - def test_loc_setitem_bool_mask(self): - # GH 14946 - df = pd.DataFrame({"x": range(10)}) - df.index = pd.to_timedelta(range(10), unit="s") - conditions = [df["x"] > 3, df["x"] == 3, df["x"] < 3] - expected_data = [ - [0, 1, 2, 3, 10, 10, 10, 10, 10, 10], - [0, 1, 2, 10, 4, 5, 6, 7, 8, 9], - [10, 10, 10, 3, 4, 5, 6, 7, 8, 9], - ] - for cond, data in zip(conditions, expected_data): - result = df.copy() - result.loc[cond, "x"] = 10 - - expected = pd.DataFrame( - data, - index=pd.to_timedelta(range(10), unit="s"), - columns=["x"], - dtype="int64", - ) - tm.assert_frame_equal(expected, result) - - @pytest.mark.parametrize( - "indexer, expected", - [ - (0, [20, 1, 2, 3, 4, 5, 6, 7, 8, 9]), - (slice(4, 8), [0, 1, 2, 3, 20, 20, 20, 20, 8, 9]), - ([3, 5], [0, 1, 2, 20, 4, 20, 6, 7, 8, 9]), - ], - ) - def test_list_like_indexing(self, indexer, expected): - # GH 16637 - df = pd.DataFrame({"x": range(10)}, dtype="int64") - df.index = pd.to_timedelta(range(10), unit="s") - - df.loc[df.index[indexer], "x"] = 20 - - expected = pd.DataFrame( - expected, - index=pd.to_timedelta(range(10), unit="s"), - columns=["x"], - dtype="int64", - ) - - tm.assert_frame_equal(expected, df) - - def test_string_indexing(self): - # GH 16896 - df = pd.DataFrame({"x": range(3)}, index=pd.to_timedelta(range(3), unit="days")) - expected = df.iloc[0] - sliced = df.loc["0 days"] - tm.assert_series_equal(sliced, expected) - - @pytest.mark.parametrize("value", [None, pd.NaT, np.nan]) - def test_setitem_mask_na_value_td64(self, value): - # issue (#18586) - series = pd.Series([0, 1, 2], dtype="timedelta64[ns]") - series[series == series[0]] = value - expected = pd.Series([pd.NaT, 1, 2], dtype="timedelta64[ns]") - tm.assert_series_equal(series, expected) - - @pytest.mark.parametrize("value", [None, pd.NaT, np.nan]) - def test_listlike_setitem(self, value): - # issue (#18586) - series = pd.Series([0, 1, 2], dtype="timedelta64[ns]") - series.iloc[0] = value - expected = pd.Series([pd.NaT, 1, 2], dtype="timedelta64[ns]") - tm.assert_series_equal(series, expected) - - @pytest.mark.parametrize( - "start,stop, expected_slice", - [ - [np.timedelta64(0, "ns"), None, slice(0, 11)], - [np.timedelta64(1, "D"), np.timedelta64(6, "D"), slice(1, 7)], - [None, np.timedelta64(4, "D"), slice(0, 5)], - ], - ) - def test_numpy_timedelta_scalar_indexing(self, start, stop, expected_slice): - # GH 20393 - s = pd.Series(range(11), pd.timedelta_range("0 days", "10 days")) - result = s.loc[slice(start, stop)] - expected = s.iloc[expected_slice] - tm.assert_series_equal(result, expected) - - def test_roundtrip_thru_setitem(self): - # PR 23462 - dt1 = pd.Timedelta(0) - dt2 = pd.Timedelta(28767471428571405) - df = pd.DataFrame({"dt": pd.Series([dt1, dt2])}) - df_copy = df.copy() - s = pd.Series([dt1]) - - expected = df["dt"].iloc[1].value - df.loc[[True, False]] = s - result = df["dt"].iloc[1].value - - assert expected == result - tm.assert_frame_equal(df, df_copy) diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 7e25e5200d610..4f00f9c931d6a 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -126,6 +126,15 @@ def test_setitem_boolean_different_order(self, string_series): tm.assert_series_equal(copy, expected) + @pytest.mark.parametrize("value", [None, NaT, np.nan]) + def test_setitem_boolean_td64_values_cast_na(self, value): + # GH#18586 + series = Series([0, 1, 2], dtype="timedelta64[ns]") + mask = series == series[0] + series[mask] = value + expected = Series([NaT, 1, 2], dtype="timedelta64[ns]") + tm.assert_series_equal(series, expected) + class TestSetitemViewCopySemantics: def test_setitem_invalidates_datetime_index_freq(self):
https://api.github.com/repos/pandas-dev/pandas/pulls/37729
2020-11-10T01:08:07Z
2020-11-10T03:17:42Z
2020-11-10T03:17:42Z
2020-11-10T03:33:24Z
Bug in iloc aligned objects
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 62da3c0c5cddc..1f05c35097b22 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -589,6 +589,7 @@ Indexing - Bug in :meth:`DataFrame.xs` ignored ``droplevel=False`` for columns (:issue:`19056`) - Bug in :meth:`DataFrame.reindex` raising ``IndexingError`` wrongly for empty :class:`DataFrame` with ``tolerance`` not None or ``method="nearest"`` (:issue:`27315`) - Bug in indexing on a :class:`Series` or :class:`DataFrame` with a :class:`CategoricalIndex` using listlike indexer that contains elements that are in the index's ``categories`` but not in the index itself failing to raise ``KeyError`` (:issue:`37901`) +- Bug in :meth:`DataFrame.iloc` and :meth:`Series.iloc` aligning objects in ``__setitem__`` (:issue:`22046`) Missing ^^^^^^^ diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 62b1554246e26..9bfbc22b1e628 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -681,7 +681,7 @@ def __setitem__(self, key, value): self._has_valid_setitem_indexer(key) iloc = self if self.name == "iloc" else self.obj.iloc - iloc._setitem_with_indexer(indexer, value) + iloc._setitem_with_indexer(indexer, value, self.name) def _validate_key(self, key, axis: int): """ @@ -1517,7 +1517,7 @@ def _get_setitem_indexer(self, key): # ------------------------------------------------------------------- - def _setitem_with_indexer(self, indexer, value): + def _setitem_with_indexer(self, indexer, value, name="iloc"): """ _setitem_with_indexer is for setting values on a Series/DataFrame using positional indexers. @@ -1593,7 +1593,7 @@ def _setitem_with_indexer(self, indexer, value): new_indexer = convert_from_missing_indexer_tuple( indexer, self.obj.axes ) - self._setitem_with_indexer(new_indexer, value) + self._setitem_with_indexer(new_indexer, value, name) return @@ -1624,11 +1624,11 @@ def _setitem_with_indexer(self, indexer, value): # align and set the values if take_split_path: # We have to operate column-wise - self._setitem_with_indexer_split_path(indexer, value) + self._setitem_with_indexer_split_path(indexer, value, name) else: - self._setitem_single_block(indexer, value) + self._setitem_single_block(indexer, value, name) - def _setitem_with_indexer_split_path(self, indexer, value): + def _setitem_with_indexer_split_path(self, indexer, value, name: str): """ Setitem column-wise. """ @@ -1642,7 +1642,7 @@ def _setitem_with_indexer_split_path(self, indexer, value): if isinstance(indexer[0], np.ndarray) and indexer[0].ndim > 2: raise ValueError(r"Cannot set values with ndim > 2") - if isinstance(value, ABCSeries): + if isinstance(value, ABCSeries) and name != "iloc": value = self._align_series(indexer, value) # Ensure we have something we can iterate over @@ -1657,7 +1657,7 @@ def _setitem_with_indexer_split_path(self, indexer, value): if is_list_like_indexer(value) and getattr(value, "ndim", 1) > 0: if isinstance(value, ABCDataFrame): - self._setitem_with_indexer_frame_value(indexer, value) + self._setitem_with_indexer_frame_value(indexer, value, name) elif np.ndim(value) == 2: self._setitem_with_indexer_2d_value(indexer, value) @@ -1714,7 +1714,7 @@ def _setitem_with_indexer_2d_value(self, indexer, value): # setting with a list, re-coerces self._setitem_single_column(loc, value[:, i].tolist(), pi) - def _setitem_with_indexer_frame_value(self, indexer, value: "DataFrame"): + def _setitem_with_indexer_frame_value(self, indexer, value: "DataFrame", name: str): ilocs = self._ensure_iterable_column_indexer(indexer[1]) sub_indexer = list(indexer) @@ -1724,7 +1724,13 @@ def _setitem_with_indexer_frame_value(self, indexer, value: "DataFrame"): unique_cols = value.columns.is_unique - if not unique_cols and value.columns.equals(self.obj.columns): + # We do not want to align the value in case of iloc GH#37728 + if name == "iloc": + for i, loc in enumerate(ilocs): + val = value.iloc[:, i] + self._setitem_single_column(loc, val, pi) + + elif not unique_cols and value.columns.equals(self.obj.columns): # We assume we are already aligned, see # test_iloc_setitem_frame_duplicate_columns_multiple_blocks for loc in ilocs: @@ -1787,7 +1793,7 @@ def _setitem_single_column(self, loc: int, value, plane_indexer): # reset the sliced object if unique self.obj._iset_item(loc, ser) - def _setitem_single_block(self, indexer, value): + def _setitem_single_block(self, indexer, value, name: str): """ _setitem_with_indexer for the case when we have a single Block. """ @@ -1815,14 +1821,13 @@ def _setitem_single_block(self, indexer, value): return indexer = maybe_convert_ix(*indexer) - - if isinstance(value, (ABCSeries, dict)): + if isinstance(value, ABCSeries) and name != "iloc" or isinstance(value, dict): # TODO(EA): ExtensionBlock.setitem this causes issues with # setting for extensionarrays that store dicts. Need to decide # if it's worth supporting that. value = self._align_series(indexer, Series(value)) - elif isinstance(value, ABCDataFrame): + elif isinstance(value, ABCDataFrame) and name != "iloc": value = self._align_frame(indexer, value) # check for chained assignment @@ -1854,7 +1859,7 @@ def _setitem_with_indexer_missing(self, indexer, value): if index.is_unique: new_indexer = index.get_indexer([new_index[-1]]) if (new_indexer != -1).any(): - return self._setitem_with_indexer(new_indexer, value) + return self._setitem_with_indexer(new_indexer, value, "loc") # this preserves dtype of the value new_values = Series([value])._values diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index cb04a61b9e1cb..e4c57dc2b72fc 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -289,15 +289,6 @@ def test_setitem_periodindex(self): assert isinstance(rs.index, PeriodIndex) tm.assert_index_equal(rs.index, rng) - @pytest.mark.parametrize("klass", [list, np.array]) - def test_iloc_setitem_bool_indexer(self, klass): - # GH: 36741 - df = DataFrame({"flag": ["x", "y", "z"], "value": [1, 3, 4]}) - indexer = klass([True, False, False]) - df.iloc[indexer, 1] = df.iloc[indexer, 1] * 2 - expected = DataFrame({"flag": ["x", "y", "z"], "value": [2, 3, 4]}) - tm.assert_frame_equal(df, expected) - class TestDataFrameSetItemSlicing: def test_setitem_slice_position(self): diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 0360d7e01e62d..84073bbb023a8 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -801,6 +801,39 @@ def test_iloc_setitem_empty_frame_raises_with_3d_ndarray(self): with pytest.raises(ValueError, match=msg): obj.iloc[nd3] = 0 + def test_iloc_assign_series_to_df_cell(self): + # GH 37593 + df = DataFrame(columns=["a"], index=[0]) + df.iloc[0, 0] = Series([1, 2, 3]) + expected = DataFrame({"a": [Series([1, 2, 3])]}, columns=["a"], index=[0]) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("klass", [list, np.array]) + def test_iloc_setitem_bool_indexer(self, klass): + # GH#36741 + df = DataFrame({"flag": ["x", "y", "z"], "value": [1, 3, 4]}) + indexer = klass([True, False, False]) + df.iloc[indexer, 1] = df.iloc[indexer, 1] * 2 + expected = DataFrame({"flag": ["x", "y", "z"], "value": [2, 3, 4]}) + tm.assert_frame_equal(df, expected) + + @pytest.mark.parametrize("indexer", [[1], slice(1, 2)]) + def test_setitem_iloc_pure_position_based(self, indexer): + # GH#22046 + df1 = DataFrame({"a2": [11, 12, 13], "b2": [14, 15, 16]}) + df2 = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}) + df2.iloc[:, indexer] = df1.iloc[:, [0]] + expected = DataFrame({"a": [1, 2, 3], "b": [11, 12, 13], "c": [7, 8, 9]}) + tm.assert_frame_equal(df2, expected) + + def test_setitem_iloc_dictionary_value(self): + # GH#37728 + df = DataFrame({"x": [1, 2], "y": [2, 2]}) + rhs = dict(x=9, y=99) + df.iloc[1] = rhs + expected = DataFrame({"x": [1, 9], "y": [2, 99]}) + tm.assert_frame_equal(df, expected) + class TestILocErrors: # NB: this test should work for _any_ Series we can pass as @@ -966,3 +999,11 @@ def test_iloc(self): def test_iloc_getitem_nonunique(self): ser = Series([0, 1, 2], index=[0, 1, 0]) assert ser.iloc[2] == 2 + + def test_setitem_iloc_pure_position_based(self): + # GH#22046 + ser1 = Series([1, 2, 3]) + ser2 = Series([4, 5, 6], index=[1, 0, 2]) + ser1.iloc[1:3] = ser2.iloc[1:3] + expected = Series([1, 5, 6]) + tm.assert_series_equal(ser1, expected) diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 7470d2768590e..aae8398db2b4d 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -668,43 +668,48 @@ def test_float_index_at_iat(self): def test_rhs_alignment(self): # GH8258, tests that both rows & columns are aligned to what is # assigned to. covers both uniform data-type & multi-type cases - def run_tests(df, rhs, right): + def run_tests(df, rhs, right_loc, right_iloc): # label, index, slice lbl_one, idx_one, slice_one = list("bcd"), [1, 2, 3], slice(1, 4) lbl_two, idx_two, slice_two = ["joe", "jolie"], [1, 2], slice(1, 3) left = df.copy() left.loc[lbl_one, lbl_two] = rhs - tm.assert_frame_equal(left, right) + tm.assert_frame_equal(left, right_loc) left = df.copy() left.iloc[idx_one, idx_two] = rhs - tm.assert_frame_equal(left, right) + tm.assert_frame_equal(left, right_iloc) left = df.copy() left.iloc[slice_one, slice_two] = rhs - tm.assert_frame_equal(left, right) + tm.assert_frame_equal(left, right_iloc) xs = np.arange(20).reshape(5, 4) cols = ["jim", "joe", "jolie", "joline"] - df = DataFrame(xs, columns=cols, index=list("abcde")) + df = DataFrame(xs, columns=cols, index=list("abcde"), dtype="int64") # right hand side; permute the indices and multiplpy by -2 rhs = -2 * df.iloc[3:0:-1, 2:0:-1] # expected `right` result; just multiply by -2 - right = df.copy() - right.iloc[1:4, 1:3] *= -2 + right_iloc = df.copy() + right_iloc["joe"] = [1, 14, 10, 6, 17] + right_iloc["jolie"] = [2, 13, 9, 5, 18] + right_iloc.iloc[1:4, 1:3] *= -2 + right_loc = df.copy() + right_loc.iloc[1:4, 1:3] *= -2 # run tests with uniform dtypes - run_tests(df, rhs, right) + run_tests(df, rhs, right_loc, right_iloc) # make frames multi-type & re-run tests - for frame in [df, rhs, right]: + for frame in [df, rhs, right_loc, right_iloc]: frame["joe"] = frame["joe"].astype("float64") frame["jolie"] = frame["jolie"].map("@{}".format) - - run_tests(df, rhs, right) + right_iloc["joe"] = [1.0, "@-28", "@-20", "@-12", 17.0] + right_iloc["jolie"] = ["@2", -26.0, -18.0, -10.0, "@18"] + run_tests(df, rhs, right_loc, right_iloc) def test_str_label_slicing_with_negative_step(self): SLC = pd.IndexSlice
- [x] closes #22046 - [x] closes #37593 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry If iloc should be purely position based, this PR fixes the bug described in the issue. One test depends on the wrong behavior, so I had to adjust it.
https://api.github.com/repos/pandas-dev/pandas/pulls/37728
2020-11-10T00:27:19Z
2020-11-19T00:22:07Z
2020-11-19T00:22:06Z
2020-11-19T20:00:27Z