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
DOC: small clean ups
diff --git a/doc/source/getting_started/install.rst b/doc/source/getting_started/install.rst index cd61f17220f22..df481e8c986f7 100644 --- a/doc/source/getting_started/install.rst +++ b/doc/source/getting_started/install.rst @@ -28,20 +28,20 @@ Installing pandas Installing with Anaconda ~~~~~~~~~~~~~~~~~~~~~~~~ -Installing pandas and the rest of the `NumPy <https://www.numpy.org/>`__ and -`SciPy <https://www.scipy.org/>`__ stack can be a little +Installing pandas and the rest of the `NumPy <https://numpy.org/>`__ and +`SciPy <https://scipy.org/>`__ stack can be a little difficult for inexperienced users. The simplest way to install not only pandas, but Python and the most popular -packages that make up the `SciPy <https://www.scipy.org/>`__ stack -(`IPython <https://ipython.org/>`__, `NumPy <https://www.numpy.org/>`__, +packages that make up the `SciPy <https://scipy.org/>`__ stack +(`IPython <https://ipython.org/>`__, `NumPy <https://numpy.org/>`__, `Matplotlib <https://matplotlib.org/>`__, ...) is with `Anaconda <https://docs.continuum.io/anaconda/>`__, a cross-platform -(Linux, Mac OS X, Windows) Python distribution for data analytics and +(Linux, macOS, Windows) Python distribution for data analytics and scientific computing. After running the installer, the user will have access to pandas and the -rest of the `SciPy <https://www.scipy.org/>`__ stack without needing to install +rest of the `SciPy <https://scipy.org/>`__ stack without needing to install anything else, and without needing to wait for any software to be compiled. Installation instructions for `Anaconda <https://docs.continuum.io/anaconda/>`__ @@ -220,7 +220,7 @@ Dependencies Package Minimum supported version ================================================================ ========================== `setuptools <https://setuptools.readthedocs.io/en/latest/>`__ 24.2.0 -`NumPy <https://www.numpy.org>`__ 1.16.5 +`NumPy <https://numpy.org>`__ 1.16.5 `python-dateutil <https://dateutil.readthedocs.io/en/stable/>`__ 2.7.3 `pytz <https://pypi.org/project/pytz/>`__ 2017.3 ================================================================ ==========================
small clean ups - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37412
2020-10-26T04:02:40Z
2020-10-26T13:47:37Z
2020-10-26T13:47:37Z
2022-07-15T23:39:28Z
TST/CLN: misplaced factorize tests
diff --git a/pandas/tests/base/test_factorize.py b/pandas/tests/base/test_factorize.py deleted file mode 100644 index f8cbadb987d29..0000000000000 --- a/pandas/tests/base/test_factorize.py +++ /dev/null @@ -1,41 +0,0 @@ -import numpy as np -import pytest - -import pandas as pd -import pandas._testing as tm - - -@pytest.mark.parametrize("sort", [True, False]) -def test_factorize(index_or_series_obj, sort): - obj = index_or_series_obj - result_codes, result_uniques = obj.factorize(sort=sort) - - constructor = pd.Index - if isinstance(obj, pd.MultiIndex): - constructor = pd.MultiIndex.from_tuples - expected_uniques = constructor(obj.unique()) - - if sort: - expected_uniques = expected_uniques.sort_values() - - # construct an integer ndarray so that - # `expected_uniques.take(expected_codes)` is equal to `obj` - expected_uniques_list = list(expected_uniques) - expected_codes = [expected_uniques_list.index(val) for val in obj] - expected_codes = np.asarray(expected_codes, dtype=np.intp) - - tm.assert_numpy_array_equal(result_codes, expected_codes) - tm.assert_index_equal(result_uniques, expected_uniques) - - -def test_series_factorize_na_sentinel_none(): - # GH35667 - values = np.array([1, 2, 1, np.nan]) - ser = pd.Series(values) - codes, uniques = ser.factorize(na_sentinel=None) - - expected_codes = np.array([0, 1, 0, 2], dtype=np.intp) - expected_uniques = pd.Index([1.0, 2.0, np.nan]) - - tm.assert_numpy_array_equal(codes, expected_codes) - tm.assert_index_equal(uniques, expected_uniques) diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index ee8e2385fe698..caaca38d07fa5 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -23,11 +23,21 @@ from pandas import ( Categorical, CategoricalIndex, + DataFrame, DatetimeIndex, Index, IntervalIndex, + MultiIndex, + NaT, + Period, + PeriodIndex, Series, + Timedelta, Timestamp, + date_range, + timedelta_range, + to_datetime, + to_timedelta, ) import pandas._testing as tm import pandas.core.algorithms as algos @@ -36,6 +46,40 @@ class TestFactorize: + @pytest.mark.parametrize("sort", [True, False]) + def test_factorize(self, index_or_series_obj, sort): + obj = index_or_series_obj + result_codes, result_uniques = obj.factorize(sort=sort) + + constructor = Index + if isinstance(obj, MultiIndex): + constructor = MultiIndex.from_tuples + expected_uniques = constructor(obj.unique()) + + if sort: + expected_uniques = expected_uniques.sort_values() + + # construct an integer ndarray so that + # `expected_uniques.take(expected_codes)` is equal to `obj` + expected_uniques_list = list(expected_uniques) + expected_codes = [expected_uniques_list.index(val) for val in obj] + expected_codes = np.asarray(expected_codes, dtype=np.intp) + + tm.assert_numpy_array_equal(result_codes, expected_codes) + tm.assert_index_equal(result_uniques, expected_uniques) + + def test_series_factorize_na_sentinel_none(self): + # GH#35667 + values = np.array([1, 2, 1, np.nan]) + ser = Series(values) + codes, uniques = ser.factorize(na_sentinel=None) + + expected_codes = np.array([0, 1, 0, 2], dtype=np.intp) + expected_uniques = Index([1.0, 2.0, np.nan]) + + tm.assert_numpy_array_equal(codes, expected_codes) + tm.assert_index_equal(uniques, expected_uniques) + def test_basic(self): codes, uniques = algos.factorize(["a", "b", "b", "a", "a", "c", "c", "c"]) @@ -111,34 +155,34 @@ def test_datelike(self): tm.assert_index_equal(uniques, exp) # period - v1 = pd.Period("201302", freq="M") - v2 = pd.Period("201303", freq="M") + v1 = Period("201302", freq="M") + v2 = Period("201303", freq="M") x = Series([v1, v1, v1, v2, v2, v1]) # periods are not 'sorted' as they are converted back into an index codes, uniques = algos.factorize(x) exp = np.array([0, 0, 0, 1, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) - tm.assert_index_equal(uniques, pd.PeriodIndex([v1, v2])) + tm.assert_index_equal(uniques, PeriodIndex([v1, v2])) codes, uniques = algos.factorize(x, sort=True) exp = np.array([0, 0, 0, 1, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) - tm.assert_index_equal(uniques, pd.PeriodIndex([v1, v2])) + tm.assert_index_equal(uniques, PeriodIndex([v1, v2])) # GH 5986 - v1 = pd.to_timedelta("1 day 1 min") - v2 = pd.to_timedelta("1 day") + v1 = to_timedelta("1 day 1 min") + v2 = to_timedelta("1 day") x = Series([v1, v2, v1, v1, v2, v2, v1]) codes, uniques = algos.factorize(x) exp = np.array([0, 1, 0, 0, 1, 1, 0], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) - tm.assert_index_equal(uniques, pd.to_timedelta([v1, v2])) + tm.assert_index_equal(uniques, to_timedelta([v1, v2])) codes, uniques = algos.factorize(x, sort=True) exp = np.array([1, 0, 1, 1, 0, 0, 1], dtype=np.intp) tm.assert_numpy_array_equal(codes, exp) - tm.assert_index_equal(uniques, pd.to_timedelta([v2, v1])) + tm.assert_index_equal(uniques, to_timedelta([v2, v1])) def test_factorize_nan(self): # nan should map to na_sentinel, not reverse_indexer[na_sentinel] @@ -241,7 +285,7 @@ def test_string_factorize(self, writable): tm.assert_numpy_array_equal(uniques, expected_uniques) def test_object_factorize(self, writable): - data = np.array(["a", "c", None, np.nan, "a", "b", pd.NaT, "c"], dtype=object) + data = np.array(["a", "c", None, np.nan, "a", "b", NaT, "c"], dtype=object) data.setflags(write=writable) expected_codes = np.array([0, 1, -1, -1, 0, 2, -1, 1], dtype=np.intp) expected_uniques = np.array(["a", "c", "b"], dtype=object) @@ -404,7 +448,7 @@ def test_object_refcount_bug(self): def test_on_index_object(self): - mindex = pd.MultiIndex.from_arrays( + mindex = MultiIndex.from_arrays( [np.arange(5).repeat(5), np.tile(np.arange(5), 5)] ) expected = mindex.values @@ -456,7 +500,7 @@ def test_datetime64_dtype_array_returned(self): dtype="M8[ns]", ) - dt_index = pd.to_datetime( + dt_index = to_datetime( [ "2015-01-03T00:00:00.000000000", "2015-01-01T00:00:00.000000000", @@ -493,7 +537,7 @@ def test_timedelta64_dtype_array_returned(self): # GH 9431 expected = np.array([31200, 45678, 10000], dtype="m8[ns]") - td_index = pd.to_timedelta([31200, 45678, 31200, 10000, 45678]) + td_index = to_timedelta([31200, 45678, 31200, 10000, 45678]) result = algos.unique(td_index) tm.assert_numpy_array_equal(result, expected) assert result.dtype == expected.dtype @@ -772,7 +816,7 @@ def test_basic(self): def test_i8(self): - arr = pd.date_range("20130101", periods=3).values + arr = date_range("20130101", periods=3).values result = algos.isin(arr, [arr[0]]) expected = np.array([True, False, False]) tm.assert_numpy_array_equal(result, expected) @@ -785,7 +829,7 @@ def test_i8(self): expected = np.array([True, True, False]) tm.assert_numpy_array_equal(result, expected) - arr = pd.timedelta_range("1 day", periods=3).values + arr = timedelta_range("1 day", periods=3).values result = algos.isin(arr, [arr[0]]) expected = np.array([True, False, False]) tm.assert_numpy_array_equal(result, expected) @@ -799,7 +843,7 @@ def test_i8(self): tm.assert_numpy_array_equal(result, expected) def test_large(self): - s = pd.date_range("20000101", periods=2000000, freq="s").values + s = date_range("20000101", periods=2000000, freq="s").values result = algos.isin(s, s[0:2]) expected = np.zeros(len(s), dtype=bool) expected[0] = True @@ -950,27 +994,27 @@ def test_different_nans_as_float64(self): def test_isin_int_df_string_search(self): """Comparing df with int`s (1,2) with a string at isin() ("1") -> should not match values because int 1 is not equal str 1""" - df = pd.DataFrame({"values": [1, 2]}) + df = DataFrame({"values": [1, 2]}) result = df.isin(["1"]) - expected_false = pd.DataFrame({"values": [False, False]}) + expected_false = DataFrame({"values": [False, False]}) tm.assert_frame_equal(result, expected_false) @pytest.mark.xfail(reason="problem related with issue #34125") def test_isin_nan_df_string_search(self): """Comparing df with nan value (np.nan,2) with a string at isin() ("NaN") -> should not match values because np.nan is not equal str NaN""" - df = pd.DataFrame({"values": [np.nan, 2]}) + df = DataFrame({"values": [np.nan, 2]}) result = df.isin(["NaN"]) - expected_false = pd.DataFrame({"values": [False, False]}) + expected_false = DataFrame({"values": [False, False]}) tm.assert_frame_equal(result, expected_false) @pytest.mark.xfail(reason="problem related with issue #34125") def test_isin_float_df_string_search(self): """Comparing df with floats (1.4245,2.32441) with a string at isin() ("1.4245") -> should not match values because float 1.4245 is not equal str 1.4245""" - df = pd.DataFrame({"values": [1.4245, 2.32441]}) + df = DataFrame({"values": [1.4245, 2.32441]}) result = df.isin(["1.4245"]) - expected_false = pd.DataFrame({"values": [False, False]}) + expected_false = DataFrame({"values": [False, False]}) tm.assert_frame_equal(result, expected_false) @@ -1016,8 +1060,8 @@ def test_value_counts_dtypes(self): algos.value_counts(["1", 1], bins=1) def test_value_counts_nat(self): - td = Series([np.timedelta64(10000), pd.NaT], dtype="timedelta64[ns]") - dt = pd.to_datetime(["NaT", "2014-01-01"]) + td = Series([np.timedelta64(10000), NaT], dtype="timedelta64[ns]") + dt = to_datetime(["NaT", "2014-01-01"]) for s in [td, dt]: vc = algos.value_counts(s) @@ -1051,7 +1095,7 @@ def test_value_counts_datetime_outofbounds(self): tm.assert_series_equal(res, exp) # GH 12424 - res = pd.to_datetime(Series(["2362-01-01", np.nan]), errors="ignore") + res = to_datetime(Series(["2362-01-01", np.nan]), errors="ignore") exp = Series(["2362-01-01", np.nan], dtype=object) tm.assert_series_equal(res, exp) @@ -1323,9 +1367,9 @@ def test_datetime_likes(self): cases = [ np.array([Timestamp(d) for d in dt]), np.array([Timestamp(d, tz="US/Eastern") for d in dt]), - np.array([pd.Period(d, freq="D") for d in dt]), + np.array([Period(d, freq="D") for d in dt]), np.array([np.datetime64(d) for d in dt]), - np.array([pd.Timedelta(d) for d in td]), + np.array([Timedelta(d) for d in td]), ] exp_first = np.array( @@ -1530,7 +1574,7 @@ def test_hashtable_unique(self, htable, tm_dtype, writable): s.loc[500] = np.nan elif htable == ht.PyObjectHashTable: # use different NaN types for object column - s.loc[500:502] = [np.nan, None, pd.NaT] + s.loc[500:502] = [np.nan, None, NaT] # create duplicated selection s_duplicated = s.sample(frac=3, replace=True).reset_index(drop=True) @@ -1570,7 +1614,7 @@ def test_hashtable_factorize(self, htable, tm_dtype, writable): s.loc[500] = np.nan elif htable == ht.PyObjectHashTable: # use different NaN types for object column - s.loc[500:502] = [np.nan, None, pd.NaT] + s.loc[500:502] = [np.nan, None, NaT] # create duplicated selection s_duplicated = s.sample(frac=3, replace=True).reset_index(drop=True) @@ -2307,7 +2351,7 @@ def test_diff_datetimelike_nat(self, dtype): tm.assert_numpy_array_equal(result, expected.T) def test_diff_ea_axis(self): - dta = pd.date_range("2016-01-01", periods=3, tz="US/Pacific")._data + dta = date_range("2016-01-01", periods=3, tz="US/Pacific")._data msg = "cannot diff DatetimeArray on axis=1" with pytest.raises(ValueError, match=msg):
https://api.github.com/repos/pandas-dev/pandas/pulls/37411
2020-10-26T02:15:20Z
2020-10-26T12:04:12Z
2020-10-26T12:04:12Z
2020-10-26T15:03:30Z
TST/REF: misplaced tests in tests.base
diff --git a/pandas/tests/base/test_drop_duplicates.py b/pandas/tests/base/test_drop_duplicates.py index 4032890b4db18..8cde7aae5df05 100644 --- a/pandas/tests/base/test_drop_duplicates.py +++ b/pandas/tests/base/test_drop_duplicates.py @@ -1,12 +1,14 @@ from datetime import datetime import numpy as np +import pytest import pandas as pd import pandas._testing as tm -def test_drop_duplicates_series_vs_dataframe(): +@pytest.mark.parametrize("keep", ["first", "last", False]) +def test_drop_duplicates_series_vs_dataframe(keep): # GH 14192 df = pd.DataFrame( { @@ -24,7 +26,6 @@ def test_drop_duplicates_series_vs_dataframe(): } ) for column in df.columns: - for keep in ["first", "last", False]: - dropped_frame = df[[column]].drop_duplicates(keep=keep) - dropped_series = df[column].drop_duplicates(keep=keep) - tm.assert_frame_equal(dropped_frame, dropped_series.to_frame()) + dropped_frame = df[[column]].drop_duplicates(keep=keep) + dropped_series = df[column].drop_duplicates(keep=keep) + tm.assert_frame_equal(dropped_frame, dropped_series.to_frame()) diff --git a/pandas/tests/base/test_misc.py b/pandas/tests/base/test_misc.py index f7952c81cfd61..2a17006a7c407 100644 --- a/pandas/tests/base/test_misc.py +++ b/pandas/tests/base/test_misc.py @@ -14,7 +14,6 @@ import pandas as pd from pandas import DataFrame, Index, IntervalIndex, Series -import pandas._testing as tm @pytest.mark.parametrize( @@ -196,10 +195,3 @@ def test_access_by_position(index): msg = "single positional indexer is out-of-bounds" with pytest.raises(IndexError, match=msg): series.iloc[size] - - -def test_get_indexer_non_unique_dtype_mismatch(): - # GH 25459 - indexes, missing = Index(["A", "B"]).get_indexer_non_unique(Index([0])) - tm.assert_numpy_array_equal(np.array([-1], dtype=np.intp), indexes) - tm.assert_numpy_array_equal(np.array([0], dtype=np.intp), missing) diff --git a/pandas/tests/indexes/base_class/test_indexing.py b/pandas/tests/indexes/base_class/test_indexing.py index b2fa8f31ee5ec..fd04a820037b9 100644 --- a/pandas/tests/indexes/base_class/test_indexing.py +++ b/pandas/tests/indexes/base_class/test_indexing.py @@ -1,6 +1,8 @@ +import numpy as np import pytest from pandas import Index +import pandas._testing as tm class TestGetSliceBounds: @@ -24,3 +26,11 @@ def test_get_slice_bounds_outside(self, kind, side, expected, data, bound): def test_get_slice_bounds_invalid_side(self): with pytest.raises(ValueError, match="Invalid value for side kwarg"): Index([]).get_slice_bound("a", kind=None, side="middle") + + +class TestGetIndexerNonUnique: + def test_get_indexer_non_unique_dtype_mismatch(self): + # GH#25459 + indexes, missing = Index(["A", "B"]).get_indexer_non_unique(Index([0])) + tm.assert_numpy_array_equal(np.array([-1], dtype=np.intp), indexes) + tm.assert_numpy_array_equal(np.array([0], dtype=np.intp), missing)
https://api.github.com/repos/pandas-dev/pandas/pulls/37410
2020-10-26T01:56:41Z
2020-10-26T12:12:24Z
2020-10-26T12:12:24Z
2020-10-26T15:17:33Z
TST: Set timeoffset as the window parameter
diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index e919812be9fce..02365906c55bb 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -919,6 +919,67 @@ def test_rolling_var_numerical_issues(func, third_value, values): tm.assert_series_equal(result, expected) +def test_timeoffset_as_window_parameter_for_corr(): + # GH: 28266 + exp = DataFrame( + { + "B": [ + np.nan, + np.nan, + 0.9999999999999998, + -1.0, + 1.0, + -0.3273268353539892, + 0.9999999999999998, + 1.0, + 0.9999999999999998, + 1.0, + ], + "A": [ + np.nan, + np.nan, + -1.0, + 1.0000000000000002, + -0.3273268353539892, + 0.9999999999999966, + 1.0, + 1.0000000000000002, + 1.0, + 1.0000000000000002, + ], + }, + index=pd.MultiIndex.from_tuples( + [ + (pd.Timestamp("20130101 09:00:00"), "B"), + (pd.Timestamp("20130101 09:00:00"), "A"), + (pd.Timestamp("20130102 09:00:02"), "B"), + (pd.Timestamp("20130102 09:00:02"), "A"), + (pd.Timestamp("20130103 09:00:03"), "B"), + (pd.Timestamp("20130103 09:00:03"), "A"), + (pd.Timestamp("20130105 09:00:05"), "B"), + (pd.Timestamp("20130105 09:00:05"), "A"), + (pd.Timestamp("20130106 09:00:06"), "B"), + (pd.Timestamp("20130106 09:00:06"), "A"), + ] + ), + ) + + df = DataFrame( + {"B": [0, 1, 2, 4, 3], "A": [7, 4, 6, 9, 3]}, + index=[ + pd.Timestamp("20130101 09:00:00"), + pd.Timestamp("20130102 09:00:02"), + pd.Timestamp("20130103 09:00:03"), + pd.Timestamp("20130105 09:00:05"), + pd.Timestamp("20130106 09:00:06"), + ], + ) + + res = df.rolling(window="3d").corr() + + tm.assert_frame_equal(exp, res) + + @pytest.mark.parametrize("method", ["var", "sum", "mean", "skew", "kurt", "min", "max"]) def test_rolling_decreasing_indices(method): """
- [X] closes #28266 - [X] tests added / passed - [X] passes `black pandas` - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Hi guys, just added tests for issue #28266. I'm participating in the Hacktoberfest event and would much appreciate it if someone put the label ‘hacktoberfest-accepted’ on this PR. Any modification needed just hit me up :)
https://api.github.com/repos/pandas-dev/pandas/pulls/37407
2020-10-25T22:51:15Z
2020-10-26T03:18:19Z
2020-10-26T03:18:18Z
2020-10-27T15:45:14Z
BUG: Fix inconsistent ordering between left and right in merge
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index cea42cbffa906..68b13c2fe28f5 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -712,6 +712,7 @@ Reshaping - Fixed regression in :func:`merge` on merging DatetimeIndex with empty DataFrame (:issue:`36895`) - Bug in :meth:`DataFrame.apply` not setting index of return value when ``func`` return type is ``dict`` (:issue:`37544`) - Bug in :func:`concat` resulting in a ``ValueError`` when at least one of both inputs had a non-unique index (:issue:`36263`) +- Bug in :meth:`DataFrame.merge` and :meth:`pandas.merge` returning inconsistent ordering in result for ``how=right`` and ``how=left`` (:issue:`35382`) Sparse ^^^^^^ diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 918a894a27916..cdcd6b19704c4 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -1358,12 +1358,14 @@ def get_join_indexers( lkey, rkey, count = _factorize_keys(lkey, rkey, sort=sort, how=how) # preserve left frame order if how == 'left' and sort == False kwargs = copy.copy(kwargs) - if how == "left": + if how in ("left", "right"): kwargs["sort"] = sort join_func = { "inner": libjoin.inner_join, "left": libjoin.left_outer_join, - "right": _right_outer_join, + "right": lambda x, y, count, **kwargs: libjoin.left_outer_join( + y, x, count, **kwargs + )[::-1], "outer": libjoin.full_outer_join, }[how] @@ -1883,11 +1885,6 @@ def _left_join_on_index(left_ax: Index, right_ax: Index, join_keys, sort: bool = return left_ax, None, right_indexer -def _right_outer_join(x, y, max_groups): - right_indexer, left_indexer = libjoin.left_outer_join(y, x, max_groups) - return left_indexer, right_indexer - - def _factorize_keys( lk: ArrayLike, rk: ArrayLike, sort: bool = True, how: str = "inner" ) -> Tuple[np.ndarray, np.ndarray, int]: diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 999b827fe0571..9ccfdfc146eac 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -601,6 +601,18 @@ def test_merge_nosort(self): assert (df.var3.unique() == result.var3.unique()).all() + @pytest.mark.parametrize( + ("sort", "values"), [(False, [1, 1, 0, 1, 1]), (True, [0, 1, 1, 1, 1])] + ) + @pytest.mark.parametrize("how", ["left", "right"]) + def test_merge_same_order_left_right(self, sort, values, how): + # GH#35382 + df = DataFrame({"a": [1, 0, 1]}) + + result = df.merge(df, on="a", how=how, sort=sort) + expected = DataFrame(values, columns=["a"]) + tm.assert_frame_equal(result, expected) + def test_merge_nan_right(self): df1 = DataFrame({"i1": [0, 1], "i2": [0, 1]}) df2 = DataFrame({"i1": [0], "i3": [0]})
- [x] closes #35382 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Passed sort through for right join too. Did not see a reason why not. On a related note: I think outer joins return a inconsistent order too. ``` df = pd.DataFrame({'a': [1, 0, 1]}) print(df.merge(df, on='a', how='outer', sort=False)) a 0 1 1 1 2 1 3 1 4 0 ``` instead of ``` a 0 1 1 1 2 0 3 1 4 1 ``` like ``left`` and ``right`` now. Would have to add a ``sort`` keyword to outer join. Should I open an issue for that?
https://api.github.com/repos/pandas-dev/pandas/pulls/37406
2020-10-25T22:18:48Z
2020-11-21T22:23:28Z
2020-11-21T22:23:27Z
2020-11-21T23:50:46Z
CLN: Fix unwanted pattern in unittest
diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index e224c20ca84d3..c85f65cd62563 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -694,7 +694,7 @@ def test_constructor_invalid_coerce_ints_with_float_nan(self, any_int_dtype): msg = "cannot convert float NaN to integer" with pytest.raises(ValueError, match=msg): - pd.Series([1, 2, np.nan], dtype=any_int_dtype) + Series([1, 2, np.nan], dtype=any_int_dtype) def test_constructor_dtype_no_cast(self): # see gh-1572
- [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` Introduced with #37090
https://api.github.com/repos/pandas-dev/pandas/pulls/37404
2020-10-25T19:38:48Z
2020-10-25T19:45:50Z
2020-10-25T19:45:49Z
2020-10-25T19:54:02Z
TST/REF: collect tests by method
diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py index 91992da594288..c589b72fa2895 100644 --- a/pandas/tests/arrays/categorical/test_indexing.py +++ b/pandas/tests/arrays/categorical/test_indexing.py @@ -91,6 +91,22 @@ def test_setitem_tuple(self): cat[1] = cat[0] assert cat[1] == (0, 1) + def test_setitem_listlike(self): + + # GH#9469 + # properly coerce the input indexers + np.random.seed(1) + c = Categorical( + np.random.randint(0, 5, size=150000).astype(np.int8) + ).add_categories([-1000]) + indexer = np.array([100000]).astype(np.int64) + c[indexer] = -1000 + + # we are asserting the code result here + # which maps to the -1000 category + result = c.codes[np.array([100000]).astype(np.int64)] + tm.assert_numpy_array_equal(result, np.array([5], dtype="int8")) + class TestCategoricalIndexing: def test_getitem_slice(self): diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py index 5a5aac87b057d..9e50d2889f9ad 100644 --- a/pandas/tests/frame/methods/test_reindex.py +++ b/pandas/tests/frame/methods/test_reindex.py @@ -5,8 +5,18 @@ import pytest import pandas as pd -from pandas import Categorical, DataFrame, Index, MultiIndex, Series, date_range, isna +from pandas import ( + Categorical, + CategoricalIndex, + DataFrame, + Index, + MultiIndex, + Series, + date_range, + isna, +) import pandas._testing as tm +from pandas.api.types import CategoricalDtype as CDT import pandas.core.common as com @@ -745,3 +755,94 @@ def test_reindex_multi_categorical_time(self): result = df2.reindex(midx) expected = DataFrame({"a": [0, 1, 2, 3, 4, 5, 6, np.nan, 8]}, index=midx) tm.assert_frame_equal(result, expected) + + def test_reindex_with_categoricalindex(self): + df = DataFrame( + { + "A": np.arange(3, dtype="int64"), + }, + index=CategoricalIndex(list("abc"), dtype=CDT(list("cabe")), name="B"), + ) + + # reindexing + # convert to a regular index + result = df.reindex(["a", "b", "e"]) + expected = DataFrame({"A": [0, 1, np.nan], "B": Series(list("abe"))}).set_index( + "B" + ) + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(["a", "b"]) + expected = DataFrame({"A": [0, 1], "B": Series(list("ab"))}).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(["e"]) + expected = DataFrame({"A": [np.nan], "B": Series(["e"])}).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(["d"]) + expected = DataFrame({"A": [np.nan], "B": Series(["d"])}).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + # since we are actually reindexing with a Categorical + # then return a Categorical + cats = list("cabe") + + result = df.reindex(Categorical(["a", "e"], categories=cats)) + expected = DataFrame( + {"A": [0, np.nan], "B": Series(list("ae")).astype(CDT(cats))} + ).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(Categorical(["a"], categories=cats)) + expected = DataFrame( + {"A": [0], "B": Series(list("a")).astype(CDT(cats))} + ).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(["a", "b", "e"]) + expected = DataFrame({"A": [0, 1, np.nan], "B": Series(list("abe"))}).set_index( + "B" + ) + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(["a", "b"]) + expected = DataFrame({"A": [0, 1], "B": Series(list("ab"))}).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(["e"]) + expected = DataFrame({"A": [np.nan], "B": Series(["e"])}).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + # give back the type of categorical that we received + result = df.reindex(Categorical(["a", "e"], categories=cats, ordered=True)) + expected = DataFrame( + {"A": [0, np.nan], "B": Series(list("ae")).astype(CDT(cats, ordered=True))} + ).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + result = df.reindex(Categorical(["a", "d"], categories=["a", "d"])) + expected = DataFrame( + {"A": [0, np.nan], "B": Series(list("ad")).astype(CDT(["a", "d"]))} + ).set_index("B") + tm.assert_frame_equal(result, expected, check_index_type=True) + + df2 = DataFrame( + { + "A": np.arange(6, dtype="int64"), + }, + index=CategoricalIndex(list("aabbca"), dtype=CDT(list("cabe")), name="B"), + ) + # passed duplicate indexers are not allowed + msg = "cannot reindex from a duplicate axis" + with pytest.raises(ValueError, match=msg): + df2.reindex(["a", "b"]) + + # args NotImplemented ATM + msg = r"argument {} is not implemented for CategoricalIndex\.reindex" + with pytest.raises(NotImplementedError, match=msg.format("method")): + df.reindex(["a"], method="ffill") + with pytest.raises(NotImplementedError, match=msg.format("level")): + df.reindex(["a"], level=1) + with pytest.raises(NotImplementedError, match=msg.format("limit")): + df.reindex(["a"], limit=2) diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py index 50d643cf83d7f..16d451a12efc0 100644 --- a/pandas/tests/frame/methods/test_sort_index.py +++ b/pandas/tests/frame/methods/test_sort_index.py @@ -4,6 +4,7 @@ import pandas as pd from pandas import ( CategoricalDtype, + CategoricalIndex, DataFrame, Index, IntervalIndex, @@ -495,7 +496,7 @@ def test_sort_index_categorical_multiindex(self): columns=["a"], index=MultiIndex( levels=[ - pd.CategoricalIndex( + CategoricalIndex( ["c", "a", "b"], categories=["c", "a", "b"], ordered=True, @@ -736,6 +737,34 @@ def test_sort_index_multilevel_repr_8017(self, gen, extra): result = result.sort_index(axis=1) tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize( + "categories", + [ + pytest.param(["a", "b", "c"], id="str"), + pytest.param( + [pd.Interval(0, 1), pd.Interval(1, 2), pd.Interval(2, 3)], + id="pd.Interval", + ), + ], + ) + def test_sort_index_with_categories(self, categories): + # GH#23452 + df = DataFrame( + {"foo": range(len(categories))}, + index=CategoricalIndex( + data=categories, categories=categories, ordered=True + ), + ) + df.index = df.index.reorder_categories(df.index.categories[::-1]) + result = df.sort_index() + expected = DataFrame( + {"foo": reversed(range(len(categories)))}, + index=CategoricalIndex( + data=categories[::-1], categories=categories[::-1], ordered=True + ), + ) + tm.assert_frame_equal(result, expected) + class TestDataFrameSortIndexKey: def test_sort_multi_index_key(self): diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py index d59dc08b94563..7a1f0a35e1486 100644 --- a/pandas/tests/frame/methods/test_sort_values.py +++ b/pandas/tests/frame/methods/test_sort_values.py @@ -3,6 +3,8 @@ import numpy as np import pytest +from pandas.errors import PerformanceWarning + import pandas as pd from pandas import Categorical, DataFrame, NaT, Timestamp, date_range import pandas._testing as tm @@ -711,3 +713,90 @@ def sorter(key): ) tm.assert_frame_equal(result, expected) + + +@pytest.fixture +def df_none(): + return DataFrame( + { + "outer": ["a", "a", "a", "b", "b", "b"], + "inner": [1, 2, 2, 2, 1, 1], + "A": np.arange(6, 0, -1), + ("B", 5): ["one", "one", "two", "two", "one", "one"], + } + ) + + +@pytest.fixture(params=[["outer"], ["outer", "inner"]]) +def df_idx(request, df_none): + levels = request.param + return df_none.set_index(levels) + + +@pytest.fixture( + params=[ + "inner", # index level + ["outer"], # list of index level + "A", # column + [("B", 5)], # list of column + ["inner", "outer"], # two index levels + [("B", 5), "outer"], # index level and column + ["A", ("B", 5)], # Two columns + ["inner", "outer"], # two index levels and column + ] +) +def sort_names(request): + return request.param + + +@pytest.fixture(params=[True, False]) +def ascending(request): + return request.param + + +class TestSortValuesLevelAsStr: + def test_sort_index_level_and_column_label( + self, df_none, df_idx, sort_names, ascending + ): + # GH#14353 + + # Get index levels from df_idx + levels = df_idx.index.names + + # Compute expected by sorting on columns and the setting index + expected = df_none.sort_values( + by=sort_names, ascending=ascending, axis=0 + ).set_index(levels) + + # Compute result sorting on mix on columns and index levels + result = df_idx.sort_values(by=sort_names, ascending=ascending, axis=0) + + tm.assert_frame_equal(result, expected) + + def test_sort_column_level_and_index_label( + self, df_none, df_idx, sort_names, ascending + ): + # GH#14353 + + # Get levels from df_idx + levels = df_idx.index.names + + # Compute expected by sorting on axis=0, setting index levels, and then + # transposing. For some cases this will result in a frame with + # multiple column levels + expected = ( + df_none.sort_values(by=sort_names, ascending=ascending, axis=0) + .set_index(levels) + .T + ) + + # Compute result by transposing and sorting on axis=1. + result = df_idx.T.sort_values(by=sort_names, ascending=ascending, axis=1) + + if len(levels) > 1: + # Accessing multi-level columns that are not lexsorted raises a + # performance warning + with tm.assert_produces_warning(PerformanceWarning, check_stacklevel=False): + tm.assert_frame_equal(result, expected) + else: + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 69f36f039e6db..1521f66a6bc61 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2699,6 +2699,13 @@ def test_frame_ctor_datetime64_column(self): class TestDataFrameConstructorWithDatetimeTZ: + def test_constructor_data_aware_dtype_naive(self, tz_aware_fixture): + # GH#25843 + tz = tz_aware_fixture + result = DataFrame({"d": [Timestamp("2019", tz=tz)]}, dtype="datetime64[ns]") + expected = DataFrame({"d": [Timestamp("2019")]}) + tm.assert_frame_equal(result, expected) + def test_from_dict(self): # 8260 diff --git a/pandas/tests/frame/test_join.py b/pandas/tests/frame/test_join.py index a2e1f2398e711..eba92cc71a6d0 100644 --- a/pandas/tests/frame/test_join.py +++ b/pandas/tests/frame/test_join.py @@ -4,7 +4,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, MultiIndex, period_range +from pandas import DataFrame, Index, MultiIndex, date_range, period_range import pandas._testing as tm @@ -341,3 +341,24 @@ def test_merge_join_different_levels(self): with tm.assert_produces_warning(UserWarning): result = df1.join(df2, on="a") tm.assert_frame_equal(result, expected) + + def test_frame_join_tzaware(self): + test1 = DataFrame( + np.zeros((6, 3)), + index=date_range( + "2012-11-15 00:00:00", periods=6, freq="100L", tz="US/Central" + ), + ) + test2 = DataFrame( + np.zeros((3, 3)), + index=date_range( + "2012-11-15 00:00:00", periods=3, freq="250L", tz="US/Central" + ), + columns=range(3, 6), + ) + + result = test1.join(test2, how="outer") + expected = test1.index.union(test2.index) + + tm.assert_index_equal(result.index, expected) + assert result.index.tz.zone == "US/Central" diff --git a/pandas/tests/frame/test_sort_values_level_as_str.py b/pandas/tests/frame/test_sort_values_level_as_str.py deleted file mode 100644 index 40526ab27ac9a..0000000000000 --- a/pandas/tests/frame/test_sort_values_level_as_str.py +++ /dev/null @@ -1,92 +0,0 @@ -import numpy as np -import pytest - -from pandas.errors import PerformanceWarning - -from pandas import DataFrame -import pandas._testing as tm - - -@pytest.fixture -def df_none(): - return DataFrame( - { - "outer": ["a", "a", "a", "b", "b", "b"], - "inner": [1, 2, 2, 2, 1, 1], - "A": np.arange(6, 0, -1), - ("B", 5): ["one", "one", "two", "two", "one", "one"], - } - ) - - -@pytest.fixture(params=[["outer"], ["outer", "inner"]]) -def df_idx(request, df_none): - levels = request.param - return df_none.set_index(levels) - - -@pytest.fixture( - params=[ - "inner", # index level - ["outer"], # list of index level - "A", # column - [("B", 5)], # list of column - ["inner", "outer"], # two index levels - [("B", 5), "outer"], # index level and column - ["A", ("B", 5)], # Two columns - ["inner", "outer"], # two index levels and column - ] -) -def sort_names(request): - return request.param - - -@pytest.fixture(params=[True, False]) -def ascending(request): - return request.param - - -def test_sort_index_level_and_column_label(df_none, df_idx, sort_names, ascending): - - # GH 14353 - - # Get index levels from df_idx - levels = df_idx.index.names - - # Compute expected by sorting on columns and the setting index - expected = df_none.sort_values( - by=sort_names, ascending=ascending, axis=0 - ).set_index(levels) - - # Compute result sorting on mix on columns and index levels - result = df_idx.sort_values(by=sort_names, ascending=ascending, axis=0) - - tm.assert_frame_equal(result, expected) - - -def test_sort_column_level_and_index_label(df_none, df_idx, sort_names, ascending): - - # GH 14353 - - # Get levels from df_idx - levels = df_idx.index.names - - # Compute expected by sorting on axis=0, setting index levels, and then - # transposing. For some cases this will result in a frame with - # multiple column levels - expected = ( - df_none.sort_values(by=sort_names, ascending=ascending, axis=0) - .set_index(levels) - .T - ) - - # Compute result by transposing and sorting on axis=1. - result = df_idx.T.sort_values(by=sort_names, ascending=ascending, axis=1) - - if len(levels) > 1: - # Accessing multi-level columns that are not lexsorted raises a - # performance warning - with tm.assert_produces_warning(PerformanceWarning, check_stacklevel=False): - tm.assert_frame_equal(result, expected) - else: - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py index f3667c4dd9d9d..22ffb30324366 100644 --- a/pandas/tests/frame/test_timeseries.py +++ b/pandas/tests/frame/test_timeseries.py @@ -1,4 +1,5 @@ import numpy as np +import pytest import pandas as pd from pandas import DataFrame, to_datetime @@ -6,39 +7,41 @@ class TestDataFrameTimeSeriesMethods: - def test_frame_append_datetime64_col_other_units(self): + @pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"]) + def test_frame_append_datetime64_col_other_units(self, unit): n = 100 - units = ["h", "m", "s", "ms", "D", "M", "Y"] - ns_dtype = np.dtype("M8[ns]") - for unit in units: - dtype = np.dtype(f"M8[{unit}]") - vals = np.arange(n, dtype=np.int64).view(dtype) + dtype = np.dtype(f"M8[{unit}]") + vals = np.arange(n, dtype=np.int64).view(dtype) - df = DataFrame({"ints": np.arange(n)}, index=np.arange(n)) - df[unit] = vals + df = DataFrame({"ints": np.arange(n)}, index=np.arange(n)) + df[unit] = vals - ex_vals = to_datetime(vals.astype("O")).values + ex_vals = to_datetime(vals.astype("O")).values - assert df[unit].dtype == ns_dtype - assert (df[unit].values == ex_vals).all() + assert df[unit].dtype == ns_dtype + assert (df[unit].values == ex_vals).all() + @pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"]) + def test_frame_setitem_existing_datetime64_col_other_units(self, unit): # Test insertion into existing datetime64 column + n = 100 + ns_dtype = np.dtype("M8[ns]") + df = DataFrame({"ints": np.arange(n)}, index=np.arange(n)) df["dates"] = np.arange(n, dtype=np.int64).view(ns_dtype) - for unit in units: - dtype = np.dtype(f"M8[{unit}]") - vals = np.arange(n, dtype=np.int64).view(dtype) + dtype = np.dtype(f"M8[{unit}]") + vals = np.arange(n, dtype=np.int64).view(dtype) - tmp = df.copy() + tmp = df.copy() - tmp["dates"] = vals - ex_vals = to_datetime(vals.astype("O")).values + tmp["dates"] = vals + ex_vals = to_datetime(vals.astype("O")).values - assert (tmp["dates"].values == ex_vals).all() + assert (tmp["dates"].values == ex_vals).all() def test_datetime_assignment_with_NaT_and_diff_time_units(self): # GH 7492 diff --git a/pandas/tests/frame/test_timezones.py b/pandas/tests/frame/test_timezones.py index bb4e7a157f53e..3d814f22ce262 100644 --- a/pandas/tests/frame/test_timezones.py +++ b/pandas/tests/frame/test_timezones.py @@ -6,34 +6,12 @@ from pandas.core.dtypes.dtypes import DatetimeTZDtype -import pandas as pd from pandas import DataFrame, Series import pandas._testing as tm from pandas.core.indexes.datetimes import date_range class TestDataFrameTimezones: - def test_frame_join_tzaware(self): - test1 = DataFrame( - np.zeros((6, 3)), - index=date_range( - "2012-11-15 00:00:00", periods=6, freq="100L", tz="US/Central" - ), - ) - test2 = DataFrame( - np.zeros((3, 3)), - index=date_range( - "2012-11-15 00:00:00", periods=3, freq="250L", tz="US/Central" - ), - columns=range(3, 6), - ) - - result = test1.join(test2, how="outer") - ex_index = test1.index.union(test2.index) - - tm.assert_index_equal(result.index, ex_index) - assert result.index.tz.zone == "US/Central" - @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"]) def test_frame_no_datetime64_dtype(self, tz): # after GH#7822 @@ -95,10 +73,3 @@ def test_tz_localize_convert_copy_inplace_mutate(self, copy, method, tz): np.arange(0, 5), index=date_range("20131027", periods=5, freq="1H", tz=tz) ) tm.assert_frame_equal(result, expected) - - def test_constructor_data_aware_dtype_naive(self, tz_aware_fixture): - # GH 25843 - tz = tz_aware_fixture - result = DataFrame({"d": [pd.Timestamp("2019", tz=tz)]}, dtype="datetime64[ns]") - expected = DataFrame({"d": [pd.Timestamp("2019")]}) - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/indexes/categorical/test_map.py b/pandas/tests/indexes/categorical/test_map.py index 55e050ebdb2d8..1a326c1acea46 100644 --- a/pandas/tests/indexes/categorical/test_map.py +++ b/pandas/tests/indexes/categorical/test_map.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -from pandas import CategoricalIndex, Index +from pandas import CategoricalIndex, Index, Series import pandas._testing as tm @@ -56,7 +56,7 @@ def f(x): ) tm.assert_index_equal(result, exp) - result = ci.map(pd.Series([10, 20, 30], index=["A", "B", "C"])) + result = ci.map(Series([10, 20, 30], index=["A", "B", "C"])) tm.assert_index_equal(result, exp) result = ci.map({"A": 10, "B": 20, "C": 30}) @@ -65,8 +65,8 @@ def f(x): def test_map_with_categorical_series(self): # GH 12756 a = Index([1, 2, 3, 4]) - b = pd.Series(["even", "odd", "even", "odd"], dtype="category") - c = pd.Series(["even", "odd", "even", "odd"]) + b = Series(["even", "odd", "even", "odd"], dtype="category") + c = Series(["even", "odd", "even", "odd"]) exp = CategoricalIndex(["odd", "even", "odd", np.nan]) tm.assert_index_equal(a.map(b), exp) @@ -80,8 +80,8 @@ def test_map_with_categorical_series(self): ([1, 2, np.nan], pd.isna), ([1, 1, np.nan], {1: False}), ([1, 2, np.nan], {1: False, 2: False}), - ([1, 1, np.nan], pd.Series([False, False])), - ([1, 2, np.nan], pd.Series([False, False, False])), + ([1, 1, np.nan], Series([False, False])), + ([1, 2, np.nan], Series([False, False, False])), ), ) def test_map_with_nan(self, data, f): # GH 24241 @@ -93,3 +93,19 @@ def test_map_with_nan(self, data, f): # GH 24241 else: expected = Index([False, False, np.nan]) tm.assert_index_equal(result, expected) + + def test_map_with_dict_or_series(self): + orig_values = ["a", "B", 1, "a"] + new_values = ["one", 2, 3.0, "one"] + cur_index = CategoricalIndex(orig_values, name="XXX") + expected = CategoricalIndex(new_values, name="XXX", categories=[3.0, 2, "one"]) + + mapper = Series(new_values[:-1], index=orig_values[:-1]) + result = cur_index.map(mapper) + # Order of categories in result can be different + tm.assert_index_equal(result, expected) + + mapper = {o: n for o, n in zip(orig_values[:-1], new_values[:-1])} + result = cur_index.map(mapper) + # Order of categories in result can be different + tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexing/test_categorical.py b/pandas/tests/indexing/test_categorical.py index 9b52c297ec688..854ca176fd2f4 100644 --- a/pandas/tests/indexing/test_categorical.py +++ b/pandas/tests/indexing/test_categorical.py @@ -25,27 +25,15 @@ def setup_method(self, method): self.df = DataFrame( { "A": np.arange(6, dtype="int64"), - "B": Series(list("aabbca")).astype(CDT(list("cab"))), - } - ).set_index("B") + }, + index=CategoricalIndex(list("aabbca"), dtype=CDT(list("cab")), name="B"), + ) self.df2 = DataFrame( { "A": np.arange(6, dtype="int64"), - "B": Series(list("aabbca")).astype(CDT(list("cabe"))), - } - ).set_index("B") - self.df3 = DataFrame( - { - "A": np.arange(6, dtype="int64"), - "B": (Series([1, 1, 2, 1, 3, 2]).astype(CDT([3, 2, 1], ordered=True))), - } - ).set_index("B") - self.df4 = DataFrame( - { - "A": np.arange(6, dtype="int64"), - "B": (Series([1, 1, 2, 1, 3, 2]).astype(CDT([3, 2, 1], ordered=False))), - } - ).set_index("B") + }, + index=CategoricalIndex(list("aabbca"), dtype=CDT(list("cabe")), name="B"), + ) def test_loc_scalar(self): result = self.df.loc["a"] @@ -446,22 +434,6 @@ def test_getitem_with_listlike(self): result = dummies[list(dummies.columns)] tm.assert_frame_equal(result, expected) - def test_setitem_listlike(self): - - # GH 9469 - # properly coerce the input indexers - np.random.seed(1) - c = Categorical( - np.random.randint(0, 5, size=150000).astype(np.int8) - ).add_categories([-1000]) - indexer = np.array([100000]).astype(np.int64) - c[indexer] = -1000 - - # we are asserting the code result here - # which maps to the -1000 category - result = c.codes[np.array([100000]).astype(np.int64)] - tm.assert_numpy_array_equal(result, np.array([5], dtype="int8")) - def test_ix_categorical_index(self): # GH 12531 df = DataFrame(np.random.randn(3, 3), index=list("ABC"), columns=list("XYZ")) @@ -530,91 +502,6 @@ def test_read_only_source(self): tm.assert_series_equal(rw_df.loc[1], ro_df.loc[1]) tm.assert_frame_equal(rw_df.loc[1:3], ro_df.loc[1:3]) - def test_reindexing(self): - df = DataFrame( - { - "A": np.arange(3, dtype="int64"), - "B": Series(list("abc")).astype(CDT(list("cabe"))), - } - ).set_index("B") - - # reindexing - # convert to a regular index - result = df.reindex(["a", "b", "e"]) - expected = DataFrame({"A": [0, 1, np.nan], "B": Series(list("abe"))}).set_index( - "B" - ) - tm.assert_frame_equal(result, expected, check_index_type=True) - - result = df.reindex(["a", "b"]) - expected = DataFrame({"A": [0, 1], "B": Series(list("ab"))}).set_index("B") - tm.assert_frame_equal(result, expected, check_index_type=True) - - result = df.reindex(["e"]) - expected = DataFrame({"A": [np.nan], "B": Series(["e"])}).set_index("B") - tm.assert_frame_equal(result, expected, check_index_type=True) - - result = df.reindex(["d"]) - expected = DataFrame({"A": [np.nan], "B": Series(["d"])}).set_index("B") - tm.assert_frame_equal(result, expected, check_index_type=True) - - # since we are actually reindexing with a Categorical - # then return a Categorical - cats = list("cabe") - - result = df.reindex(Categorical(["a", "e"], categories=cats)) - expected = DataFrame( - {"A": [0, np.nan], "B": Series(list("ae")).astype(CDT(cats))} - ).set_index("B") - tm.assert_frame_equal(result, expected, check_index_type=True) - - result = df.reindex(Categorical(["a"], categories=cats)) - expected = DataFrame( - {"A": [0], "B": Series(list("a")).astype(CDT(cats))} - ).set_index("B") - tm.assert_frame_equal(result, expected, check_index_type=True) - - result = df.reindex(["a", "b", "e"]) - expected = DataFrame({"A": [0, 1, np.nan], "B": Series(list("abe"))}).set_index( - "B" - ) - tm.assert_frame_equal(result, expected, check_index_type=True) - - result = df.reindex(["a", "b"]) - expected = DataFrame({"A": [0, 1], "B": Series(list("ab"))}).set_index("B") - tm.assert_frame_equal(result, expected, check_index_type=True) - - result = df.reindex(["e"]) - expected = DataFrame({"A": [np.nan], "B": Series(["e"])}).set_index("B") - tm.assert_frame_equal(result, expected, check_index_type=True) - - # give back the type of categorical that we received - result = df.reindex(Categorical(["a", "e"], categories=cats, ordered=True)) - expected = DataFrame( - {"A": [0, np.nan], "B": Series(list("ae")).astype(CDT(cats, ordered=True))} - ).set_index("B") - tm.assert_frame_equal(result, expected, check_index_type=True) - - result = df.reindex(Categorical(["a", "d"], categories=["a", "d"])) - expected = DataFrame( - {"A": [0, np.nan], "B": Series(list("ad")).astype(CDT(["a", "d"]))} - ).set_index("B") - tm.assert_frame_equal(result, expected, check_index_type=True) - - # passed duplicate indexers are not allowed - msg = "cannot reindex from a duplicate axis" - with pytest.raises(ValueError, match=msg): - self.df2.reindex(["a", "b"]) - - # args NotImplemented ATM - msg = r"argument {} is not implemented for CategoricalIndex\.reindex" - with pytest.raises(NotImplementedError, match=msg.format("method")): - df.reindex(["a"], method="ffill") - with pytest.raises(NotImplementedError, match=msg.format("level")): - df.reindex(["a"], level=1) - with pytest.raises(NotImplementedError, match=msg.format("limit")): - df.reindex(["a"], limit=2) - def test_loc_slice(self): # GH9748 with pytest.raises(KeyError, match="1"): @@ -635,10 +522,24 @@ def test_loc_and_at_with_categorical_index(self): assert df.loc["B", 1] == 4 assert df.at["B", 1] == 4 - def test_boolean_selection(self): + def test_getitem_bool_mask_categorical_index(self): - df3 = self.df3 - df4 = self.df4 + df3 = DataFrame( + { + "A": np.arange(6, dtype="int64"), + }, + index=CategoricalIndex( + [1, 1, 2, 1, 3, 2], dtype=CDT([3, 2, 1], ordered=True), name="B" + ), + ) + df4 = DataFrame( + { + "A": np.arange(6, dtype="int64"), + }, + index=CategoricalIndex( + [1, 1, 2, 1, 3, 2], dtype=CDT([3, 2, 1], ordered=False), name="B" + ), + ) result = df3[df3.index == "a"] expected = df3.iloc[[]] @@ -699,24 +600,6 @@ def test_indexing_with_category(self): res = cat[["A"]] == "foo" tm.assert_frame_equal(res, exp) - def test_map_with_dict_or_series(self): - orig_values = ["a", "B", 1, "a"] - new_values = ["one", 2, 3.0, "one"] - cur_index = pd.CategoricalIndex(orig_values, name="XXX") - expected = pd.CategoricalIndex( - new_values, name="XXX", categories=[3.0, 2, "one"] - ) - - mapper = Series(new_values[:-1], index=orig_values[:-1]) - output = cur_index.map(mapper) - # Order of categories in output can be different - tm.assert_index_equal(expected, output) - - mapper = {o: n for o, n in zip(orig_values[:-1], new_values[:-1])} - output = cur_index.map(mapper) - # Order of categories in output can be different - tm.assert_index_equal(expected, output) - @pytest.mark.parametrize( "idx_values", [ @@ -781,31 +664,3 @@ def test_loc_with_non_string_categories(self, idx_values, ordered): result.loc[sl, "A"] = ["qux", "qux2"] expected = DataFrame({"A": ["qux", "qux2", "baz"]}, index=cat_idx) tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( - "categories", - [ - pytest.param(["a", "b", "c"], id="str"), - pytest.param( - [pd.Interval(0, 1), pd.Interval(1, 2), pd.Interval(2, 3)], - id="pd.Interval", - ), - ], - ) - def test_reorder_index_with_categories(self, categories): - # GH23452 - df = DataFrame( - {"foo": range(len(categories))}, - index=CategoricalIndex( - data=categories, categories=categories, ordered=True - ), - ) - df.index = df.index.reorder_categories(df.index.categories[::-1]) - result = df.sort_index() - expected = DataFrame( - {"foo": reversed(range(len(categories)))}, - index=CategoricalIndex( - data=categories[::-1], categories=categories[::-1], ordered=True - ), - ) - tm.assert_frame_equal(result, expected)
https://api.github.com/repos/pandas-dev/pandas/pulls/37403
2020-10-25T18:11:28Z
2020-10-26T12:10:55Z
2020-10-26T12:10:55Z
2020-10-26T15:08:26Z
TST: check_comprehensiveness compat for --lf and -k
diff --git a/pandas/tests/indexing/test_coercion.py b/pandas/tests/indexing/test_coercion.py index d37b5986b57c1..436b2aa838b08 100644 --- a/pandas/tests/indexing/test_coercion.py +++ b/pandas/tests/indexing/test_coercion.py @@ -29,11 +29,21 @@ def has_test(combo): klass in x.name and dtype in x.name and method in x.name for x in cls_funcs ) - for combo in combos: - if not has_test(combo): - raise AssertionError(f"test method is not defined: {cls.__name__}, {combo}") + opts = request.config.option + if opts.lf or opts.keyword: + # If we are running with "last-failed" or -k foo, we expect to only + # run a subset of tests. + yield - yield + else: + + for combo in combos: + if not has_test(combo): + raise AssertionError( + f"test method is not defined: {cls.__name__}, {combo}" + ) + + yield class CoercionBase:
- [x] closes #23930 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37402
2020-10-25T16:02:28Z
2020-10-29T00:58:49Z
2020-10-29T00:58:48Z
2020-10-29T02:01:57Z
CI/CLN: Lint more class references in tests
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index a9cce9357b531..7c48905135f89 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -38,8 +38,8 @@ function invgrep { } function check_namespace { - local -r CLASS="${1}" - grep -R -l --include "*.py" " ${CLASS}(" pandas/tests | xargs grep -n "pd\.${CLASS}(" + local -r CLASS=${1} + grep -R -l --include "*.py" " ${CLASS}(" pandas/tests | xargs grep -n "pd\.${CLASS}[(\.]" test $? -gt 0 } @@ -146,7 +146,7 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then RET=$(($RET + $?)) ; echo $MSG "DONE" MSG='Check for inconsistent use of pandas namespace in tests' ; echo $MSG - for class in "Series" "DataFrame" "Index"; do + for class in "Series" "DataFrame" "Index" "MultiIndex" "Timestamp" "Timedelta" "TimedeltaIndex" "DatetimeIndex" "Categorical"; do check_namespace ${class} RET=$(($RET + $?)) done diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index f9dd4a7445a99..cefd2ae7a9ddb 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -115,7 +115,7 @@ def test_dt64arr_cmp_mixed_invalid(self, tz_naive_fixture): dta = date_range("1970-01-01", freq="h", periods=5, tz=tz)._data - other = np.array([0, 1, 2, dta[3], pd.Timedelta(days=1)]) + other = np.array([0, 1, 2, dta[3], Timedelta(days=1)]) result = dta == other expected = np.array([False, False, False, True, False]) tm.assert_numpy_array_equal(result, expected) @@ -139,7 +139,7 @@ def test_dt64arr_nat_comparison(self, tz_naive_fixture, box_with_array): box = box_with_array xbox = box if box not in [pd.Index, pd.array] else np.ndarray - ts = pd.Timestamp.now(tz) + ts = Timestamp.now(tz) ser = Series([ts, pd.NaT]) obj = tm.box_expected(ser, box) @@ -158,12 +158,12 @@ class TestDatetime64SeriesComparison: "pair", [ ( - [pd.Timestamp("2011-01-01"), NaT, pd.Timestamp("2011-01-03")], - [NaT, NaT, pd.Timestamp("2011-01-03")], + [Timestamp("2011-01-01"), NaT, Timestamp("2011-01-03")], + [NaT, NaT, Timestamp("2011-01-03")], ), ( - [pd.Timedelta("1 days"), NaT, pd.Timedelta("3 days")], - [NaT, NaT, pd.Timedelta("3 days")], + [Timedelta("1 days"), NaT, Timedelta("3 days")], + [NaT, NaT, Timedelta("3 days")], ), ( [pd.Period("2011-01", freq="M"), NaT, pd.Period("2011-03", freq="M")], @@ -281,30 +281,30 @@ def test_timestamp_compare_series(self, left, right): ser = Series(pd.date_range("20010101", periods=10), name="dates") s_nat = ser.copy(deep=True) - ser[0] = pd.Timestamp("nat") - ser[3] = pd.Timestamp("nat") + ser[0] = Timestamp("nat") + ser[3] = Timestamp("nat") left_f = getattr(operator, left) right_f = getattr(operator, right) # No NaT - expected = left_f(ser, pd.Timestamp("20010109")) - result = right_f(pd.Timestamp("20010109"), ser) + expected = left_f(ser, Timestamp("20010109")) + result = right_f(Timestamp("20010109"), ser) tm.assert_series_equal(result, expected) # NaT - expected = left_f(ser, pd.Timestamp("nat")) - result = right_f(pd.Timestamp("nat"), ser) + expected = left_f(ser, Timestamp("nat")) + result = right_f(Timestamp("nat"), ser) tm.assert_series_equal(result, expected) # Compare to Timestamp with series containing NaT - expected = left_f(s_nat, pd.Timestamp("20010109")) - result = right_f(pd.Timestamp("20010109"), s_nat) + expected = left_f(s_nat, Timestamp("20010109")) + result = right_f(Timestamp("20010109"), s_nat) tm.assert_series_equal(result, expected) # Compare to NaT with series containing NaT - expected = left_f(s_nat, pd.Timestamp("nat")) - result = right_f(pd.Timestamp("nat"), s_nat) + expected = left_f(s_nat, Timestamp("nat")) + result = right_f(Timestamp("nat"), s_nat) tm.assert_series_equal(result, expected) def test_dt64arr_timestamp_equality(self, box_with_array): @@ -313,7 +313,7 @@ def test_dt64arr_timestamp_equality(self, box_with_array): box_with_array if box_with_array not in [pd.Index, pd.array] else np.ndarray ) - ser = Series([pd.Timestamp("2000-01-29 01:59:00"), "NaT"]) + ser = Series([Timestamp("2000-01-29 01:59:00"), "NaT"]) ser = tm.box_expected(ser, box_with_array) result = ser != ser @@ -413,10 +413,8 @@ def test_dti_cmp_nat(self, dtype, box_with_array): box_with_array if box_with_array not in [pd.Index, pd.array] else np.ndarray ) - left = pd.DatetimeIndex( - [pd.Timestamp("2011-01-01"), pd.NaT, pd.Timestamp("2011-01-03")] - ) - right = pd.DatetimeIndex([pd.NaT, pd.NaT, pd.Timestamp("2011-01-03")]) + left = DatetimeIndex([Timestamp("2011-01-01"), pd.NaT, Timestamp("2011-01-03")]) + right = DatetimeIndex([pd.NaT, pd.NaT, Timestamp("2011-01-03")]) left = tm.box_expected(left, box_with_array) right = tm.box_expected(right, box_with_array) @@ -454,10 +452,10 @@ def test_dti_cmp_nat_behaves_like_float_cmp_nan(self): fidx1 = pd.Index([1.0, np.nan, 3.0, np.nan, 5.0, 7.0]) fidx2 = pd.Index([2.0, 3.0, np.nan, np.nan, 6.0, 7.0]) - didx1 = pd.DatetimeIndex( + didx1 = DatetimeIndex( ["2014-01-01", pd.NaT, "2014-03-01", pd.NaT, "2014-05-01", "2014-07-01"] ) - didx2 = pd.DatetimeIndex( + didx2 = DatetimeIndex( ["2014-02-01", "2014-03-01", pd.NaT, pd.NaT, "2014-06-01", "2014-07-01"] ) darr = np.array( @@ -611,8 +609,8 @@ def test_comparison_tzawareness_compat_scalars(self, op, box_with_array): dz = tm.box_expected(dz, box_with_array) # Check comparisons against scalar Timestamps - ts = pd.Timestamp("2000-03-14 01:59") - ts_tz = pd.Timestamp("2000-03-14 01:59", tz="Europe/Amsterdam") + ts = Timestamp("2000-03-14 01:59") + ts_tz = Timestamp("2000-03-14 01:59", tz="Europe/Amsterdam") assert np.all(dr > ts) msg = r"Invalid comparison between dtype=datetime64\[ns.*\] and Timestamp" @@ -679,7 +677,7 @@ def test_scalar_comparison_tzawareness( def test_nat_comparison_tzawareness(self, op): # GH#19276 # tzaware DatetimeIndex should not raise when compared to NaT - dti = pd.DatetimeIndex( + dti = DatetimeIndex( ["2014-01-01", pd.NaT, "2014-03-01", pd.NaT, "2014-05-01", "2014-07-01"] ) expected = np.array([op == operator.ne] * len(dti)) @@ -885,7 +883,7 @@ def test_dt64arr_add_sub_td64_nat(self, box_with_array, tz_naive_fixture): dti = pd.date_range("1994-04-01", periods=9, tz=tz, freq="QS") other = np.timedelta64("NaT") - expected = pd.DatetimeIndex(["NaT"] * 9, tz=tz) + expected = DatetimeIndex(["NaT"] * 9, tz=tz) obj = tm.box_expected(dti, box_with_array) expected = tm.box_expected(expected, box_with_array) @@ -904,7 +902,7 @@ def test_dt64arr_add_sub_td64ndarray(self, tz_naive_fixture, box_with_array): tz = tz_naive_fixture dti = pd.date_range("2016-01-01", periods=3, tz=tz) - tdi = pd.TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"]) + tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"]) tdarr = tdi.values expected = pd.date_range("2015-12-31", "2016-01-02", periods=3, tz=tz) @@ -932,9 +930,9 @@ def test_dt64arr_add_sub_td64ndarray(self, tz_naive_fixture, box_with_array): @pytest.mark.parametrize( "ts", [ - pd.Timestamp("2013-01-01"), - pd.Timestamp("2013-01-01").to_pydatetime(), - pd.Timestamp("2013-01-01").to_datetime64(), + Timestamp("2013-01-01"), + Timestamp("2013-01-01").to_pydatetime(), + Timestamp("2013-01-01").to_datetime64(), ], ) def test_dt64arr_sub_dtscalar(self, box_with_array, ts): @@ -942,7 +940,7 @@ def test_dt64arr_sub_dtscalar(self, box_with_array, ts): idx = pd.date_range("2013-01-01", periods=3)._with_freq(None) idx = tm.box_expected(idx, box_with_array) - expected = pd.TimedeltaIndex(["0 Days", "1 Day", "2 Days"]) + expected = TimedeltaIndex(["0 Days", "1 Day", "2 Days"]) expected = tm.box_expected(expected, box_with_array) result = idx - ts @@ -957,7 +955,7 @@ def test_dt64arr_sub_datetime64_not_ns(self, box_with_array): dti = pd.date_range("20130101", periods=3)._with_freq(None) dtarr = tm.box_expected(dti, box_with_array) - expected = pd.TimedeltaIndex(["0 Days", "1 Day", "2 Days"]) + expected = TimedeltaIndex(["0 Days", "1 Day", "2 Days"]) expected = tm.box_expected(expected, box_with_array) result = dtarr - dt64 @@ -981,7 +979,7 @@ def test_dt64arr_sub_timestamp(self, box_with_array): def test_dt64arr_sub_NaT(self, box_with_array): # GH#18808 - dti = pd.DatetimeIndex([pd.NaT, pd.Timestamp("19900315")]) + dti = DatetimeIndex([pd.NaT, Timestamp("19900315")]) ser = tm.box_expected(dti, box_with_array) result = ser - pd.NaT @@ -1102,7 +1100,7 @@ def test_dt64arr_add_sub_parr( self, dti_freq, pi_freq, box_with_array, box_with_array2 ): # GH#20049 subtracting PeriodIndex should raise TypeError - dti = pd.DatetimeIndex(["2011-01-01", "2011-01-02"], freq=dti_freq) + dti = DatetimeIndex(["2011-01-01", "2011-01-02"], freq=dti_freq) pi = dti.to_period(pi_freq) dtarr = tm.box_expected(dti, box_with_array) @@ -1579,7 +1577,7 @@ def test_dti_add_sub_nonzero_mth_offset( mth = getattr(date, op) result = mth(offset) - expected = pd.DatetimeIndex(exp, tz=tz) + expected = DatetimeIndex(exp, tz=tz) expected = tm.box_expected(expected, box_with_array, False) tm.assert_equal(result, expected) @@ -1603,8 +1601,8 @@ def test_dt64_overflow_masking(self, box_with_array): def test_dt64_series_arith_overflow(self): # GH#12534, fixed by GH#19024 - dt = pd.Timestamp("1700-01-31") - td = pd.Timedelta("20000 Days") + dt = Timestamp("1700-01-31") + td = Timedelta("20000 Days") dti = pd.date_range("1949-09-30", freq="100Y", periods=4) ser = Series(dti) msg = "Overflow in int64 addition" @@ -1634,8 +1632,8 @@ def test_dt64_series_arith_overflow(self): tm.assert_series_equal(res, -expected) def test_datetimeindex_sub_timestamp_overflow(self): - dtimax = pd.to_datetime(["now", pd.Timestamp.max]) - dtimin = pd.to_datetime(["now", pd.Timestamp.min]) + dtimax = pd.to_datetime(["now", Timestamp.max]) + dtimin = pd.to_datetime(["now", Timestamp.min]) tsneg = Timestamp("1950-01-01") ts_neg_variants = [ @@ -1657,12 +1655,12 @@ def test_datetimeindex_sub_timestamp_overflow(self): with pytest.raises(OverflowError, match=msg): dtimax - variant - expected = pd.Timestamp.max.value - tspos.value + expected = Timestamp.max.value - tspos.value for variant in ts_pos_variants: res = dtimax - variant assert res[1].value == expected - expected = pd.Timestamp.min.value - tsneg.value + expected = Timestamp.min.value - tsneg.value for variant in ts_neg_variants: res = dtimin - variant assert res[1].value == expected @@ -1673,18 +1671,18 @@ def test_datetimeindex_sub_timestamp_overflow(self): def test_datetimeindex_sub_datetimeindex_overflow(self): # GH#22492, GH#22508 - dtimax = pd.to_datetime(["now", pd.Timestamp.max]) - dtimin = pd.to_datetime(["now", pd.Timestamp.min]) + dtimax = pd.to_datetime(["now", Timestamp.max]) + dtimin = pd.to_datetime(["now", Timestamp.min]) ts_neg = pd.to_datetime(["1950-01-01", "1950-01-01"]) ts_pos = pd.to_datetime(["1980-01-01", "1980-01-01"]) # General tests - expected = pd.Timestamp.max.value - ts_pos[1].value + expected = Timestamp.max.value - ts_pos[1].value result = dtimax - ts_pos assert result[1].value == expected - expected = pd.Timestamp.min.value - ts_neg[1].value + expected = Timestamp.min.value - ts_neg[1].value result = dtimin - ts_neg assert result[1].value == expected msg = "Overflow in int64 addition" @@ -1695,13 +1693,13 @@ def test_datetimeindex_sub_datetimeindex_overflow(self): dtimin - ts_pos # Edge cases - tmin = pd.to_datetime([pd.Timestamp.min]) - t1 = tmin + pd.Timedelta.max + pd.Timedelta("1us") + tmin = pd.to_datetime([Timestamp.min]) + t1 = tmin + Timedelta.max + Timedelta("1us") with pytest.raises(OverflowError, match=msg): t1 - tmin - tmax = pd.to_datetime([pd.Timestamp.max]) - t2 = tmax + pd.Timedelta.min - pd.Timedelta("1us") + tmax = pd.to_datetime([Timestamp.max]) + t2 = tmax + Timedelta.min - Timedelta("1us") with pytest.raises(OverflowError, match=msg): tmax - t2 @@ -1727,17 +1725,17 @@ def test_operators_datetimelike(self): # ## datetime64 ### dt1 = Series( [ - pd.Timestamp("20111230"), - pd.Timestamp("20120101"), - pd.Timestamp("20120103"), + Timestamp("20111230"), + Timestamp("20120101"), + Timestamp("20120103"), ] ) dt1.iloc[2] = np.nan dt2 = Series( [ - pd.Timestamp("20111231"), - pd.Timestamp("20120102"), - pd.Timestamp("20120104"), + Timestamp("20111231"), + Timestamp("20120102"), + Timestamp("20120104"), ] ) dt1 - dt2 @@ -1815,8 +1813,8 @@ def check(get_ser, test_ser): def test_sub_single_tz(self): # GH#12290 - s1 = Series([pd.Timestamp("2016-02-10", tz="America/Sao_Paulo")]) - s2 = Series([pd.Timestamp("2016-02-08", tz="America/Sao_Paulo")]) + s1 = Series([Timestamp("2016-02-10", tz="America/Sao_Paulo")]) + s2 = Series([Timestamp("2016-02-08", tz="America/Sao_Paulo")]) result = s1 - s2 expected = Series([Timedelta("2days")]) tm.assert_series_equal(result, expected) @@ -1829,7 +1827,7 @@ def test_dt64tz_series_sub_dtitz(self): # (with same tz) raises, fixed by #19024 dti = pd.date_range("1999-09-30", periods=10, tz="US/Pacific") ser = Series(dti) - expected = Series(pd.TimedeltaIndex(["0days"] * 10)) + expected = Series(TimedeltaIndex(["0days"] * 10)) res = dti - ser tm.assert_series_equal(res, expected) @@ -1928,7 +1926,7 @@ def test_dt64_mul_div_numeric_invalid(self, one, dt64_series): def test_dt64_series_add_intlike(self, tz_naive_fixture, op): # GH#19123 tz = tz_naive_fixture - dti = pd.DatetimeIndex(["2016-01-02", "2016-02-03", "NaT"], tz=tz) + dti = DatetimeIndex(["2016-01-02", "2016-02-03", "NaT"], tz=tz) ser = Series(dti) other = Series([20, 30, 40], dtype="uint8") @@ -2060,7 +2058,7 @@ def test_dti_add_intarray_non_tick(self, int_holder, freq): @pytest.mark.parametrize("int_holder", [np.array, pd.Index]) def test_dti_add_intarray_no_freq(self, int_holder): # GH#19959 - dti = pd.DatetimeIndex(["2016-01-01", "NaT", "2017-04-05 06:07:08"]) + dti = DatetimeIndex(["2016-01-01", "NaT", "2017-04-05 06:07:08"]) other = int_holder([9, 4, -1]) msg = "|".join( ["cannot subtract DatetimeArray from", "Addition/subtraction of integers"] @@ -2450,10 +2448,10 @@ def test_dti_addsub_object_arraylike( dti = pd.date_range("2017-01-01", periods=2, tz=tz) dtarr = tm.box_expected(dti, box_with_array) - other = other_box([pd.offsets.MonthEnd(), pd.Timedelta(days=4)]) + other = other_box([pd.offsets.MonthEnd(), Timedelta(days=4)]) xbox = get_upcast_box(box_with_array, other) - expected = pd.DatetimeIndex(["2017-01-31", "2017-01-06"], tz=tz_naive_fixture) + expected = DatetimeIndex(["2017-01-31", "2017-01-06"], tz=tz_naive_fixture) expected = tm.box_expected(expected, xbox) warn = PerformanceWarning @@ -2464,7 +2462,7 @@ def test_dti_addsub_object_arraylike( result = dtarr + other tm.assert_equal(result, expected) - expected = pd.DatetimeIndex(["2016-12-31", "2016-12-29"], tz=tz_naive_fixture) + expected = DatetimeIndex(["2016-12-31", "2016-12-29"], tz=tz_naive_fixture) expected = tm.box_expected(expected, xbox) with tm.assert_produces_warning(warn): diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py index 1418aec015b92..836b1dcddf0dd 100644 --- a/pandas/tests/arithmetic/test_numeric.py +++ b/pandas/tests/arithmetic/test_numeric.py @@ -135,7 +135,7 @@ def test_mul_td64arr(self, left, box_cls): right = np.array([1, 2, 3], dtype="m8[s]") right = box_cls(right) - expected = pd.TimedeltaIndex(["10s", "40s", "90s"]) + expected = TimedeltaIndex(["10s", "40s", "90s"]) if isinstance(left, Series) or box_cls is Series: expected = Series(expected) @@ -155,7 +155,7 @@ def test_div_td64arr(self, left, box_cls): right = np.array([10, 40, 90], dtype="m8[s]") right = box_cls(right) - expected = pd.TimedeltaIndex(["1s", "2s", "3s"]) + expected = TimedeltaIndex(["1s", "2s", "3s"]) if isinstance(left, Series) or box_cls is Series: expected = Series(expected) @@ -189,7 +189,7 @@ def test_numeric_arr_mul_tdscalar(self, scalar_td, numeric_idx, box_with_array): # GH#19333 box = box_with_array index = numeric_idx - expected = pd.TimedeltaIndex([pd.Timedelta(days=n) for n in range(len(index))]) + expected = TimedeltaIndex([Timedelta(days=n) for n in range(len(index))]) index = tm.box_expected(index, box) expected = tm.box_expected(expected, box) @@ -244,10 +244,10 @@ def test_numeric_arr_rdiv_tdscalar(self, three_days, numeric_idx, box_with_array @pytest.mark.parametrize( "other", [ - pd.Timedelta(hours=31), - pd.Timedelta(hours=31).to_pytimedelta(), - pd.Timedelta(hours=31).to_timedelta64(), - pd.Timedelta(hours=31).to_timedelta64().astype("m8[h]"), + Timedelta(hours=31), + Timedelta(hours=31).to_pytimedelta(), + Timedelta(hours=31).to_timedelta64(), + Timedelta(hours=31).to_timedelta64().astype("m8[h]"), np.timedelta64("NaT"), np.timedelta64("NaT", "D"), pd.offsets.Minute(3), diff --git a/pandas/tests/arithmetic/test_object.py b/pandas/tests/arithmetic/test_object.py index ddd14af0918de..a31c2e6d8c258 100644 --- a/pandas/tests/arithmetic/test_object.py +++ b/pandas/tests/arithmetic/test_object.py @@ -196,8 +196,8 @@ def test_mixed_timezone_series_ops_object(self): # GH#13043 ser = Series( [ - pd.Timestamp("2015-01-01", tz="US/Eastern"), - pd.Timestamp("2015-01-01", tz="Asia/Tokyo"), + Timestamp("2015-01-01", tz="US/Eastern"), + Timestamp("2015-01-01", tz="Asia/Tokyo"), ], name="xxx", ) @@ -205,8 +205,8 @@ def test_mixed_timezone_series_ops_object(self): exp = Series( [ - pd.Timestamp("2015-01-02", tz="US/Eastern"), - pd.Timestamp("2015-01-02", tz="Asia/Tokyo"), + Timestamp("2015-01-02", tz="US/Eastern"), + Timestamp("2015-01-02", tz="Asia/Tokyo"), ], name="xxx", ) @@ -216,8 +216,8 @@ def test_mixed_timezone_series_ops_object(self): # object series & object series ser2 = Series( [ - pd.Timestamp("2015-01-03", tz="US/Eastern"), - pd.Timestamp("2015-01-05", tz="Asia/Tokyo"), + Timestamp("2015-01-03", tz="US/Eastern"), + Timestamp("2015-01-05", tz="Asia/Tokyo"), ], name="xxx", ) @@ -326,7 +326,7 @@ def test_rsub_object(self): "foo" - index with pytest.raises(TypeError, match=msg): - np.array([True, pd.Timestamp.now()]) - index + np.array([True, Timestamp.now()]) - index class MyIndex(pd.Index): diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index f02259a1c7e62..f9fcee889ec96 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -10,7 +10,7 @@ from pandas.errors import PerformanceWarning import pandas as pd -from pandas import PeriodIndex, Series, TimedeltaIndex, period_range +from pandas import PeriodIndex, Series, Timedelta, TimedeltaIndex, period_range import pandas._testing as tm from pandas.core import ops from pandas.core.arrays import TimedeltaArray @@ -41,9 +41,7 @@ def test_compare_zerodim(self, box_with_array): expected = tm.box_expected(expected, xbox) tm.assert_equal(result, expected) - @pytest.mark.parametrize( - "scalar", ["foo", pd.Timestamp.now(), pd.Timedelta(days=4)] - ) + @pytest.mark.parametrize("scalar", ["foo", Timestamp.now(), Timedelta(days=4)]) def test_compare_invalid_scalar(self, box_with_array, scalar): # comparison with scalar that cannot be interpreted as a Period pi = pd.period_range("2000", periods=4) @@ -698,9 +696,9 @@ def test_parr_add_sub_float_raises(self, op, other, box_with_array): "other", [ # datetime scalars - pd.Timestamp.now(), - pd.Timestamp.now().to_pydatetime(), - pd.Timestamp.now().to_datetime64(), + Timestamp.now(), + Timestamp.now().to_pydatetime(), + Timestamp.now().to_datetime64(), # datetime-like arrays pd.date_range("2016-01-01", periods=3, freq="H"), pd.date_range("2016-01-01", periods=3, tz="Europe/Brussels"), @@ -733,7 +731,7 @@ def test_parr_add_sub_invalid(self, other, box_with_array): def test_pi_add_sub_td64_array_non_tick_raises(self): rng = pd.period_range("1/1/2000", freq="Q", periods=3) - tdi = pd.TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"]) + tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"]) tdarr = tdi.values msg = r"Cannot add or subtract timedelta64\[ns\] dtype from period\[Q-DEC\]" @@ -752,7 +750,7 @@ def test_pi_add_sub_td64_array_tick(self): # PeriodIndex + Timedelta-like is allowed only with # tick-like frequencies rng = pd.period_range("1/1/2000", freq="90D", periods=3) - tdi = pd.TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"]) + tdi = TimedeltaIndex(["-1 Day", "-1 Day", "-1 Day"]) tdarr = tdi.values expected = pd.period_range("12/31/1999", freq="90D", periods=3) @@ -1227,7 +1225,7 @@ def test_parr_add_sub_object_array(self): pi = pd.period_range("2000-12-31", periods=3, freq="D") parr = pi.array - other = np.array([pd.Timedelta(days=1), pd.offsets.Day(2), 3]) + other = np.array([Timedelta(days=1), pd.offsets.Day(2), 3]) with tm.assert_produces_warning(PerformanceWarning): result = parr + other @@ -1258,10 +1256,10 @@ def test_ops_series_timedelta(self): name="xxx", ) - result = ser + pd.Timedelta("1 days") + result = ser + Timedelta("1 days") tm.assert_series_equal(result, expected) - result = pd.Timedelta("1 days") + ser + result = Timedelta("1 days") + ser tm.assert_series_equal(result, expected) result = ser + pd.tseries.offsets.Day() @@ -1492,7 +1490,7 @@ def test_pi_sub_period(self): result = np.subtract(pd.Period("2012-01", freq="M"), idx) tm.assert_index_equal(result, exp) - exp = pd.TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx") + exp = TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx") result = idx - pd.Period("NaT", freq="M") tm.assert_index_equal(result, exp) assert result.freq == exp.freq @@ -1506,7 +1504,7 @@ def test_pi_sub_pdnat(self): idx = PeriodIndex( ["2011-01", "2011-02", "NaT", "2011-04"], freq="M", name="idx" ) - exp = pd.TimedeltaIndex([pd.NaT] * 4, name="idx") + exp = TimedeltaIndex([pd.NaT] * 4, name="idx") tm.assert_index_equal(pd.NaT - idx, exp) tm.assert_index_equal(idx - pd.NaT, exp) @@ -1525,7 +1523,7 @@ def test_pi_sub_period_nat(self): exp = pd.Index([12 * off, pd.NaT, 10 * off, 9 * off], name="idx") tm.assert_index_equal(result, exp) - exp = pd.TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx") + exp = TimedeltaIndex([np.nan, np.nan, np.nan, np.nan], name="idx") tm.assert_index_equal(idx - pd.Period("NaT", freq="M"), exp) tm.assert_index_equal(pd.Period("NaT", freq="M") - idx, exp) diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 5f556718ea0d3..31c7a17fd9ef5 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -119,7 +119,7 @@ def test_td64arr_cmp_arraylike_invalid(self, other): def test_td64arr_cmp_mixed_invalid(self): rng = timedelta_range("1 days", periods=5)._data - other = np.array([0, 1, 2, rng[3], pd.Timestamp.now()]) + other = np.array([0, 1, 2, rng[3], Timestamp.now()]) result = rng == other expected = np.array([False, False, False, True, False]) tm.assert_numpy_array_equal(result, expected) @@ -143,10 +143,8 @@ class TestTimedelta64ArrayComparisons: @pytest.mark.parametrize("dtype", [None, object]) def test_comp_nat(self, dtype): - left = pd.TimedeltaIndex( - [pd.Timedelta("1 days"), pd.NaT, pd.Timedelta("3 days")] - ) - right = pd.TimedeltaIndex([pd.NaT, pd.NaT, pd.Timedelta("3 days")]) + left = TimedeltaIndex([Timedelta("1 days"), pd.NaT, Timedelta("3 days")]) + right = TimedeltaIndex([pd.NaT, pd.NaT, Timedelta("3 days")]) lhs, rhs = left, right if dtype is object: @@ -173,7 +171,7 @@ def test_comp_nat(self, dtype): tm.assert_numpy_array_equal(pd.NaT > lhs, expected) def test_comparisons_nat(self): - tdidx1 = pd.TimedeltaIndex( + tdidx1 = TimedeltaIndex( [ "1 day", pd.NaT, @@ -183,7 +181,7 @@ def test_comparisons_nat(self): "5 day 00:00:03", ] ) - tdidx2 = pd.TimedeltaIndex( + tdidx2 = TimedeltaIndex( ["2 day", "2 day", pd.NaT, pd.NaT, "1 day 00:00:02", "5 days 00:00:03"] ) tdarr = np.array( @@ -1030,7 +1028,7 @@ def test_tdi_sub_dt64_array(self, box_with_array): dti = pd.date_range("2016-01-01", periods=3) tdi = dti - dti.shift(1) dtarr = dti.values - expected = pd.DatetimeIndex(dtarr) - tdi + expected = DatetimeIndex(dtarr) - tdi tdi = tm.box_expected(tdi, box_with_array) expected = tm.box_expected(expected, box_with_array) @@ -1047,7 +1045,7 @@ def test_tdi_add_dt64_array(self, box_with_array): dti = pd.date_range("2016-01-01", periods=3) tdi = dti - dti.shift(1) dtarr = dti.values - expected = pd.DatetimeIndex(dtarr) + tdi + expected = DatetimeIndex(dtarr) + tdi tdi = tm.box_expected(tdi, box_with_array) expected = tm.box_expected(expected, box_with_array) @@ -1062,7 +1060,7 @@ def test_td64arr_add_datetime64_nat(self, box_with_array): other = np.datetime64("NaT") tdi = timedelta_range("1 day", periods=3) - expected = pd.DatetimeIndex(["NaT", "NaT", "NaT"]) + expected = DatetimeIndex(["NaT", "NaT", "NaT"]) tdser = tm.box_expected(tdi, box_with_array) expected = tm.box_expected(expected, box_with_array) @@ -1246,9 +1244,9 @@ def test_td64arr_add_sub_tdi(self, box_with_array, names): def test_td64arr_add_sub_td64_nat(self, box_with_array): # GH#23320 special handling for timedelta64("NaT") box = box_with_array - tdi = pd.TimedeltaIndex([NaT, Timedelta("1s")]) + tdi = TimedeltaIndex([NaT, Timedelta("1s")]) other = np.timedelta64("NaT") - expected = pd.TimedeltaIndex(["NaT"] * 2) + expected = TimedeltaIndex(["NaT"] * 2) obj = tm.box_expected(tdi, box) expected = tm.box_expected(expected, box) @@ -1472,14 +1470,14 @@ def test_td64arr_add_sub_object_array(self, box_with_array): tdarr = tm.box_expected(tdi, box) other = np.array( - [pd.Timedelta(days=1), pd.offsets.Day(2), pd.Timestamp("2000-01-04")] + [Timedelta(days=1), pd.offsets.Day(2), Timestamp("2000-01-04")] ) with tm.assert_produces_warning(PerformanceWarning): result = tdarr + other expected = pd.Index( - [pd.Timedelta(days=2), pd.Timedelta(days=4), pd.Timestamp("2000-01-07")] + [Timedelta(days=2), Timedelta(days=4), Timestamp("2000-01-07")] ) expected = tm.box_expected(expected, xbox) tm.assert_equal(result, expected) @@ -1492,9 +1490,7 @@ def test_td64arr_add_sub_object_array(self, box_with_array): with tm.assert_produces_warning(PerformanceWarning): result = other - tdarr - expected = pd.Index( - [pd.Timedelta(0), pd.Timedelta(0), pd.Timestamp("2000-01-01")] - ) + expected = pd.Index([Timedelta(0), Timedelta(0), Timestamp("2000-01-01")]) expected = tm.box_expected(expected, xbox) tm.assert_equal(result, expected) @@ -2188,9 +2184,9 @@ def test_td64arr_pow_invalid(self, scalar_td, box_with_array): def test_add_timestamp_to_timedelta(): # GH: 35897 - timestamp = pd.Timestamp.now() + timestamp = Timestamp.now() result = timestamp + pd.timedelta_range("0s", "1s", periods=31) - expected = pd.DatetimeIndex( + expected = DatetimeIndex( [ timestamp + ( diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index 471e11cff9fd7..657511116c306 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -54,7 +54,7 @@ def test_constructor_empty(self): def test_constructor_empty_boolean(self): # see gh-22702 - cat = pd.Categorical([], categories=[True, False]) + cat = Categorical([], categories=[True, False]) categories = sorted(cat.categories.tolist()) assert categories == [False, True] @@ -412,7 +412,7 @@ def test_constructor_str_unknown(self): def test_constructor_np_strs(self): # GH#31499 Hastable.map_locations needs to work on np.str_ objects - cat = pd.Categorical(["1", "0", "1"], [np.str_("0"), np.str_("1")]) + cat = Categorical(["1", "0", "1"], [np.str_("0"), np.str_("1")]) assert all(isinstance(x, np.str_) for x in cat.categories) def test_constructor_from_categorical_with_dtype(self): @@ -637,48 +637,48 @@ def test_constructor_imaginary(self): def test_constructor_string_and_tuples(self): # GH 21416 - c = pd.Categorical(np.array(["c", ("a", "b"), ("b", "a"), "c"], dtype=object)) + c = Categorical(np.array(["c", ("a", "b"), ("b", "a"), "c"], dtype=object)) expected_index = Index([("a", "b"), ("b", "a"), "c"]) assert c.categories.equals(expected_index) def test_interval(self): idx = pd.interval_range(0, 10, periods=10) - cat = pd.Categorical(idx, categories=idx) + cat = Categorical(idx, categories=idx) expected_codes = np.arange(10, dtype="int8") tm.assert_numpy_array_equal(cat.codes, expected_codes) tm.assert_index_equal(cat.categories, idx) # infer categories - cat = pd.Categorical(idx) + cat = Categorical(idx) tm.assert_numpy_array_equal(cat.codes, expected_codes) tm.assert_index_equal(cat.categories, idx) # list values - cat = pd.Categorical(list(idx)) + cat = Categorical(list(idx)) tm.assert_numpy_array_equal(cat.codes, expected_codes) tm.assert_index_equal(cat.categories, idx) # list values, categories - cat = pd.Categorical(list(idx), categories=list(idx)) + cat = Categorical(list(idx), categories=list(idx)) tm.assert_numpy_array_equal(cat.codes, expected_codes) tm.assert_index_equal(cat.categories, idx) # shuffled values = idx.take([1, 2, 0]) - cat = pd.Categorical(values, categories=idx) + cat = Categorical(values, categories=idx) tm.assert_numpy_array_equal(cat.codes, np.array([1, 2, 0], dtype="int8")) tm.assert_index_equal(cat.categories, idx) # extra values = pd.interval_range(8, 11, periods=3) - cat = pd.Categorical(values, categories=idx) + cat = Categorical(values, categories=idx) expected_codes = np.array([8, 9, -1], dtype="int8") tm.assert_numpy_array_equal(cat.codes, expected_codes) tm.assert_index_equal(cat.categories, idx) # overlapping idx = pd.IntervalIndex([pd.Interval(0, 2), pd.Interval(0, 1)]) - cat = pd.Categorical(idx, categories=idx) + cat = Categorical(idx, categories=idx) expected_codes = np.array([0, 1], dtype="int8") tm.assert_numpy_array_equal(cat.codes, expected_codes) tm.assert_index_equal(cat.categories, idx) diff --git a/pandas/tests/arrays/categorical/test_indexing.py b/pandas/tests/arrays/categorical/test_indexing.py index c589b72fa2895..bf0b5289b5df1 100644 --- a/pandas/tests/arrays/categorical/test_indexing.py +++ b/pandas/tests/arrays/categorical/test_indexing.py @@ -1,7 +1,6 @@ import numpy as np import pytest -import pandas as pd from pandas import Categorical, CategoricalIndex, Index, PeriodIndex, Series import pandas._testing as tm import pandas.core.common as com @@ -40,28 +39,28 @@ def test_setitem(self): @pytest.mark.parametrize( "other", - [pd.Categorical(["b", "a"]), pd.Categorical(["b", "a"], categories=["b", "a"])], + [Categorical(["b", "a"]), Categorical(["b", "a"], categories=["b", "a"])], ) def test_setitem_same_but_unordered(self, other): # GH-24142 - target = pd.Categorical(["a", "b"], categories=["a", "b"]) + target = Categorical(["a", "b"], categories=["a", "b"]) mask = np.array([True, False]) target[mask] = other[mask] - expected = pd.Categorical(["b", "b"], categories=["a", "b"]) + expected = Categorical(["b", "b"], categories=["a", "b"]) tm.assert_categorical_equal(target, expected) @pytest.mark.parametrize( "other", [ - pd.Categorical(["b", "a"], categories=["b", "a", "c"]), - pd.Categorical(["b", "a"], categories=["a", "b", "c"]), - pd.Categorical(["a", "a"], categories=["a"]), - pd.Categorical(["b", "b"], categories=["b"]), + Categorical(["b", "a"], categories=["b", "a", "c"]), + Categorical(["b", "a"], categories=["a", "b", "c"]), + Categorical(["a", "a"], categories=["a"]), + Categorical(["b", "b"], categories=["b"]), ], ) def test_setitem_different_unordered_raises(self, other): # GH-24142 - target = pd.Categorical(["a", "b"], categories=["a", "b"]) + target = Categorical(["a", "b"], categories=["a", "b"]) mask = np.array([True, False]) msg = "Cannot set a Categorical with another, without identical categories" with pytest.raises(ValueError, match=msg): @@ -70,14 +69,14 @@ def test_setitem_different_unordered_raises(self, other): @pytest.mark.parametrize( "other", [ - pd.Categorical(["b", "a"]), - pd.Categorical(["b", "a"], categories=["b", "a"], ordered=True), - pd.Categorical(["b", "a"], categories=["a", "b", "c"], ordered=True), + Categorical(["b", "a"]), + Categorical(["b", "a"], categories=["b", "a"], ordered=True), + Categorical(["b", "a"], categories=["a", "b", "c"], ordered=True), ], ) def test_setitem_same_ordered_raises(self, other): # Gh-24142 - target = pd.Categorical(["a", "b"], categories=["a", "b"], ordered=True) + target = Categorical(["a", "b"], categories=["a", "b"], ordered=True) mask = np.array([True, False]) msg = "Cannot set a Categorical with another, without identical categories" with pytest.raises(ValueError, match=msg): @@ -85,7 +84,7 @@ def test_setitem_same_ordered_raises(self, other): def test_setitem_tuple(self): # GH#20439 - cat = pd.Categorical([(0, 1), (0, 2), (0, 1)]) + cat = Categorical([(0, 1), (0, 2), (0, 1)]) # This should not raise cat[1] = cat[0] @@ -216,15 +215,15 @@ def test_get_indexer_non_unique(self, idx_values, key_values, key_class): tm.assert_numpy_array_equal(exp_miss, res_miss) def test_where_unobserved_nan(self): - ser = Series(pd.Categorical(["a", "b"])) + ser = Series(Categorical(["a", "b"])) result = ser.where([True, False]) - expected = Series(pd.Categorical(["a", None], categories=["a", "b"])) + expected = Series(Categorical(["a", None], categories=["a", "b"])) tm.assert_series_equal(result, expected) # all NA - ser = Series(pd.Categorical(["a", "b"])) + ser = Series(Categorical(["a", "b"])) result = ser.where([False, False]) - expected = Series(pd.Categorical([None, None], categories=["a", "b"])) + expected = Series(Categorical([None, None], categories=["a", "b"])) tm.assert_series_equal(result, expected) def test_where_unobserved_categories(self): diff --git a/pandas/tests/arrays/categorical/test_operators.py b/pandas/tests/arrays/categorical/test_operators.py index ed70417523491..51dc66c18a3e6 100644 --- a/pandas/tests/arrays/categorical/test_operators.py +++ b/pandas/tests/arrays/categorical/test_operators.py @@ -180,7 +180,7 @@ def test_comparison_with_unknown_scalars(self): tm.assert_numpy_array_equal(cat != 4, np.array([True, True, True])) def test_comparison_with_tuple(self): - cat = pd.Categorical(np.array(["foo", (0, 1), 3, (0, 1)], dtype=object)) + cat = Categorical(np.array(["foo", (0, 1), 3, (0, 1)], dtype=object)) result = cat == "foo" expected = np.array([True, False, False, False], dtype=bool) @@ -337,8 +337,8 @@ def test_compare_different_lengths(self): def test_compare_unordered_different_order(self): # https://github.com/pandas-dev/pandas/issues/16603#issuecomment- # 349290078 - a = pd.Categorical(["a"], categories=["a", "b"]) - b = pd.Categorical(["b"], categories=["b", "a"]) + a = Categorical(["a"], categories=["a", "b"]) + b = Categorical(["b"], categories=["b", "a"]) assert not a.equals(b) def test_numeric_like_ops(self): @@ -398,7 +398,7 @@ def test_numeric_like_ops(self): def test_contains(self): # GH21508 - c = pd.Categorical(list("aabbca"), categories=list("cab")) + c = Categorical(list("aabbca"), categories=list("cab")) assert "b" in c assert "z" not in c @@ -410,7 +410,7 @@ def test_contains(self): assert 0 not in c assert 1 not in c - c = pd.Categorical(list("aabbca") + [np.nan], categories=list("cab")) + c = Categorical(list("aabbca") + [np.nan], categories=list("cab")) assert np.nan in c @pytest.mark.parametrize( diff --git a/pandas/tests/arrays/test_timedeltas.py b/pandas/tests/arrays/test_timedeltas.py index 47ebfe311d9ea..c0567209ff91b 100644 --- a/pandas/tests/arrays/test_timedeltas.py +++ b/pandas/tests/arrays/test_timedeltas.py @@ -81,7 +81,7 @@ def test_from_sequence_dtype(self): @pytest.mark.parametrize("dtype", [int, np.int32, np.int64, "uint32", "uint64"]) def test_astype_int(self, dtype): - arr = TimedeltaArray._from_sequence([pd.Timedelta("1H"), pd.Timedelta("2H")]) + arr = TimedeltaArray._from_sequence([Timedelta("1H"), Timedelta("2H")]) result = arr.astype(dtype) if np.dtype(dtype).kind == "u": @@ -95,15 +95,15 @@ def test_astype_int(self, dtype): def test_setitem_clears_freq(self): a = TimedeltaArray(pd.timedelta_range("1H", periods=2, freq="H")) - a[0] = pd.Timedelta("1H") + a[0] = Timedelta("1H") assert a.freq is None @pytest.mark.parametrize( "obj", [ - pd.Timedelta(seconds=1), - pd.Timedelta(seconds=1).to_timedelta64(), - pd.Timedelta(seconds=1).to_pytimedelta(), + Timedelta(seconds=1), + Timedelta(seconds=1).to_timedelta64(), + Timedelta(seconds=1).to_pytimedelta(), ], ) def test_setitem_objects(self, obj): @@ -112,7 +112,7 @@ def test_setitem_objects(self, obj): arr = TimedeltaArray(tdi, freq=tdi.freq) arr[0] = obj - assert arr[0] == pd.Timedelta(seconds=1) + assert arr[0] == Timedelta(seconds=1) @pytest.mark.parametrize( "other", @@ -206,11 +206,11 @@ def test_min_max(self): arr = TimedeltaArray._from_sequence(["3H", "3H", "NaT", "2H", "5H", "4H"]) result = arr.min() - expected = pd.Timedelta("2H") + expected = Timedelta("2H") assert result == expected result = arr.max() - expected = pd.Timedelta("5H") + expected = Timedelta("5H") assert result == expected result = arr.min(skipna=False) @@ -224,12 +224,12 @@ def test_sum(self): arr = tdi.array result = arr.sum(skipna=True) - expected = pd.Timedelta(hours=17) - assert isinstance(result, pd.Timedelta) + expected = Timedelta(hours=17) + assert isinstance(result, Timedelta) assert result == expected result = tdi.sum(skipna=True) - assert isinstance(result, pd.Timedelta) + assert isinstance(result, Timedelta) assert result == expected result = arr.sum(skipna=False) @@ -245,11 +245,11 @@ def test_sum(self): assert result is pd.NaT result = arr.sum(min_count=1) - assert isinstance(result, pd.Timedelta) + assert isinstance(result, Timedelta) assert result == expected result = tdi.sum(min_count=1) - assert isinstance(result, pd.Timedelta) + assert isinstance(result, Timedelta) assert result == expected def test_npsum(self): @@ -258,12 +258,12 @@ def test_npsum(self): arr = tdi.array result = np.sum(tdi) - expected = pd.Timedelta(hours=17) - assert isinstance(result, pd.Timedelta) + expected = Timedelta(hours=17) + assert isinstance(result, Timedelta) assert result == expected result = np.sum(arr) - assert isinstance(result, pd.Timedelta) + assert isinstance(result, Timedelta) assert result == expected def test_sum_2d_skipna_false(self): @@ -276,15 +276,15 @@ def test_sum_2d_skipna_false(self): assert result is pd.NaT result = tda.sum(axis=0, skipna=False) - expected = pd.TimedeltaIndex([pd.Timedelta(seconds=12), pd.NaT])._values + expected = pd.TimedeltaIndex([Timedelta(seconds=12), pd.NaT])._values tm.assert_timedelta_array_equal(result, expected) result = tda.sum(axis=1, skipna=False) expected = pd.TimedeltaIndex( [ - pd.Timedelta(seconds=1), - pd.Timedelta(seconds=5), - pd.Timedelta(seconds=9), + Timedelta(seconds=1), + Timedelta(seconds=5), + Timedelta(seconds=9), pd.NaT, ] )._values @@ -294,7 +294,7 @@ def test_sum_2d_skipna_false(self): @pytest.mark.parametrize( "add", [ - pd.Timedelta(0), + Timedelta(0), pd.Timestamp.now(), pd.Timestamp.now("UTC"), pd.Timestamp.now("Asia/Tokyo"), @@ -305,17 +305,17 @@ def test_std(self, add): arr = tdi.array result = arr.std(skipna=True) - expected = pd.Timedelta(hours=2) - assert isinstance(result, pd.Timedelta) + expected = Timedelta(hours=2) + assert isinstance(result, Timedelta) assert result == expected result = tdi.std(skipna=True) - assert isinstance(result, pd.Timedelta) + assert isinstance(result, Timedelta) assert result == expected if getattr(arr, "tz", None) is None: result = nanops.nanstd(np.asarray(arr), skipna=True) - assert isinstance(result, pd.Timedelta) + assert isinstance(result, Timedelta) assert result == expected result = arr.std(skipna=False) @@ -333,12 +333,12 @@ def test_median(self): arr = tdi.array result = arr.median(skipna=True) - expected = pd.Timedelta(hours=2) - assert isinstance(result, pd.Timedelta) + expected = Timedelta(hours=2) + assert isinstance(result, Timedelta) assert result == expected result = tdi.median(skipna=True) - assert isinstance(result, pd.Timedelta) + assert isinstance(result, Timedelta) assert result == expected result = arr.median(skipna=False) @@ -352,7 +352,7 @@ def test_mean(self): arr = tdi._data # manually verified result - expected = pd.Timedelta(arr.dropna()._ndarray.mean()) + expected = Timedelta(arr.dropna()._ndarray.mean()) result = arr.mean() assert result == expected @@ -374,7 +374,7 @@ def test_mean_2d(self): tm.assert_timedelta_array_equal(result, expected) result = tda.mean(axis=1) - expected = tda[:, 0] + pd.Timedelta(hours=12) + expected = tda[:, 0] + Timedelta(hours=12) tm.assert_timedelta_array_equal(result, expected) result = tda.mean(axis=None) diff --git a/pandas/tests/base/test_conversion.py b/pandas/tests/base/test_conversion.py index 538cf2c78b50e..24e88824088be 100644 --- a/pandas/tests/base/test_conversion.py +++ b/pandas/tests/base/test_conversion.py @@ -306,8 +306,8 @@ def test_array_multiindex_raises(): ), np.array( [ - pd.Timestamp("2000-01-01", tz="US/Central"), - pd.Timestamp("2000-01-02", tz="US/Central"), + Timestamp("2000-01-01", tz="US/Central"), + Timestamp("2000-01-02", tz="US/Central"), ] ), ), @@ -360,7 +360,7 @@ def test_to_numpy_dtype(as_series): # preserve tz by default result = obj.to_numpy() expected = np.array( - [pd.Timestamp("2000", tz=tz), pd.Timestamp("2001", tz=tz)], dtype=object + [Timestamp("2000", tz=tz), Timestamp("2001", tz=tz)], dtype=object ) tm.assert_numpy_array_equal(result, expected) @@ -377,9 +377,9 @@ def test_to_numpy_dtype(as_series): [ ([1, 2, None], "float64", 0, [1.0, 2.0, 0.0]), ( - [pd.Timestamp("2000"), pd.Timestamp("2000"), pd.NaT], + [Timestamp("2000"), Timestamp("2000"), pd.NaT], None, - pd.Timestamp("2000"), + Timestamp("2000"), [np.datetime64("2000-01-01T00:00:00.000000000")] * 3, ), ], diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index afae6ab7b9c07..1c82d6f9a26ff 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -821,10 +821,10 @@ def test_infer_dtype_datetime64_with_na(self, na_value): np.array( [np.datetime64("2011-01-02"), np.timedelta64("nat")], dtype=object ), - np.array([np.datetime64("2011-01-01"), pd.Timestamp("2011-01-02")]), - np.array([pd.Timestamp("2011-01-02"), np.datetime64("2011-01-01")]), - np.array([np.nan, pd.Timestamp("2011-01-02"), 1.1]), - np.array([np.nan, "2011-01-01", pd.Timestamp("2011-01-02")]), + np.array([np.datetime64("2011-01-01"), Timestamp("2011-01-02")]), + np.array([Timestamp("2011-01-02"), np.datetime64("2011-01-01")]), + np.array([np.nan, Timestamp("2011-01-02"), 1.1]), + np.array([np.nan, "2011-01-01", Timestamp("2011-01-02")]), np.array([np.datetime64("nat"), np.timedelta64(1, "D")], dtype=object), np.array([np.timedelta64(1, "D"), np.datetime64("nat")], dtype=object), ], @@ -833,7 +833,7 @@ def test_infer_datetimelike_dtype_mixed(self, arr): assert lib.infer_dtype(arr, skipna=False) == "mixed" def test_infer_dtype_mixed_integer(self): - arr = np.array([np.nan, pd.Timestamp("2011-01-02"), 1]) + arr = np.array([np.nan, Timestamp("2011-01-02"), 1]) assert lib.infer_dtype(arr, skipna=True) == "mixed-integer" @pytest.mark.parametrize( @@ -841,7 +841,7 @@ def test_infer_dtype_mixed_integer(self): [ np.array([Timestamp("2011-01-01"), Timestamp("2011-01-02")]), np.array([datetime(2011, 1, 1), datetime(2012, 2, 1)]), - np.array([datetime(2011, 1, 1), pd.Timestamp("2011-01-02")]), + np.array([datetime(2011, 1, 1), Timestamp("2011-01-02")]), ], ) def test_infer_dtype_datetime(self, arr): @@ -849,7 +849,7 @@ def test_infer_dtype_datetime(self, arr): @pytest.mark.parametrize("na_value", [pd.NaT, np.nan]) @pytest.mark.parametrize( - "time_stamp", [pd.Timestamp("2011-01-01"), datetime(2011, 1, 1)] + "time_stamp", [Timestamp("2011-01-01"), datetime(2011, 1, 1)] ) def test_infer_dtype_datetime_with_na(self, na_value, time_stamp): # starts with nan @@ -1062,8 +1062,8 @@ def test_is_datetimelike_array_all_nan_nat_like(self): assert lib.is_datetime_with_singletz_array( np.array( [ - pd.Timestamp("20130101", tz="US/Eastern"), - pd.Timestamp("20130102", tz="US/Eastern"), + Timestamp("20130101", tz="US/Eastern"), + Timestamp("20130102", tz="US/Eastern"), ], dtype=object, ) @@ -1071,8 +1071,8 @@ def test_is_datetimelike_array_all_nan_nat_like(self): assert not lib.is_datetime_with_singletz_array( np.array( [ - pd.Timestamp("20130101", tz="US/Eastern"), - pd.Timestamp("20130102", tz="CET"), + Timestamp("20130101", tz="US/Eastern"), + Timestamp("20130102", tz="CET"), ], dtype=object, ) @@ -1115,8 +1115,8 @@ def test_date(self): @pytest.mark.parametrize( "values", [ - [date(2020, 1, 1), pd.Timestamp("2020-01-01")], - [pd.Timestamp("2020-01-01"), date(2020, 1, 1)], + [date(2020, 1, 1), Timestamp("2020-01-01")], + [Timestamp("2020-01-01"), date(2020, 1, 1)], [date(2020, 1, 1), pd.NaT], [pd.NaT, date(2020, 1, 1)], ], @@ -1194,7 +1194,7 @@ def test_to_object_array_width(self): def test_is_period(self): assert lib.is_period(pd.Period("2011-01", freq="M")) assert not lib.is_period(pd.PeriodIndex(["2011-01"], freq="M")) - assert not lib.is_period(pd.Timestamp("2011-01")) + assert not lib.is_period(Timestamp("2011-01")) assert not lib.is_period(1) assert not lib.is_period(np.nan) diff --git a/pandas/tests/dtypes/test_missing.py b/pandas/tests/dtypes/test_missing.py index e7b5d2598d8e7..c02185dd82043 100644 --- a/pandas/tests/dtypes/test_missing.py +++ b/pandas/tests/dtypes/test_missing.py @@ -225,7 +225,7 @@ def test_complex(self, value, expected): tm.assert_numpy_array_equal(result, expected) def test_datetime_other_units(self): - idx = pd.DatetimeIndex(["2011-01-01", "NaT", "2011-01-02"]) + idx = DatetimeIndex(["2011-01-01", "NaT", "2011-01-02"]) exp = np.array([False, True, False]) tm.assert_numpy_array_equal(isna(idx), exp) tm.assert_numpy_array_equal(notna(idx), ~exp) @@ -256,7 +256,7 @@ def test_datetime_other_units(self): tm.assert_series_equal(notna(s), ~exp) def test_timedelta_other_units(self): - idx = pd.TimedeltaIndex(["1 days", "NaT", "2 days"]) + idx = TimedeltaIndex(["1 days", "NaT", "2 days"]) exp = np.array([False, True, False]) tm.assert_numpy_array_equal(isna(idx), exp) tm.assert_numpy_array_equal(notna(idx), ~exp) diff --git a/pandas/tests/extension/test_categorical.py b/pandas/tests/extension/test_categorical.py index 7d03dadb20dd9..e8d82b525c9f4 100644 --- a/pandas/tests/extension/test_categorical.py +++ b/pandas/tests/extension/test_categorical.py @@ -199,7 +199,7 @@ def test_cast_category_to_extension_dtype(self, expected): ) def test_consistent_casting(self, dtype, expected): # GH 28448 - result = pd.Categorical("2015-01-01").astype(dtype) + result = Categorical("2015-01-01").astype(dtype) assert result == expected diff --git a/pandas/tests/frame/apply/test_frame_apply.py b/pandas/tests/frame/apply/test_frame_apply.py index 5744a893cd9d6..03498b278f890 100644 --- a/pandas/tests/frame/apply/test_frame_apply.py +++ b/pandas/tests/frame/apply/test_frame_apply.py @@ -659,10 +659,10 @@ def test_applymap_box(self): # ufunc will not be boxed. Same test cases as the test_map_box df = DataFrame( { - "a": [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")], + "a": [Timestamp("2011-01-01"), Timestamp("2011-01-02")], "b": [ - pd.Timestamp("2011-01-01", tz="US/Eastern"), - pd.Timestamp("2011-01-02", tz="US/Eastern"), + Timestamp("2011-01-01", tz="US/Eastern"), + Timestamp("2011-01-02", tz="US/Eastern"), ], "c": [pd.Timedelta("1 days"), pd.Timedelta("2 days")], "d": [ @@ -734,7 +734,7 @@ def apply_list(row): def test_apply_noreduction_tzaware_object(self): # https://github.com/pandas-dev/pandas/issues/31505 df = DataFrame( - {"foo": [pd.Timestamp("2020", tz="UTC")]}, dtype="datetime64[ns, UTC]" + {"foo": [Timestamp("2020", tz="UTC")]}, dtype="datetime64[ns, UTC]" ) result = df.apply(lambda x: x) tm.assert_frame_equal(result, df) @@ -844,8 +844,8 @@ def test_with_dictlike_columns(self): tm.assert_series_equal(result, expected) df["tm"] = [ - pd.Timestamp("2017-05-01 00:00:00"), - pd.Timestamp("2017-05-02 00:00:00"), + Timestamp("2017-05-01 00:00:00"), + Timestamp("2017-05-02 00:00:00"), ] result = df.apply(lambda x: {"s": x["a"] + x["b"]}, axis=1) tm.assert_series_equal(result, expected) @@ -876,8 +876,8 @@ def test_with_dictlike_columns_with_infer(self): tm.assert_frame_equal(result, expected) df["tm"] = [ - pd.Timestamp("2017-05-01 00:00:00"), - pd.Timestamp("2017-05-02 00:00:00"), + Timestamp("2017-05-01 00:00:00"), + Timestamp("2017-05-02 00:00:00"), ] result = df.apply( lambda x: {"s": x["a"] + x["b"]}, axis=1, result_type="expand" @@ -920,8 +920,8 @@ def test_infer_output_shape_columns(self): "number": [1.0, 2.0], "string": ["foo", "bar"], "datetime": [ - pd.Timestamp("2017-11-29 03:30:00"), - pd.Timestamp("2017-11-29 03:45:00"), + Timestamp("2017-11-29 03:30:00"), + Timestamp("2017-11-29 03:45:00"), ], } ) @@ -957,10 +957,10 @@ def test_infer_output_shape_listlike_columns(self): df = DataFrame( { "a": [ - pd.Timestamp("2010-02-01"), - pd.Timestamp("2010-02-04"), - pd.Timestamp("2010-02-05"), - pd.Timestamp("2010-02-06"), + Timestamp("2010-02-01"), + Timestamp("2010-02-04"), + Timestamp("2010-02-05"), + Timestamp("2010-02-06"), ], "b": [9, 5, 4, 3], "c": [5, 3, 4, 2], @@ -1176,7 +1176,7 @@ def test_agg_multiple_mixed_no_warning(self): "A": [1, 6], "B": [1.0, 6.0], "C": ["bar", "foobarbaz"], - "D": [pd.Timestamp("2013-01-01"), pd.NaT], + "D": [Timestamp("2013-01-01"), pd.NaT], }, index=["min", "sum"], ) @@ -1297,12 +1297,12 @@ def test_nuiscance_columns(self): ) result = df.agg("min") - expected = Series([1, 1.0, "bar", pd.Timestamp("20130101")], index=df.columns) + expected = Series([1, 1.0, "bar", Timestamp("20130101")], index=df.columns) tm.assert_series_equal(result, expected) result = df.agg(["min"]) expected = DataFrame( - [[1, 1.0, "bar", pd.Timestamp("20130101")]], + [[1, 1.0, "bar", Timestamp("20130101")]], index=["min"], columns=df.columns, ) @@ -1505,9 +1505,9 @@ def test_apply_datetime_tz_issue(self): # GH 29052 timestamps = [ - pd.Timestamp("2019-03-15 12:34:31.909000+0000", tz="UTC"), - pd.Timestamp("2019-03-15 12:34:34.359000+0000", tz="UTC"), - pd.Timestamp("2019-03-15 12:34:34.660000+0000", tz="UTC"), + Timestamp("2019-03-15 12:34:31.909000+0000", tz="UTC"), + Timestamp("2019-03-15 12:34:34.359000+0000", tz="UTC"), + Timestamp("2019-03-15 12:34:34.660000+0000", tz="UTC"), ] df = DataFrame(data=[0, 1, 2], index=timestamps) result = df.apply(lambda x: x.name, axis=1) diff --git a/pandas/tests/frame/indexing/test_categorical.py b/pandas/tests/frame/indexing/test_categorical.py index e37d00c540974..d3c907f4ce30f 100644 --- a/pandas/tests/frame/indexing/test_categorical.py +++ b/pandas/tests/frame/indexing/test_categorical.py @@ -355,7 +355,7 @@ def test_assigning_ops(self): def test_setitem_single_row_categorical(self): # GH 25495 df = DataFrame({"Alpha": ["a"], "Numeric": [0]}) - categories = pd.Categorical(df["Alpha"], categories=["a", "b", "c"]) + categories = Categorical(df["Alpha"], categories=["a", "b", "c"]) df.loc[:, "Alpha"] = categories result = df["Alpha"] diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index d7be4d071ad74..58f0e5bc1ad39 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -1456,11 +1456,11 @@ def test_loc_duplicates(self): # insert a duplicate element to the index trange = pd.date_range( - start=pd.Timestamp(year=2017, month=1, day=1), - end=pd.Timestamp(year=2017, month=1, day=5), + start=Timestamp(year=2017, month=1, day=1), + end=Timestamp(year=2017, month=1, day=5), ) - trange = trange.insert(loc=5, item=pd.Timestamp(year=2017, month=1, day=5)) + trange = trange.insert(loc=5, item=Timestamp(year=2017, month=1, day=5)) df = DataFrame(0, index=trange, columns=["A", "B"]) bool_idx = np.array([False, False, False, False, False, True]) @@ -1530,12 +1530,12 @@ def test_setitem_with_unaligned_tz_aware_datetime_column(self): def test_loc_setitem_datetime_coercion(self): # gh-1048 - df = DataFrame({"c": [pd.Timestamp("2010-10-01")] * 3}) + df = DataFrame({"c": [Timestamp("2010-10-01")] * 3}) df.loc[0:1, "c"] = np.datetime64("2008-08-08") - assert pd.Timestamp("2008-08-08") == df.loc[0, "c"] - assert pd.Timestamp("2008-08-08") == df.loc[1, "c"] + assert Timestamp("2008-08-08") == df.loc[0, "c"] + assert Timestamp("2008-08-08") == df.loc[1, "c"] df.loc[2, "c"] = date(2005, 5, 5) - assert pd.Timestamp("2005-05-05") == df.loc[2, "c"] + assert Timestamp("2005-05-05") == df.loc[2, "c"] def test_loc_setitem_datetimelike_with_inference(self): # GH 7592 @@ -1812,27 +1812,27 @@ def test_object_casting_indexing_wraps_datetimelike(): ) ser = df.loc[0] - assert isinstance(ser.values[1], pd.Timestamp) + assert isinstance(ser.values[1], Timestamp) assert isinstance(ser.values[2], pd.Timedelta) ser = df.iloc[0] - assert isinstance(ser.values[1], pd.Timestamp) + assert isinstance(ser.values[1], Timestamp) assert isinstance(ser.values[2], pd.Timedelta) ser = df.xs(0, axis=0) - assert isinstance(ser.values[1], pd.Timestamp) + assert isinstance(ser.values[1], Timestamp) assert isinstance(ser.values[2], pd.Timedelta) mgr = df._mgr mgr._rebuild_blknos_and_blklocs() arr = mgr.fast_xs(0) - assert isinstance(arr[1], pd.Timestamp) + assert isinstance(arr[1], Timestamp) assert isinstance(arr[2], pd.Timedelta) blk = mgr.blocks[mgr.blknos[1]] assert blk.dtype == "M8[ns]" # we got the right block val = blk.iget((0, 0)) - assert isinstance(val, pd.Timestamp) + assert isinstance(val, Timestamp) blk = mgr.blocks[mgr.blknos[2]] assert blk.dtype == "m8[ns]" # we got the right block diff --git a/pandas/tests/frame/methods/test_append.py b/pandas/tests/frame/methods/test_append.py index c08a77d00a96d..38b5c150630fe 100644 --- a/pandas/tests/frame/methods/test_append.py +++ b/pandas/tests/frame/methods/test_append.py @@ -189,9 +189,9 @@ def test_append_dtypes(self): def test_append_timestamps_aware_or_naive(self, tz_naive_fixture, timestamp): # GH 30238 tz = tz_naive_fixture - df = DataFrame([pd.Timestamp(timestamp, tz=tz)]) + df = DataFrame([Timestamp(timestamp, tz=tz)]) result = df.append(df.iloc[0]).iloc[-1] - expected = Series(pd.Timestamp(timestamp, tz=tz), name=0) + expected = Series(Timestamp(timestamp, tz=tz), name=0) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( diff --git a/pandas/tests/frame/methods/test_describe.py b/pandas/tests/frame/methods/test_describe.py index 0358bc3c04539..a90781cf43c16 100644 --- a/pandas/tests/frame/methods/test_describe.py +++ b/pandas/tests/frame/methods/test_describe.py @@ -277,12 +277,12 @@ def test_datetime_is_numeric_includes_datetime(self): { "a": [ 3, - pd.Timestamp("2012-01-02"), - pd.Timestamp("2012-01-01"), - pd.Timestamp("2012-01-01T12:00:00"), - pd.Timestamp("2012-01-02"), - pd.Timestamp("2012-01-02T12:00:00"), - pd.Timestamp("2012-01-03"), + Timestamp("2012-01-02"), + Timestamp("2012-01-01"), + Timestamp("2012-01-01T12:00:00"), + Timestamp("2012-01-02"), + Timestamp("2012-01-02T12:00:00"), + Timestamp("2012-01-03"), np.nan, ], "b": [3, 2, 1, 1.5, 2, 2.5, 3, 1], diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py index 09c10861e87c2..eb5bc31f3aa8f 100644 --- a/pandas/tests/frame/methods/test_drop.py +++ b/pandas/tests/frame/methods/test_drop.py @@ -19,7 +19,7 @@ ) def test_drop_raise_exception_if_labels_not_in_level(msg, labels, level): # GH 8594 - mi = pd.MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"]) + mi = MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"]) s = pd.Series([10, 20, 30], index=mi) df = DataFrame([10, 20, 30], index=mi) @@ -32,7 +32,7 @@ def test_drop_raise_exception_if_labels_not_in_level(msg, labels, level): @pytest.mark.parametrize("labels,level", [(4, "a"), (7, "b")]) def test_drop_errors_ignore(labels, level): # GH 8594 - mi = pd.MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"]) + mi = MultiIndex.from_arrays([[1, 2, 3], [4, 5, 6]], names=["a", "b"]) s = pd.Series([10, 20, 30], index=mi) df = DataFrame([10, 20, 30], index=mi) @@ -313,7 +313,7 @@ def test_drop_multiindex_other_level_nan(self): expected = DataFrame( [2, 1], columns=["D"], - index=pd.MultiIndex.from_tuples( + index=MultiIndex.from_tuples( [("one", 0.0, "b"), ("one", np.nan, "a")], names=["A", "B", "C"] ), ) diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py index 5cdd65b8cf6e2..13e00c97d6f71 100644 --- a/pandas/tests/frame/methods/test_quantile.py +++ b/pandas/tests/frame/methods/test_quantile.py @@ -288,14 +288,14 @@ def test_quantile_box(self): df = DataFrame( { "A": [ - pd.Timestamp("2011-01-01"), - pd.Timestamp("2011-01-02"), - pd.Timestamp("2011-01-03"), + Timestamp("2011-01-01"), + Timestamp("2011-01-02"), + Timestamp("2011-01-03"), ], "B": [ - pd.Timestamp("2011-01-01", tz="US/Eastern"), - pd.Timestamp("2011-01-02", tz="US/Eastern"), - pd.Timestamp("2011-01-03", tz="US/Eastern"), + Timestamp("2011-01-01", tz="US/Eastern"), + Timestamp("2011-01-02", tz="US/Eastern"), + Timestamp("2011-01-03", tz="US/Eastern"), ], "C": [ pd.Timedelta("1 days"), @@ -309,8 +309,8 @@ def test_quantile_box(self): exp = Series( [ - pd.Timestamp("2011-01-02"), - pd.Timestamp("2011-01-02", tz="US/Eastern"), + Timestamp("2011-01-02"), + Timestamp("2011-01-02", tz="US/Eastern"), pd.Timedelta("2 days"), ], name=0.5, @@ -322,8 +322,8 @@ def test_quantile_box(self): exp = DataFrame( [ [ - pd.Timestamp("2011-01-02"), - pd.Timestamp("2011-01-02", tz="US/Eastern"), + Timestamp("2011-01-02"), + Timestamp("2011-01-02", tz="US/Eastern"), pd.Timedelta("2 days"), ] ], @@ -336,28 +336,28 @@ def test_quantile_box(self): df = DataFrame( { "A": [ - pd.Timestamp("2011-01-01"), + Timestamp("2011-01-01"), pd.NaT, - pd.Timestamp("2011-01-02"), - pd.Timestamp("2011-01-03"), + Timestamp("2011-01-02"), + Timestamp("2011-01-03"), ], "a": [ - pd.Timestamp("2011-01-01"), - pd.Timestamp("2011-01-02"), + Timestamp("2011-01-01"), + Timestamp("2011-01-02"), pd.NaT, - pd.Timestamp("2011-01-03"), + Timestamp("2011-01-03"), ], "B": [ - pd.Timestamp("2011-01-01", tz="US/Eastern"), + Timestamp("2011-01-01", tz="US/Eastern"), pd.NaT, - pd.Timestamp("2011-01-02", tz="US/Eastern"), - pd.Timestamp("2011-01-03", tz="US/Eastern"), + Timestamp("2011-01-02", tz="US/Eastern"), + Timestamp("2011-01-03", tz="US/Eastern"), ], "b": [ - pd.Timestamp("2011-01-01", tz="US/Eastern"), - pd.Timestamp("2011-01-02", tz="US/Eastern"), + Timestamp("2011-01-01", tz="US/Eastern"), + Timestamp("2011-01-02", tz="US/Eastern"), pd.NaT, - pd.Timestamp("2011-01-03", tz="US/Eastern"), + Timestamp("2011-01-03", tz="US/Eastern"), ], "C": [ pd.Timedelta("1 days"), @@ -378,10 +378,10 @@ def test_quantile_box(self): res = df.quantile(0.5, numeric_only=False) exp = Series( [ - pd.Timestamp("2011-01-02"), - pd.Timestamp("2011-01-02"), - pd.Timestamp("2011-01-02", tz="US/Eastern"), - pd.Timestamp("2011-01-02", tz="US/Eastern"), + Timestamp("2011-01-02"), + Timestamp("2011-01-02"), + Timestamp("2011-01-02", tz="US/Eastern"), + Timestamp("2011-01-02", tz="US/Eastern"), pd.Timedelta("2 days"), pd.Timedelta("2 days"), ], @@ -394,10 +394,10 @@ def test_quantile_box(self): exp = DataFrame( [ [ - pd.Timestamp("2011-01-02"), - pd.Timestamp("2011-01-02"), - pd.Timestamp("2011-01-02", tz="US/Eastern"), - pd.Timestamp("2011-01-02", tz="US/Eastern"), + Timestamp("2011-01-02"), + Timestamp("2011-01-02"), + Timestamp("2011-01-02", tz="US/Eastern"), + Timestamp("2011-01-02", tz="US/Eastern"), pd.Timedelta("2 days"), pd.Timedelta("2 days"), ] @@ -457,21 +457,21 @@ def test_quantile_nat(self): df = DataFrame( { "a": [ - pd.Timestamp("2012-01-01"), - pd.Timestamp("2012-01-02"), - pd.Timestamp("2012-01-03"), + Timestamp("2012-01-01"), + Timestamp("2012-01-02"), + Timestamp("2012-01-03"), ], "b": [pd.NaT, pd.NaT, pd.NaT], } ) res = df.quantile(0.5, numeric_only=False) - exp = Series([pd.Timestamp("2012-01-02"), pd.NaT], index=["a", "b"], name=0.5) + exp = Series([Timestamp("2012-01-02"), pd.NaT], index=["a", "b"], name=0.5) tm.assert_series_equal(res, exp) res = df.quantile([0.5], numeric_only=False) exp = DataFrame( - [[pd.Timestamp("2012-01-02"), pd.NaT]], index=[0.5], columns=["a", "b"] + [[Timestamp("2012-01-02"), pd.NaT]], index=[0.5], columns=["a", "b"] ) tm.assert_frame_equal(res, exp) diff --git a/pandas/tests/frame/methods/test_replace.py b/pandas/tests/frame/methods/test_replace.py index 2c909ab2f8227..baa310ddd6f09 100644 --- a/pandas/tests/frame/methods/test_replace.py +++ b/pandas/tests/frame/methods/test_replace.py @@ -1245,13 +1245,13 @@ def test_replace_period(self): def test_replace_datetime(self): d = { "fname": { - "out_augmented_AUG_2011.json": pd.Timestamp("2011-08"), - "out_augmented_JAN_2011.json": pd.Timestamp("2011-01"), - "out_augmented_MAY_2012.json": pd.Timestamp("2012-05"), - "out_augmented_SUBSIDY_WEEK.json": pd.Timestamp("2011-04"), - "out_augmented_AUG_2012.json": pd.Timestamp("2012-08"), - "out_augmented_MAY_2011.json": pd.Timestamp("2011-05"), - "out_augmented_SEP_2013.json": pd.Timestamp("2013-09"), + "out_augmented_AUG_2011.json": Timestamp("2011-08"), + "out_augmented_JAN_2011.json": Timestamp("2011-01"), + "out_augmented_MAY_2012.json": Timestamp("2012-05"), + "out_augmented_SUBSIDY_WEEK.json": Timestamp("2011-04"), + "out_augmented_AUG_2012.json": Timestamp("2012-08"), + "out_augmented_MAY_2011.json": Timestamp("2011-05"), + "out_augmented_SEP_2013.json": Timestamp("2013-09"), } } @@ -1462,7 +1462,7 @@ def test_replace_commutative(self, df, to_replace, exp): @pytest.mark.parametrize( "replacer", [ - pd.Timestamp("20170827"), + Timestamp("20170827"), np.int8(1), np.int16(1), np.float32(1), diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index 6aebc23d1c016..92c9f7564a670 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -526,8 +526,8 @@ def test_reset_index_with_drop( {"a": [pd.NaT, pd.NaT], "b": [1, 2], "x": [11, 12]}, ), ( - [(pd.NaT, 1), (pd.Timestamp("2020-01-01"), 2)], - {"a": [pd.NaT, pd.Timestamp("2020-01-01")], "b": [1, 2], "x": [11, 12]}, + [(pd.NaT, 1), (Timestamp("2020-01-01"), 2)], + {"a": [pd.NaT, Timestamp("2020-01-01")], "b": [1, 2], "x": [11, 12]}, ), ( [(pd.NaT, 1), (pd.Timedelta(123, "d"), 2)], @@ -593,7 +593,7 @@ def test_reset_index_dtypes_on_empty_frame_with_multiindex(array, dtype): def test_reset_index_empty_frame_with_datetime64_multiindex(): # https://github.com/pandas-dev/pandas/issues/35606 idx = MultiIndex( - levels=[[pd.Timestamp("2020-07-20 00:00:00")], [3, 4]], + levels=[[Timestamp("2020-07-20 00:00:00")], [3, 4]], codes=[[], []], names=["a", "b"], ) diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py index 16d451a12efc0..de847c12723b2 100644 --- a/pandas/tests/frame/methods/test_sort_index.py +++ b/pandas/tests/frame/methods/test_sort_index.py @@ -851,7 +851,7 @@ def test_sort_index_multiindex_sparse_column(self): i: pd.array([0.0, 0.0, 0.0, 0.0], dtype=pd.SparseDtype("float64", 0.0)) for i in range(0, 4) }, - index=pd.MultiIndex.from_product([[1, 2], [1, 2]]), + index=MultiIndex.from_product([[1, 2], [1, 2]]), ) result = expected.sort_index(level=0) diff --git a/pandas/tests/frame/methods/test_sort_values.py b/pandas/tests/frame/methods/test_sort_values.py index 7a1f0a35e1486..be5f3ee9c8191 100644 --- a/pandas/tests/frame/methods/test_sort_values.py +++ b/pandas/tests/frame/methods/test_sort_values.py @@ -242,7 +242,7 @@ def test_sort_values_stable_descending_multicolumn_sort(self): def test_sort_values_stable_categorial(self): # GH#16793 - df = DataFrame({"x": pd.Categorical(np.repeat([1, 2, 3, 4], 5), ordered=True)}) + df = DataFrame({"x": Categorical(np.repeat([1, 2, 3, 4], 5), ordered=True)}) expected = df.copy() sorted_df = df.sort_values("x", kind="mergesort") tm.assert_frame_equal(sorted_df, expected) @@ -385,7 +385,7 @@ def test_sort_values_na_position_with_categories(self): df = DataFrame( { - column_name: pd.Categorical( + column_name: Categorical( ["A", np.nan, "B", np.nan, "C"], categories=categories, ordered=True ) } @@ -477,7 +477,7 @@ def test_sort_values_nat(self): def test_sort_values_na_position_with_categories_raises(self): df = DataFrame( { - "c": pd.Categorical( + "c": Categorical( ["A", np.nan, "B", np.nan, "C"], categories=["A", "B", "C"], ordered=True, @@ -703,7 +703,7 @@ def test_sort_values_key_casts_to_categorical(self, ordered): def sorter(key): if key.name == "y": return pd.Series( - pd.Categorical(key, categories=categories, ordered=ordered) + Categorical(key, categories=categories, ordered=ordered) ) return key diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index f2847315f4959..fbb51b70d34fd 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -463,7 +463,7 @@ def test_nunique(self): @pytest.mark.parametrize("tz", [None, "UTC"]) def test_mean_mixed_datetime_numeric(self, tz): # https://github.com/pandas-dev/pandas/issues/24752 - df = DataFrame({"A": [1, 1], "B": [pd.Timestamp("2000", tz=tz)] * 2}) + df = DataFrame({"A": [1, 1], "B": [Timestamp("2000", tz=tz)] * 2}) with tm.assert_produces_warning(FutureWarning): result = df.mean() expected = Series([1.0], index=["A"]) @@ -474,7 +474,7 @@ def test_mean_excludes_datetimes(self, tz): # https://github.com/pandas-dev/pandas/issues/24752 # Our long-term desired behavior is unclear, but the behavior in # 0.24.0rc1 was buggy. - df = DataFrame({"A": [pd.Timestamp("2000", tz=tz)] * 2}) + df = DataFrame({"A": [Timestamp("2000", tz=tz)] * 2}) with tm.assert_produces_warning(FutureWarning): result = df.mean() @@ -1016,8 +1016,8 @@ def test_any_datetime(self): # GH 23070 float_data = [1, np.nan, 3, np.nan] datetime_data = [ - pd.Timestamp("1960-02-15"), - pd.Timestamp("1960-02-16"), + Timestamp("1960-02-15"), + Timestamp("1960-02-16"), pd.NaT, pd.NaT, ] @@ -1148,14 +1148,14 @@ def test_series_broadcasting(self): class TestDataFrameReductions: def test_min_max_dt64_with_NaT(self): # Both NaT and Timestamp are in DataFrame. - df = DataFrame({"foo": [pd.NaT, pd.NaT, pd.Timestamp("2012-05-01")]}) + df = DataFrame({"foo": [pd.NaT, pd.NaT, Timestamp("2012-05-01")]}) res = df.min() - exp = Series([pd.Timestamp("2012-05-01")], index=["foo"]) + exp = Series([Timestamp("2012-05-01")], index=["foo"]) tm.assert_series_equal(res, exp) res = df.max() - exp = Series([pd.Timestamp("2012-05-01")], index=["foo"]) + exp = Series([Timestamp("2012-05-01")], index=["foo"]) tm.assert_series_equal(res, exp) # GH12941, only NaTs are in DataFrame. diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 479d7902aa111..46e34a7a58ae4 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2580,7 +2580,7 @@ def test_from_records_series_categorical_index(self): [pd.Interval(-20, -10), pd.Interval(-10, 0), pd.Interval(0, 10)] ) series_of_dicts = Series([{"a": 1}, {"a": 2}, {"b": 3}], index=index) - frame = pd.DataFrame.from_records(series_of_dicts, index=index) + frame = DataFrame.from_records(series_of_dicts, index=index) expected = DataFrame( {"a": [1, 2, np.NaN], "b": [np.NaN, np.NaN, 3]}, index=index ) diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py index c34f5b35c1ab7..d1425c85caaee 100644 --- a/pandas/tests/frame/test_stack_unstack.py +++ b/pandas/tests/frame/test_stack_unstack.py @@ -228,7 +228,7 @@ def test_unstack_fill_frame_categorical(self): # Test unstacking with categorical data = Series(["a", "b", "c", "a"], dtype="category") - data.index = pd.MultiIndex.from_tuples( + data.index = MultiIndex.from_tuples( [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")] ) @@ -261,7 +261,7 @@ def test_unstack_fill_frame_categorical(self): def test_unstack_tuplename_in_multiindex(self): # GH 19966 - idx = pd.MultiIndex.from_product( + idx = MultiIndex.from_product( [["a", "b", "c"], [1, 2, 3]], names=[("A", "a"), ("B", "b")] ) df = DataFrame({"d": [1] * 9, "e": [2] * 9}, index=idx) @@ -269,7 +269,7 @@ def test_unstack_tuplename_in_multiindex(self): expected = DataFrame( [[1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2]], - columns=pd.MultiIndex.from_tuples( + columns=MultiIndex.from_tuples( [ ("d", "a"), ("d", "b"), @@ -290,10 +290,10 @@ def test_unstack_tuplename_in_multiindex(self): ( ("A", "a"), [[1, 1, 2, 2], [1, 1, 2, 2], [1, 1, 2, 2], [1, 1, 2, 2]], - pd.MultiIndex.from_tuples( + MultiIndex.from_tuples( [(1, 3), (1, 4), (2, 3), (2, 4)], names=["B", "C"] ), - pd.MultiIndex.from_tuples( + MultiIndex.from_tuples( [("d", "a"), ("d", "b"), ("e", "a"), ("e", "b")], names=[None, ("A", "a")], ), @@ -302,7 +302,7 @@ def test_unstack_tuplename_in_multiindex(self): (("A", "a"), "B"), [[1, 1, 1, 1, 2, 2, 2, 2], [1, 1, 1, 1, 2, 2, 2, 2]], Index([3, 4], name="C"), - pd.MultiIndex.from_tuples( + MultiIndex.from_tuples( [ ("d", "a", 1), ("d", "a", 2), @@ -322,7 +322,7 @@ def test_unstack_mixed_type_name_in_multiindex( self, unstack_idx, expected_values, expected_index, expected_columns ): # GH 19966 - idx = pd.MultiIndex.from_product( + idx = MultiIndex.from_product( [["a", "b"], [1, 2], [3, 4]], names=[("A", "a"), "B", "C"] ) df = DataFrame({"d": [1] * 8, "e": [2] * 8}, index=idx) @@ -493,7 +493,7 @@ def test_unstack_bool(self): def test_unstack_level_binding(self): # GH9856 - mi = pd.MultiIndex( + mi = MultiIndex( levels=[["foo", "bar"], ["one", "two"], ["a", "b"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1], [1, 0, 1, 0]], names=["first", "second", "third"], @@ -501,7 +501,7 @@ def test_unstack_level_binding(self): s = Series(0, index=mi) result = s.unstack([1, 2]).stack(0) - expected_mi = pd.MultiIndex( + expected_mi = MultiIndex( levels=[["foo", "bar"], ["one", "two"]], codes=[[0, 0, 1, 1], [0, 1, 0, 1]], names=["first", "second"], @@ -560,7 +560,7 @@ def test_unstack_dtypes(self): result = df3.dtypes expected = Series( [np.dtype("int64")] * 4, - index=pd.MultiIndex.from_arrays( + index=MultiIndex.from_arrays( [["C", "C", "D", "D"], [1, 2, 1, 2]], names=(None, "B") ), ) @@ -573,7 +573,7 @@ def test_unstack_dtypes(self): result = df3.dtypes expected = Series( [np.dtype("float64")] * 2 + [np.dtype("int64")] * 2, - index=pd.MultiIndex.from_arrays( + index=MultiIndex.from_arrays( [["C", "C", "D", "D"], [1, 2, 1, 2]], names=(None, "B") ), ) @@ -583,7 +583,7 @@ def test_unstack_dtypes(self): result = df3.dtypes expected = Series( [np.dtype("float64")] * 2 + [np.dtype("object")] * 2, - index=pd.MultiIndex.from_arrays( + index=MultiIndex.from_arrays( [["C", "C", "D", "D"], [1, 2, 1, 2]], names=(None, "B") ), ) @@ -628,11 +628,11 @@ def test_unstack_non_unique_index_names(self): def test_unstack_unused_levels(self): # GH 17845: unused codes in index make unstack() cast int to float - idx = pd.MultiIndex.from_product([["a"], ["A", "B", "C", "D"]])[:-1] + idx = MultiIndex.from_product([["a"], ["A", "B", "C", "D"]])[:-1] df = DataFrame([[1, 0]] * 3, index=idx) result = df.unstack() - exp_col = pd.MultiIndex.from_product([[0, 1], ["A", "B", "C"]]) + exp_col = MultiIndex.from_product([[0, 1], ["A", "B", "C"]]) expected = 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() @@ -640,7 +640,7 @@ def test_unstack_unused_levels(self): # Unused items on both levels levels = [[0, 1, 7], [0, 1, 2, 3]] codes = [[0, 0, 1, 1], [0, 2, 0, 2]] - idx = pd.MultiIndex(levels, codes) + idx = MultiIndex(levels, codes) block = np.arange(4).reshape(2, 2) df = DataFrame(np.concatenate([block, block + 4]), index=idx) result = df.unstack() @@ -653,7 +653,7 @@ def test_unstack_unused_levels(self): # With mixed dtype and NaN levels = [["a", 2, "c"], [1, 3, 5, 7]] codes = [[0, -1, 1, 1], [0, 2, -1, 2]] - idx = pd.MultiIndex(levels, codes) + idx = MultiIndex(levels, codes) data = np.arange(8) df = DataFrame(data.reshape(4, 2), index=idx) @@ -665,7 +665,7 @@ def test_unstack_unused_levels(self): 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]) + cols = MultiIndex.from_product([[0, 1], col_level]) expected = DataFrame(exp_data.reshape(3, 6), index=idx_level, columns=cols) tm.assert_frame_equal(result, expected) @@ -690,8 +690,8 @@ def test_unstack_long_index(self): # The error occurred only, if a lot of indices are used. df = DataFrame( [[1]], - columns=pd.MultiIndex.from_tuples([[0]], names=["c1"]), - index=pd.MultiIndex.from_tuples( + columns=MultiIndex.from_tuples([[0]], names=["c1"]), + index=MultiIndex.from_tuples( [[0, 0, 1, 0, 0, 0, 1]], names=["i1", "i2", "i3", "i4", "i5", "i6", "i7"], ), @@ -699,7 +699,7 @@ def test_unstack_long_index(self): result = df.unstack(["i2", "i3", "i4", "i5", "i6", "i7"]) expected = DataFrame( [[1]], - columns=pd.MultiIndex.from_tuples( + columns=MultiIndex.from_tuples( [[0, 0, 1, 0, 0, 0, 1]], names=["c1", "i2", "i3", "i4", "i5", "i6", "i7"], ), @@ -711,10 +711,10 @@ def test_unstack_multi_level_cols(self): # PH 24729: Unstack a df with multi level columns df = DataFrame( [[0.0, 0.0], [0.0, 0.0]], - columns=pd.MultiIndex.from_tuples( + columns=MultiIndex.from_tuples( [["B", "C"], ["B", "D"]], names=["c1", "c2"] ), - index=pd.MultiIndex.from_tuples( + index=MultiIndex.from_tuples( [[10, 20, 30], [10, 20, 40]], names=["i1", "i2", "i3"] ), ) @@ -724,8 +724,8 @@ def test_unstack_multi_level_rows_and_cols(self): # PH 28306: Unstack df with multi level cols and rows df = DataFrame( [[1, 2], [3, 4], [-1, -2], [-3, -4]], - columns=pd.MultiIndex.from_tuples([["a", "b", "c"], ["d", "e", "f"]]), - index=pd.MultiIndex.from_tuples( + columns=MultiIndex.from_tuples([["a", "b", "c"], ["d", "e", "f"]]), + index=MultiIndex.from_tuples( [ ["m1", "P3", 222], ["m1", "A5", 111], @@ -1039,7 +1039,7 @@ def test_stack_preserve_categorical_dtype(self, ordered, labels): # `MultiIndex.from_product` preserves categorical dtype - # it's tested elsewhere. - midx = pd.MultiIndex.from_product([df.index, cidx]) + midx = MultiIndex.from_product([df.index, cidx]) expected = Series([10, 11, 12], index=midx) tm.assert_series_equal(result, expected) @@ -1049,7 +1049,7 @@ def test_stack_preserve_categorical_dtype_values(self): cat = pd.Categorical(["a", "a", "b", "c"]) df = DataFrame({"A": cat, "B": cat}) result = df.stack() - index = pd.MultiIndex.from_product([[0, 1, 2, 3], ["A", "B"]]) + index = MultiIndex.from_product([[0, 1, 2, 3], ["A", "B"]]) expected = Series( pd.Categorical(["a", "a", "a", "a", "b", "b", "c", "c"]), index=index ) @@ -1058,16 +1058,16 @@ def test_stack_preserve_categorical_dtype_values(self): @pytest.mark.parametrize( "index, columns", [ - ([0, 0, 1, 1], pd.MultiIndex.from_product([[1, 2], ["a", "b"]])), - ([0, 0, 2, 3], pd.MultiIndex.from_product([[1, 2], ["a", "b"]])), - ([0, 1, 2, 3], pd.MultiIndex.from_product([[1, 2], ["a", "b"]])), + ([0, 0, 1, 1], MultiIndex.from_product([[1, 2], ["a", "b"]])), + ([0, 0, 2, 3], MultiIndex.from_product([[1, 2], ["a", "b"]])), + ([0, 1, 2, 3], MultiIndex.from_product([[1, 2], ["a", "b"]])), ], ) def test_stack_multi_columns_non_unique_index(self, index, columns): # GH-28301 df = DataFrame(index=index, columns=columns).fillna(1) stacked = df.stack() - new_index = pd.MultiIndex.from_tuples(stacked.index.to_numpy()) + new_index = MultiIndex.from_tuples(stacked.index.to_numpy()) expected = DataFrame( stacked.to_numpy(), index=new_index, columns=stacked.columns ) @@ -1078,9 +1078,7 @@ def test_stack_multi_columns_non_unique_index(self, index, columns): @pytest.mark.parametrize("level", [0, 1]) def test_unstack_mixed_extension_types(self, level): - index = pd.MultiIndex.from_tuples( - [("A", 0), ("A", 1), ("B", 1)], names=["a", "b"] - ) + index = MultiIndex.from_tuples([("A", 0), ("A", 1), ("B", 1)], names=["a", "b"]) df = DataFrame( { "A": pd.core.arrays.integer_array([0, 1, None]), @@ -1101,13 +1099,13 @@ def test_unstack_mixed_extension_types(self, level): @pytest.mark.parametrize("level", [0, "baz"]) def test_unstack_swaplevel_sortlevel(self, level): # GH 20994 - mi = pd.MultiIndex.from_product([[0], ["d", "c"]], names=["bar", "baz"]) + mi = MultiIndex.from_product([[0], ["d", "c"]], names=["bar", "baz"]) df = DataFrame([[0, 2], [1, 3]], index=mi, columns=["B", "A"]) df.columns.name = "foo" expected = DataFrame( [[3, 1, 2, 0]], - columns=pd.MultiIndex.from_tuples( + columns=MultiIndex.from_tuples( [("c", "A"), ("c", "B"), ("d", "A"), ("d", "B")], names=["baz", "foo"] ), ) @@ -1120,7 +1118,7 @@ def test_unstack_swaplevel_sortlevel(self, level): def test_unstack_fill_frame_object(): # GH12815 Test unstacking with object. data = Series(["a", "b", "c", "a"], dtype="object") - data.index = pd.MultiIndex.from_tuples( + data.index = MultiIndex.from_tuples( [("x", "a"), ("x", "b"), ("y", "b"), ("z", "a")] ) @@ -1154,7 +1152,7 @@ def test_unstack_timezone_aware_values(): expected = DataFrame( [[pd.Timestamp("2017-08-27 01:00:00.709949+0000", tz="UTC"), "c"]], index=Index(["a"], name="a"), - columns=pd.MultiIndex( + columns=MultiIndex( levels=[["timestamp", "c"], ["b"]], codes=[[0, 1], [0, 0]], names=[None, "b"], @@ -1172,9 +1170,7 @@ def test_stack_timezone_aware_values(): result = df.stack() expected = Series( ts, - index=pd.MultiIndex( - levels=[["a", "b", "c"], ["A"]], codes=[[0, 1, 2], [0, 0, 0]] - ), + index=MultiIndex(levels=[["a", "b", "c"], ["A"]], codes=[[0, 1, 2], [0, 0, 0]]), ) tm.assert_series_equal(result, expected) @@ -1212,12 +1208,12 @@ def test_unstacking_multi_index_df(): def test_stack_positional_level_duplicate_column_names(): # https://github.com/pandas-dev/pandas/issues/36353 - columns = pd.MultiIndex.from_product([("x", "y"), ("y", "z")], names=["a", "a"]) + columns = MultiIndex.from_product([("x", "y"), ("y", "z")], names=["a", "a"]) df = DataFrame([[1, 1, 1, 1]], columns=columns) result = df.stack(0) new_columns = Index(["y", "z"], name="a") - new_index = pd.MultiIndex.from_tuples([(0, "x"), (0, "y")], names=[None, "a"]) + new_index = MultiIndex.from_tuples([(0, "x"), (0, "y")], names=[None, "a"]) expected = DataFrame([[1, 1], [1, 1]], index=new_index, columns=new_columns) tm.assert_frame_equal(result, expected) @@ -1273,7 +1269,7 @@ def test_unstack_partial( result = result.iloc[1:2].unstack("ix2") expected = DataFrame( [expected_row], - columns=pd.MultiIndex.from_product( + columns=MultiIndex.from_product( [result_columns[2:], [index_product]], names=[None, "ix2"] ), index=Index([2], name="ix1"), diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index a7c22b4983ed7..151ec03662335 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -898,7 +898,7 @@ def test_apply_multi_level_name(category): def test_groupby_apply_datetime_result_dtypes(): # GH 14849 - data = pd.DataFrame.from_records( + data = DataFrame.from_records( [ (pd.Timestamp(2016, 1, 1), "red", "dark", 1, "8"), (pd.Timestamp(2015, 1, 1), "green", "stormy", 2, "9"), diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index c29c9e15ada79..8271d0c45313d 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -469,13 +469,13 @@ def test_observed_groups_with_nan(observed): def test_observed_nth(): # GH 26385 - cat = pd.Categorical(["a", np.nan, np.nan], categories=["a", "b", "c"]) + cat = Categorical(["a", np.nan, np.nan], categories=["a", "b", "c"]) ser = Series([1, 2, 3]) df = DataFrame({"cat": cat, "ser": ser}) result = df.groupby("cat", observed=False)["ser"].nth(0) - index = pd.Categorical(["a", "b", "c"], categories=["a", "b", "c"]) + index = Categorical(["a", "b", "c"], categories=["a", "b", "c"]) expected = Series([1, np.nan, np.nan], index=index, name="ser") expected.index.name = "cat" @@ -767,7 +767,7 @@ def test_preserve_categorical_dtype(): def test_preserve_on_ordered_ops(func, values): # gh-18502 # preserve the categoricals on ops - c = pd.Categorical(["first", "second", "third", "fourth"], ordered=True) + c = Categorical(["first", "second", "third", "fourth"], ordered=True) df = DataFrame({"payload": [-1, -2, -1, -2], "col": c}) g = df.groupby("payload") result = getattr(g, func)() @@ -818,10 +818,10 @@ def test_groupby_empty_with_category(): # GH-9614 # test fix for when group by on None resulted in # coercion of dtype categorical -> float - df = DataFrame({"A": [None] * 3, "B": pd.Categorical(["train", "train", "test"])}) + df = DataFrame({"A": [None] * 3, "B": Categorical(["train", "train", "test"])}) result = df.groupby("A").first()["B"] expected = Series( - pd.Categorical([], categories=["test", "train"]), + Categorical([], categories=["test", "train"]), index=Series([], dtype="object", name="A"), name="B", ) @@ -1253,7 +1253,7 @@ def test_groupby_categorical_series_dataframe_consistent(df_cat): def test_groupby_categorical_axis_1(code): # GH 13420 df = DataFrame({"a": [1, 2, 3, 4], "b": [-1, -2, -3, -4], "c": [5, 6, 7, 8]}) - cat = pd.Categorical.from_codes(code, categories=list("abc")) + cat = Categorical.from_codes(code, categories=list("abc")) result = df.groupby(cat, axis=1).mean() expected = df.T.groupby(cat, axis=0).mean().T tm.assert_frame_equal(result, expected) @@ -1269,7 +1269,7 @@ def test_groupby_cat_preserves_structure(observed, ordered): result = ( df.groupby("Name", observed=observed) - .agg(pd.DataFrame.sum, skipna=True) + .agg(DataFrame.sum, skipna=True) .reset_index() ) @@ -1300,8 +1300,8 @@ def test_series_groupby_on_2_categoricals_unobserved(reduction_func, observed, r df = DataFrame( { - "cat_1": pd.Categorical(list("AABB"), categories=list("ABCD")), - "cat_2": pd.Categorical(list("AB") * 2, categories=list("ABCD")), + "cat_1": Categorical(list("AABB"), categories=list("ABCD")), + "cat_2": Categorical(list("AB") * 2, categories=list("ABCD")), "value": [0.1] * 4, } ) @@ -1333,8 +1333,8 @@ def test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans( df = DataFrame( { - "cat_1": pd.Categorical(list("AABB"), categories=list("ABC")), - "cat_2": pd.Categorical(list("AB") * 2, categories=list("ABC")), + "cat_1": Categorical(list("AABB"), categories=list("ABC")), + "cat_2": Categorical(list("AB") * 2, categories=list("ABC")), "value": [0.1] * 4, } ) @@ -1362,15 +1362,15 @@ def test_series_groupby_on_2_categoricals_unobserved_zeroes_or_nans( def test_dataframe_groupby_on_2_categoricals_when_observed_is_true(reduction_func): # GH 23865 # GH 27075 - # Ensure that df.groupby, when 'by' is two pd.Categorical variables, + # Ensure that df.groupby, when 'by' is two Categorical variables, # does not return the categories that are not in df when observed=True if reduction_func == "ngroup": pytest.skip("ngroup does not return the Categories on the index") df = DataFrame( { - "cat_1": pd.Categorical(list("AABB"), categories=list("ABC")), - "cat_2": pd.Categorical(list("1111"), categories=list("12")), + "cat_1": Categorical(list("AABB"), categories=list("ABC")), + "cat_2": Categorical(list("1111"), categories=list("12")), "value": [0.1, 0.1, 0.1, 0.1], } ) @@ -1391,7 +1391,7 @@ def test_dataframe_groupby_on_2_categoricals_when_observed_is_false( ): # GH 23865 # GH 27075 - # Ensure that df.groupby, when 'by' is two pd.Categorical variables, + # Ensure that df.groupby, when 'by' is two Categorical variables, # returns the categories that are not in df when observed=False/None if reduction_func == "ngroup": @@ -1399,8 +1399,8 @@ def test_dataframe_groupby_on_2_categoricals_when_observed_is_false( df = DataFrame( { - "cat_1": pd.Categorical(list("AABB"), categories=list("ABC")), - "cat_2": pd.Categorical(list("1111"), categories=list("12")), + "cat_1": Categorical(list("AABB"), categories=list("ABC")), + "cat_2": Categorical(list("1111"), categories=list("12")), "value": [0.1, 0.1, 0.1, 0.1], } ) @@ -1433,7 +1433,7 @@ def test_series_groupby_categorical_aggregation_getitem(): @pytest.mark.parametrize( "func, expected_values", - [(pd.Series.nunique, [1, 1, 2]), (pd.Series.count, [1, 2, 2])], + [(Series.nunique, [1, 1, 2]), (Series.count, [1, 2, 2])], ) def test_groupby_agg_categorical_columns(func, expected_values): # 31256 @@ -1441,7 +1441,7 @@ def test_groupby_agg_categorical_columns(func, expected_values): { "id": [0, 1, 2, 3, 4], "groups": [0, 1, 1, 2, 2], - "value": pd.Categorical([0, 0, 0, 0, 1]), + "value": Categorical([0, 0, 0, 0, 1]), } ).set_index("id") result = df.groupby("groups").agg(func) @@ -1453,10 +1453,10 @@ def test_groupby_agg_categorical_columns(func, expected_values): def test_groupby_agg_non_numeric(): - df = DataFrame({"A": pd.Categorical(["a", "a", "b"], categories=["a", "b", "c"])}) + df = DataFrame({"A": Categorical(["a", "a", "b"], categories=["a", "b", "c"])}) expected = DataFrame({"A": [2, 1]}, index=[1, 2]) - result = df.groupby([1, 2, 1]).agg(pd.Series.nunique) + result = df.groupby([1, 2, 1]).agg(Series.nunique) tm.assert_frame_equal(result, expected) result = df.groupby([1, 2, 1]).nunique() @@ -1518,7 +1518,7 @@ def test_sorted_missing_category_values(): } ) expected = expected.rename_axis("bar", axis="index") - expected.columns = pd.CategoricalIndex( + expected.columns = CategoricalIndex( ["tiny", "small", "medium", "large"], categories=["tiny", "small", "medium", "large"], ordered=True, @@ -1637,11 +1637,11 @@ def test_series_groupby_first_on_categorical_col_grouped_on_2_categoricals( func: str, observed: bool ): # GH 34951 - cat = pd.Categorical([0, 0, 1, 1]) + cat = Categorical([0, 0, 1, 1]) val = [0, 1, 1, 0] df = DataFrame({"a": cat, "b": cat, "c": val}) - idx = pd.Categorical([0, 1]) + idx = Categorical([0, 1]) idx = pd.MultiIndex.from_product([idx, idx], names=["a", "b"]) expected_dict = { "first": Series([0, np.NaN, np.NaN, 1], idx, name="c"), @@ -1662,11 +1662,11 @@ def test_df_groupby_first_on_categorical_col_grouped_on_2_categoricals( func: str, observed: bool ): # GH 34951 - cat = pd.Categorical([0, 0, 1, 1]) + cat = Categorical([0, 0, 1, 1]) val = [0, 1, 1, 0] df = DataFrame({"a": cat, "b": cat, "c": val}) - idx = pd.Categorical([0, 1]) + idx = Categorical([0, 1]) idx = pd.MultiIndex.from_product([idx, idx], names=["a", "b"]) expected_dict = { "first": Series([0, np.NaN, np.NaN, 1], idx, name="c"), diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 05a959ea6f22b..e49e69a39b315 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -186,12 +186,12 @@ def test_arg_passthru(): "timedelta": [pd.Timedelta("1.5s"), pd.Timedelta("3s")], "int": [1.5, 3], "datetime": [ - pd.Timestamp("2013-01-01 12:00:00"), - pd.Timestamp("2013-01-03 00:00:00"), + Timestamp("2013-01-01 12:00:00"), + Timestamp("2013-01-03 00:00:00"), ], "datetimetz": [ - pd.Timestamp("2013-01-01 12:00:00", tz="US/Eastern"), - pd.Timestamp("2013-01-03 00:00:00", tz="US/Eastern"), + Timestamp("2013-01-01 12:00:00", tz="US/Eastern"), + Timestamp("2013-01-03 00:00:00", tz="US/Eastern"), ], }, index=Index([1, 2], name="group"), @@ -916,14 +916,14 @@ def test_frame_describe_tupleindex(): def test_frame_describe_unstacked_format(): # GH 4792 prices = { - pd.Timestamp("2011-01-06 10:59:05", tz=None): 24990, - pd.Timestamp("2011-01-06 12:43:33", tz=None): 25499, - pd.Timestamp("2011-01-06 12:54:09", tz=None): 25499, + Timestamp("2011-01-06 10:59:05", tz=None): 24990, + Timestamp("2011-01-06 12:43:33", tz=None): 25499, + Timestamp("2011-01-06 12:54:09", tz=None): 25499, } volumes = { - pd.Timestamp("2011-01-06 10:59:05", tz=None): 1500000000, - pd.Timestamp("2011-01-06 12:43:33", tz=None): 5000000000, - pd.Timestamp("2011-01-06 12:54:09", tz=None): 100000000, + Timestamp("2011-01-06 10:59:05", tz=None): 1500000000, + Timestamp("2011-01-06 12:43:33", tz=None): 5000000000, + Timestamp("2011-01-06 12:54:09", tz=None): 100000000, } df = DataFrame({"PRICE": prices, "VOLUME": volumes}) result = df.groupby("PRICE").VOLUME.describe() @@ -957,7 +957,7 @@ def test_describe_with_duplicate_output_column_names(as_index): ) expected = ( - pd.DataFrame.from_records( + DataFrame.from_records( [ ("a", "count", 3.0, 3.0), ("a", "mean", 88.0, 99.0), diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index b57fa2540add9..2563eeeb68672 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -601,7 +601,7 @@ def test_as_index_select_column(): result = df.groupby("A", as_index=False)["B"].apply(lambda x: x.cumsum()) expected = Series( - [2, 6, 6], name="B", index=pd.MultiIndex.from_tuples([(0, 0), (0, 1), (1, 2)]) + [2, 6, 6], name="B", index=MultiIndex.from_tuples([(0, 0), (0, 1), (1, 2)]) ) tm.assert_series_equal(result, expected) @@ -1190,7 +1190,7 @@ def test_groupby_unit64_float_conversion(): result = df.groupby(["first", "second"])["value"].max() expected = Series( [16148277970000000000], - pd.MultiIndex.from_product([[1], [1]], names=["first", "second"]), + MultiIndex.from_product([[1], [1]], names=["first", "second"]), name="value", ) tm.assert_series_equal(result, expected) @@ -1215,7 +1215,7 @@ def test_groupby_keys_same_size_as_index(): # GH 11185 freq = "s" index = pd.date_range( - start=pd.Timestamp("2015-09-29T11:34:44-0700"), periods=2, freq=freq + start=Timestamp("2015-09-29T11:34:44-0700"), periods=2, freq=freq ) df = DataFrame([["A", 10], ["B", 15]], columns=["metric", "values"], index=index) result = df.groupby([pd.Grouper(level=0, freq=freq), "metric"]).mean() @@ -1242,13 +1242,13 @@ def test_groupby_nat_exclude(): "values": np.random.randn(8), "dt": [ np.nan, - pd.Timestamp("2013-01-01"), + Timestamp("2013-01-01"), np.nan, - pd.Timestamp("2013-02-01"), + Timestamp("2013-02-01"), np.nan, - pd.Timestamp("2013-02-01"), + Timestamp("2013-02-01"), np.nan, - pd.Timestamp("2013-01-01"), + Timestamp("2013-01-01"), ], "str": [np.nan, "a", np.nan, "a", np.nan, "a", np.nan, "b"], } @@ -1724,7 +1724,7 @@ def test_group_shift_with_fill_value(): def test_group_shift_lose_timezone(): # GH 30134 - now_dt = pd.Timestamp.utcnow() + now_dt = Timestamp.utcnow() df = DataFrame({"a": [1, 1], "date": now_dt}) result = df.groupby("a").shift(0).iloc[0] expected = Series({"date": now_dt}, name=result.name) @@ -1781,9 +1781,7 @@ def test_tuple_as_grouping(): def test_tuple_correct_keyerror(): # https://github.com/pandas-dev/pandas/issues/18798 - df = DataFrame( - 1, index=range(3), columns=pd.MultiIndex.from_product([[1, 2], [3, 4]]) - ) + df = DataFrame(1, index=range(3), columns=MultiIndex.from_product([[1, 2], [3, 4]])) with pytest.raises(KeyError, match=r"^\(7, 8\)$"): df.groupby((7, 8)).mean() @@ -1798,7 +1796,7 @@ def test_groupby_agg_ohlc_non_first(): expected = DataFrame( [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]], - columns=pd.MultiIndex.from_tuples( + columns=MultiIndex.from_tuples( ( ("foo", "sum", "foo"), ("foo", "ohlc", "open"), @@ -1823,7 +1821,7 @@ def test_groupby_multiindex_nat(): (datetime(2012, 1, 2), "b"), (datetime(2012, 1, 3), "a"), ] - mi = pd.MultiIndex.from_tuples(values, names=["date", None]) + mi = MultiIndex.from_tuples(values, names=["date", None]) ser = Series([3, 2, 2.5, 4], index=mi) result = ser.groupby(level=1).mean() @@ -1844,13 +1842,13 @@ def test_groupby_multiindex_series_keys_len_equal_group_axis(): # GH 25704 index_array = [["x", "x"], ["a", "b"], ["k", "k"]] index_names = ["first", "second", "third"] - ri = pd.MultiIndex.from_arrays(index_array, names=index_names) + ri = MultiIndex.from_arrays(index_array, names=index_names) s = Series(data=[1, 2], index=ri) result = s.groupby(["first", "third"]).sum() index_array = [["x"], ["k"]] index_names = ["first", "third"] - ei = pd.MultiIndex.from_arrays(index_array, names=index_names) + ei = MultiIndex.from_arrays(index_array, names=index_names) expected = Series([3], index=ei) tm.assert_series_equal(result, expected) @@ -1859,7 +1857,7 @@ def test_groupby_multiindex_series_keys_len_equal_group_axis(): def test_groupby_groups_in_BaseGrouper(): # GH 26326 # Test if DataFrame grouped with a pandas.Grouper has correct groups - mi = pd.MultiIndex.from_product([["A", "B"], ["C", "D"]], names=["alpha", "beta"]) + mi = MultiIndex.from_product([["A", "B"], ["C", "D"]], names=["alpha", "beta"]) df = DataFrame({"foo": [1, 2, 1, 2], "bar": [1, 2, 3, 4]}, index=mi) result = df.groupby([pd.Grouper(level="alpha"), "beta"]) expected = df.groupby(["alpha", "beta"]) @@ -1885,7 +1883,7 @@ def test_groupby_axis_1(group_name): # test on MI column iterables = [["bar", "baz", "foo"], ["one", "two"]] - mi = pd.MultiIndex.from_product(iterables=iterables, names=["x", "x1"]) + mi = MultiIndex.from_product(iterables=iterables, names=["x", "x1"]) df = DataFrame(np.arange(18).reshape(3, 6), index=[0, 1, 0], columns=mi) results = df.groupby(group_name, axis=1).sum() expected = df.T.groupby(group_name).sum().T @@ -1990,7 +1988,7 @@ def test_bool_aggs_dup_column_labels(bool_agg_func): @pytest.mark.parametrize( - "idx", [Index(["a", "a"]), pd.MultiIndex.from_tuples((("a", "a"), ("a", "a")))] + "idx", [Index(["a", "a"]), MultiIndex.from_tuples((("a", "a"), ("a", "a")))] ) @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_dup_labels_output_shape(groupby_func, idx): @@ -2006,7 +2004,7 @@ def test_dup_labels_output_shape(groupby_func, idx): elif groupby_func == "corrwith": args.append(df) elif groupby_func == "tshift": - df.index = [pd.Timestamp("today")] + df.index = [Timestamp("today")] args.extend([1, "D"]) result = getattr(grp_by, groupby_func)(*args) diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 6c74e1521eeeb..1cacc5bb5ca6e 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -157,7 +157,7 @@ def test_grouper_multilevel_freq(self): d0 = date.today() - timedelta(days=14) dates = date_range(d0, date.today()) - date_index = pd.MultiIndex.from_product([dates, dates], names=["foo", "bar"]) + date_index = MultiIndex.from_product([dates, dates], names=["foo", "bar"]) df = DataFrame(np.random.randint(0, 100, 225), index=date_index) # Check string level @@ -233,7 +233,7 @@ def test_grouper_creation_bug(self): # GH8866 s = Series( np.arange(8, dtype="int64"), - index=pd.MultiIndex.from_product( + index=MultiIndex.from_product( [list("ab"), range(2), date_range("20130101", periods=2)], names=["one", "two", "three"], ), @@ -254,7 +254,7 @@ def test_grouper_column_and_index(self): # Grouping a multi-index frame by a column and an index level should # be equivalent to resetting the index and grouping by two columns - idx = pd.MultiIndex.from_tuples( + idx = MultiIndex.from_tuples( [("a", 1), ("a", 2), ("a", 3), ("b", 1), ("b", 2), ("b", 3)] ) idx.names = ["outer", "inner"] @@ -286,9 +286,7 @@ def test_grouper_column_and_index(self): def test_groupby_levels_and_columns(self): # GH9344, GH9049 idx_names = ["x", "y"] - idx = pd.MultiIndex.from_tuples( - [(1, 1), (1, 2), (3, 4), (5, 6)], names=idx_names - ) + idx = MultiIndex.from_tuples([(1, 1), (1, 2), (3, 4), (5, 6)], names=idx_names) df = DataFrame(np.arange(12).reshape(-1, 3), index=idx) by_levels = df.groupby(level=idx_names).mean() @@ -330,7 +328,7 @@ def test_grouper_getting_correct_binner(self): # and specifying levels df = DataFrame( {"A": 1}, - index=pd.MultiIndex.from_product( + index=MultiIndex.from_product( [list("ab"), date_range("20130101", periods=80)], names=["one", "two"] ), ) @@ -408,7 +406,7 @@ def test_multiindex_passthru(self): # GH 7997 # regression from 0.14.1 df = DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) - df.columns = pd.MultiIndex.from_tuples([(0, 1), (1, 1), (2, 1)]) + df.columns = MultiIndex.from_tuples([(0, 1), (1, 1), (2, 1)]) result = df.groupby(axis=1, level=[0, 1]).first() tm.assert_frame_equal(result, df) @@ -465,7 +463,7 @@ def test_groupby_multiindex_tuple(self): # GH 17979 df = DataFrame( [[1, 2, 3, 4], [3, 4, 5, 6], [1, 4, 2, 3]], - columns=pd.MultiIndex.from_arrays([["a", "b", "b", "c"], [1, 1, 2, 2]]), + columns=MultiIndex.from_arrays([["a", "b", "b", "c"], [1, 1, 2, 2]]), ) expected = df.groupby([("b", 1)]).groups result = df.groupby(("b", 1)).groups @@ -473,7 +471,7 @@ def test_groupby_multiindex_tuple(self): df2 = DataFrame( df.values, - columns=pd.MultiIndex.from_arrays( + columns=MultiIndex.from_arrays( [["a", "b", "b", "c"], ["d", "d", "e", "e"]] ), ) diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py index e82b23054f1cb..df1d7819a1894 100644 --- a/pandas/tests/groupby/test_nth.py +++ b/pandas/tests/groupby/test_nth.py @@ -94,7 +94,7 @@ def test_nth_with_na_object(index, nulls_fixture): def test_first_last_with_None(method): # https://github.com/pandas-dev/pandas/issues/32800 # None should be preserved as object dtype - df = pd.DataFrame.from_dict({"id": ["a"], "value": [None]}) + df = DataFrame.from_dict({"id": ["a"], "value": [None]}) groups = df.groupby("id", as_index=False) result = getattr(groups, method)() @@ -152,8 +152,8 @@ def test_first_strings_timestamps(): # GH 11244 test = DataFrame( { - pd.Timestamp("2012-01-01 00:00:00"): ["a", "b"], - pd.Timestamp("2012-01-02 00:00:00"): ["c", "d"], + Timestamp("2012-01-01 00:00:00"): ["a", "b"], + Timestamp("2012-01-02 00:00:00"): ["c", "d"], "name": ["e", "e"], "aaaa": ["f", "g"], } diff --git a/pandas/tests/groupby/test_nunique.py b/pandas/tests/groupby/test_nunique.py index 7edb358170b50..22970eff28f19 100644 --- a/pandas/tests/groupby/test_nunique.py +++ b/pandas/tests/groupby/test_nunique.py @@ -121,7 +121,7 @@ def test_nunique_with_timegrouper(): } ).set_index("time") result = test.groupby(pd.Grouper(freq="h"))["data"].nunique() - expected = test.groupby(pd.Grouper(freq="h"))["data"].apply(pd.Series.nunique) + expected = test.groupby(pd.Grouper(freq="h"))["data"].apply(Series.nunique) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/groupby/test_timegrouper.py b/pandas/tests/groupby/test_timegrouper.py index 0a1232d3f24da..612079447576f 100644 --- a/pandas/tests/groupby/test_timegrouper.py +++ b/pandas/tests/groupby/test_timegrouper.py @@ -363,7 +363,7 @@ def test_timegrouper_get_group(self): for df in [df_original, df_reordered]: grouped = df.groupby(pd.Grouper(freq="M", key="Date")) for t, expected in zip(dt_list, expected_list): - dt = pd.Timestamp(t) + dt = Timestamp(t) result = grouped.get_group(dt) tm.assert_frame_equal(result, expected) @@ -378,7 +378,7 @@ def test_timegrouper_get_group(self): for df in [df_original, df_reordered]: grouped = df.groupby(["Buyer", pd.Grouper(freq="M", key="Date")]) for (b, t), expected in zip(g_list, expected_list): - dt = pd.Timestamp(t) + dt = Timestamp(t) result = grouped.get_group((b, dt)) tm.assert_frame_equal(result, expected) @@ -395,7 +395,7 @@ def test_timegrouper_get_group(self): for df in [df_original, df_reordered]: grouped = df.groupby(pd.Grouper(freq="M")) for t, expected in zip(dt_list, expected_list): - dt = pd.Timestamp(t) + dt = Timestamp(t) result = grouped.get_group(dt) tm.assert_frame_equal(result, expected) @@ -452,7 +452,7 @@ def test_groupby_groups_datetimeindex(self): result = df.groupby(level="date").groups dates = ["2015-01-05", "2015-01-04", "2015-01-03", "2015-01-02", "2015-01-01"] expected = { - pd.Timestamp(date): pd.DatetimeIndex([date], name="date") for date in dates + Timestamp(date): pd.DatetimeIndex([date], name="date") for date in dates } tm.assert_dict_equal(result, expected) @@ -662,9 +662,9 @@ def test_groupby_datetime64_32_bit(self): # GH 6410 / numpy 4328 # 32-bit under 1.9-dev indexing issue - df = DataFrame({"A": range(2), "B": [pd.Timestamp("2000-01-1")] * 2}) + df = DataFrame({"A": range(2), "B": [Timestamp("2000-01-1")] * 2}) result = df.groupby("A")["B"].transform(min) - expected = Series([pd.Timestamp("2000-01-1")] * 2, name="B") + expected = Series([Timestamp("2000-01-1")] * 2, name="B") tm.assert_series_equal(result, expected) def test_groupby_with_timezone_selection(self): diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index cd3c2771db8a4..1aeff7426c33a 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -106,10 +106,10 @@ def test_transform_fast(): result = df.groupby("grouping").transform("first") dates = [ - pd.Timestamp("2014-1-1"), - pd.Timestamp("2014-1-2"), - pd.Timestamp("2014-1-2"), - pd.Timestamp("2014-1-4"), + Timestamp("2014-1-1"), + Timestamp("2014-1-2"), + Timestamp("2014-1-2"), + Timestamp("2014-1-4"), ] expected = DataFrame( {"f": [1.1, 2.1, 2.1, 4.5], "d": dates, "i": [1, 2, 2, 4]}, @@ -393,9 +393,9 @@ def test_series_fast_transform_date(): result = df.groupby("grouping")["d"].transform("first") dates = [ pd.NaT, - pd.Timestamp("2014-1-2"), - pd.Timestamp("2014-1-2"), - pd.Timestamp("2014-1-4"), + Timestamp("2014-1-2"), + Timestamp("2014-1-2"), + Timestamp("2014-1-4"), ] expected = Series(dates, name="d") tm.assert_series_equal(result, expected) diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index 2bfe9bf0194ec..cf2430d041d88 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -42,7 +42,7 @@ def test_can_hold_identifiers(self): def test_disallow_addsub_ops(self, func, op_name): # GH 10039 # set ops (+/-) raise TypeError - idx = Index(pd.Categorical(["a", "b"])) + idx = Index(Categorical(["a", "b"])) cat_or_list = "'(Categorical|list)' and '(Categorical|list)'" msg = "|".join( [ @@ -182,7 +182,7 @@ def test_insert(self): tm.assert_index_equal(result, expected) def test_insert_na_mismatched_dtype(self): - ci = pd.CategoricalIndex([0, 1, 1]) + ci = CategoricalIndex([0, 1, 1]) msg = "'fill_value=NaT' is not present in this Categorical's categories" with pytest.raises(ValueError, match=msg): ci.insert(0, pd.NaT) @@ -437,15 +437,15 @@ def test_equals_categorical(self): def test_equals_categorical_unordered(self): # https://github.com/pandas-dev/pandas/issues/16603 - a = pd.CategoricalIndex(["A"], categories=["A", "B"]) - b = pd.CategoricalIndex(["A"], categories=["B", "A"]) - c = pd.CategoricalIndex(["C"], categories=["B", "A"]) + a = CategoricalIndex(["A"], categories=["A", "B"]) + b = CategoricalIndex(["A"], categories=["B", "A"]) + c = CategoricalIndex(["C"], categories=["B", "A"]) assert a.equals(b) assert not a.equals(c) assert not b.equals(c) def test_frame_repr(self): - df = pd.DataFrame({"A": [1, 2, 3]}, index=pd.CategoricalIndex(["a", "b", "c"])) + df = pd.DataFrame({"A": [1, 2, 3]}, index=CategoricalIndex(["a", "b", "c"])) result = repr(df) expected = " A\na 1\nb 2\nc 3" assert result == expected @@ -464,11 +464,11 @@ def test_engine_type(self, dtype, engine_type): # num. of uniques required to push CategoricalIndex.codes to a # dtype (128 categories required for .codes dtype to be int16 etc.) num_uniques = {np.int8: 1, np.int16: 128, np.int32: 32768}[dtype] - ci = pd.CategoricalIndex(range(num_uniques)) + ci = CategoricalIndex(range(num_uniques)) else: # having 2**32 - 2**31 categories would be very memory-intensive, # so we cheat a bit with the dtype - ci = pd.CategoricalIndex(range(32768)) # == 2**16 - 2**(16 - 1) + ci = CategoricalIndex(range(32768)) # == 2**16 - 2**(16 - 1) ci.values._codes = ci.values._codes.astype("int64") assert np.issubdtype(ci.codes.dtype, dtype) assert isinstance(ci._engine, engine_type) diff --git a/pandas/tests/indexes/categorical/test_indexing.py b/pandas/tests/indexes/categorical/test_indexing.py index c720547aab3f8..3aa8710c6a6c8 100644 --- a/pandas/tests/indexes/categorical/test_indexing.py +++ b/pandas/tests/indexes/categorical/test_indexing.py @@ -355,7 +355,7 @@ def test_contains_na_dtype(self, unwrap): (1.5, True), (pd.Interval(0.5, 1.5), False), ("a", False), - (pd.Timestamp(1), False), + (Timestamp(1), False), (pd.Timedelta(1), False), ], ids=str, diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/test_astype.py index 13b658b31e3ee..ad9a2f112caac 100644 --- a/pandas/tests/indexes/datetimes/test_astype.py +++ b/pandas/tests/indexes/datetimes/test_astype.py @@ -268,9 +268,9 @@ def _check_rng(rng): ) def test_integer_index_astype_datetime(self, tz, dtype): # GH 20997, 20964, 24559 - val = [pd.Timestamp("2018-01-01", tz=tz).value] + val = [Timestamp("2018-01-01", tz=tz).value] result = Index(val, name="idx").astype(dtype) - expected = pd.DatetimeIndex(["2018-01-01"], tz=tz, name="idx") + expected = DatetimeIndex(["2018-01-01"], tz=tz, name="idx") tm.assert_index_equal(result, expected) def test_dti_astype_period(self): @@ -291,7 +291,7 @@ def test_astype_category(self, tz): obj = pd.date_range("2000", periods=2, tz=tz, name="idx") result = obj.astype("category") expected = pd.CategoricalIndex( - [pd.Timestamp("2000-01-01", tz=tz), pd.Timestamp("2000-01-02", tz=tz)], + [Timestamp("2000-01-01", tz=tz), Timestamp("2000-01-02", tz=tz)], name="idx", ) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index 0c562e7b8f848..48f87664d5141 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -27,9 +27,9 @@ def test_freq_validation_with_nat(self, dt_cls): "to passed frequency D" ) with pytest.raises(ValueError, match=msg): - dt_cls([pd.NaT, pd.Timestamp("2011-01-01")], freq="D") + dt_cls([pd.NaT, Timestamp("2011-01-01")], freq="D") with pytest.raises(ValueError, match=msg): - dt_cls([pd.NaT, pd.Timestamp("2011-01-01").value], freq="D") + dt_cls([pd.NaT, Timestamp("2011-01-01").value], freq="D") # TODO: better place for tests shared by DTI/TDI? @pytest.mark.parametrize( @@ -55,7 +55,7 @@ def test_categorical_preserves_tz(self): # TODO: parametrize over DatetimeIndex/DatetimeArray # once CategoricalIndex(DTA) works - dti = pd.DatetimeIndex( + dti = DatetimeIndex( [pd.NaT, "2015-01-01", "1999-04-06 15:14:13", "2015-01-01"], tz="US/Eastern" ) @@ -64,7 +64,7 @@ def test_categorical_preserves_tz(self): cser = pd.Series(ci) for obj in [ci, carr, cser]: - result = pd.DatetimeIndex(obj) + result = DatetimeIndex(obj) tm.assert_index_equal(result, dti) def test_dti_with_period_data_raises(self): @@ -106,9 +106,9 @@ def test_construction_caching(self): "dt": pd.date_range("20130101", periods=3), "dttz": pd.date_range("20130101", periods=3, tz="US/Eastern"), "dt_with_null": [ - pd.Timestamp("20130101"), + Timestamp("20130101"), pd.NaT, - pd.Timestamp("20130103"), + Timestamp("20130103"), ], "dtns": pd.date_range("20130101", periods=3, freq="ns"), } @@ -463,13 +463,13 @@ def test_construction_dti_with_mixed_timezones(self): ) def test_construction_base_constructor(self): - arr = [pd.Timestamp("2011-01-01"), pd.NaT, pd.Timestamp("2011-01-03")] - tm.assert_index_equal(Index(arr), pd.DatetimeIndex(arr)) - tm.assert_index_equal(Index(np.array(arr)), pd.DatetimeIndex(np.array(arr))) + arr = [Timestamp("2011-01-01"), pd.NaT, Timestamp("2011-01-03")] + tm.assert_index_equal(Index(arr), DatetimeIndex(arr)) + tm.assert_index_equal(Index(np.array(arr)), DatetimeIndex(np.array(arr))) - arr = [np.nan, pd.NaT, pd.Timestamp("2011-01-03")] - tm.assert_index_equal(Index(arr), pd.DatetimeIndex(arr)) - tm.assert_index_equal(Index(np.array(arr)), pd.DatetimeIndex(np.array(arr))) + arr = [np.nan, pd.NaT, Timestamp("2011-01-03")] + tm.assert_index_equal(Index(arr), DatetimeIndex(arr)) + tm.assert_index_equal(Index(np.array(arr)), DatetimeIndex(np.array(arr))) def test_construction_outofbounds(self): # GH 13663 @@ -503,13 +503,13 @@ def test_integer_values_and_tz_interpreted_as_utc(self): result = DatetimeIndex(values).tz_localize("US/Central") - expected = pd.DatetimeIndex(["2000-01-01T00:00:00"], tz="US/Central") + expected = DatetimeIndex(["2000-01-01T00:00:00"], tz="US/Central") tm.assert_index_equal(result, expected) # but UTC is *not* deprecated. with tm.assert_produces_warning(None): result = DatetimeIndex(values, tz="UTC") - expected = pd.DatetimeIndex(["2000-01-01T00:00:00"], tz="US/Central") + expected = DatetimeIndex(["2000-01-01T00:00:00"], tz="US/Central") def test_constructor_coverage(self): rng = date_range("1/1/2000", periods=10.5) @@ -755,15 +755,15 @@ def test_construction_int_rountrip(self, tz_naive_fixture): def test_construction_from_replaced_timestamps_with_dst(self): # GH 18785 index = pd.date_range( - pd.Timestamp(2000, 1, 1), - pd.Timestamp(2005, 1, 1), + Timestamp(2000, 1, 1), + Timestamp(2005, 1, 1), freq="MS", tz="Australia/Melbourne", ) test = pd.DataFrame({"data": range(len(index))}, index=index) test = test.resample("Y").mean() - result = pd.DatetimeIndex([x.replace(month=6, day=1) for x in test.index]) - expected = pd.DatetimeIndex( + result = DatetimeIndex([x.replace(month=6, day=1) for x in test.index]) + expected = DatetimeIndex( [ "2000-06-01 00:00:00", "2001-06-01 00:00:00", @@ -801,7 +801,7 @@ def test_constructor_with_ambiguous_keyword_arg(self): # ambiguous keyword in start timezone = "America/New_York" - start = pd.Timestamp(year=2020, month=11, day=1, hour=1).tz_localize( + start = Timestamp(year=2020, month=11, day=1, hour=1).tz_localize( timezone, ambiguous=False ) result = pd.date_range(start=start, periods=2, ambiguous=False) @@ -809,7 +809,7 @@ def test_constructor_with_ambiguous_keyword_arg(self): # ambiguous keyword in end timezone = "America/New_York" - end = pd.Timestamp(year=2020, month=11, day=2, hour=1).tz_localize( + end = Timestamp(year=2020, month=11, day=2, hour=1).tz_localize( timezone, ambiguous=False ) result = pd.date_range(end=end, periods=2, ambiguous=False) @@ -821,28 +821,28 @@ def test_constructor_with_nonexistent_keyword_arg(self): timezone = "Europe/Warsaw" # nonexistent keyword in start - start = pd.Timestamp("2015-03-29 02:30:00").tz_localize( + start = Timestamp("2015-03-29 02:30:00").tz_localize( timezone, nonexistent="shift_forward" ) result = pd.date_range(start=start, periods=2, freq="H") expected = DatetimeIndex( [ - pd.Timestamp("2015-03-29 03:00:00+02:00", tz=timezone), - pd.Timestamp("2015-03-29 04:00:00+02:00", tz=timezone), + Timestamp("2015-03-29 03:00:00+02:00", tz=timezone), + Timestamp("2015-03-29 04:00:00+02:00", tz=timezone), ] ) tm.assert_index_equal(result, expected) # nonexistent keyword in end - end = pd.Timestamp("2015-03-29 02:30:00").tz_localize( + end = Timestamp("2015-03-29 02:30:00").tz_localize( timezone, nonexistent="shift_forward" ) result = pd.date_range(end=end, periods=2, freq="H") expected = DatetimeIndex( [ - pd.Timestamp("2015-03-29 01:00:00+01:00", tz=timezone), - pd.Timestamp("2015-03-29 03:00:00+02:00", tz=timezone), + Timestamp("2015-03-29 01:00:00+01:00", tz=timezone), + Timestamp("2015-03-29 03:00:00+02:00", tz=timezone), ] ) @@ -853,7 +853,7 @@ def test_constructor_no_precision_raises(self): msg = "with no precision is not allowed" with pytest.raises(ValueError, match=msg): - pd.DatetimeIndex(["2000"], dtype="datetime64") + DatetimeIndex(["2000"], dtype="datetime64") with pytest.raises(ValueError, match=msg): Index(["2000"], dtype="datetime64") @@ -861,7 +861,7 @@ def test_constructor_no_precision_raises(self): def test_constructor_wrong_precision_raises(self): msg = "Unexpected value for 'dtype': 'datetime64\\[us\\]'" with pytest.raises(ValueError, match=msg): - pd.DatetimeIndex(["2000"], dtype="datetime64[us]") + DatetimeIndex(["2000"], dtype="datetime64[us]") def test_index_constructor_with_numpy_object_array_and_timestamp_tz_with_nan(self): # GH 27011 @@ -1088,7 +1088,7 @@ def test_timestamp_constructor_fold_conflict(ts_input, fold): def test_timestamp_constructor_retain_fold(tz, fold): # Test for #25057 # Check that we retain fold - ts = pd.Timestamp(year=2019, month=10, day=27, hour=1, minute=30, tz=tz, fold=fold) + ts = Timestamp(year=2019, month=10, day=27, hour=1, minute=30, tz=tz, fold=fold) result = ts.fold expected = fold assert result == expected @@ -1110,7 +1110,7 @@ def test_timestamp_constructor_infer_fold_from_value(tz, ts_input, fold_out): # Test for #25057 # Check that we infer fold correctly based on timestamps since utc # or strings - ts = pd.Timestamp(ts_input, tz=tz) + ts = Timestamp(ts_input, tz=tz) result = ts.fold expected = fold_out assert result == expected @@ -1128,7 +1128,7 @@ def test_timestamp_constructor_adjust_value_for_fold(tz, ts_input, fold, value_o # Test for #25057 # Check that we adjust value for fold correctly # based on timestamps since utc - ts = pd.Timestamp(ts_input, tz=tz, fold=fold) + ts = Timestamp(ts_input, tz=tz, fold=fold) result = ts.value expected = value_out assert result == expected diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 9d867df147096..237c82436eb84 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -161,7 +161,7 @@ def test_date_range_gen_error(self): def test_begin_year_alias(self, freq): # see gh-9313 rng = date_range("1/1/2013", "7/1/2017", freq=freq) - exp = pd.DatetimeIndex( + exp = DatetimeIndex( ["2013-01-01", "2014-01-01", "2015-01-01", "2016-01-01", "2017-01-01"], freq=freq, ) @@ -171,7 +171,7 @@ def test_begin_year_alias(self, freq): def test_end_year_alias(self, freq): # see gh-9313 rng = date_range("1/1/2013", "7/1/2017", freq=freq) - exp = pd.DatetimeIndex( + exp = DatetimeIndex( ["2013-12-31", "2014-12-31", "2015-12-31", "2016-12-31"], freq=freq ) tm.assert_index_equal(rng, exp) @@ -180,7 +180,7 @@ def test_end_year_alias(self, freq): def test_business_end_year_alias(self, freq): # see gh-9313 rng = date_range("1/1/2013", "7/1/2017", freq=freq) - exp = pd.DatetimeIndex( + exp = DatetimeIndex( ["2013-12-31", "2014-12-31", "2015-12-31", "2016-12-30"], freq=freq ) tm.assert_index_equal(rng, exp) @@ -188,12 +188,12 @@ def test_business_end_year_alias(self, freq): def test_date_range_negative_freq(self): # GH 11018 rng = date_range("2011-12-31", freq="-2A", periods=3) - exp = pd.DatetimeIndex(["2011-12-31", "2009-12-31", "2007-12-31"], freq="-2A") + exp = DatetimeIndex(["2011-12-31", "2009-12-31", "2007-12-31"], freq="-2A") tm.assert_index_equal(rng, exp) assert rng.freq == "-2A" rng = date_range("2011-01-31", freq="-2M", periods=3) - exp = pd.DatetimeIndex(["2011-01-31", "2010-11-30", "2010-09-30"], freq="-2M") + exp = DatetimeIndex(["2011-01-31", "2010-11-30", "2010-09-30"], freq="-2M") tm.assert_index_equal(rng, exp) assert rng.freq == "-2M" @@ -778,10 +778,10 @@ def test_precision_finer_than_offset(self): @pytest.mark.parametrize( "start,end", [ - (pd.Timestamp(dt1, tz=tz1), pd.Timestamp(dt2)), - (pd.Timestamp(dt1), pd.Timestamp(dt2, tz=tz2)), - (pd.Timestamp(dt1, tz=tz1), pd.Timestamp(dt2, tz=tz2)), - (pd.Timestamp(dt1, tz=tz2), pd.Timestamp(dt2, tz=tz1)), + (Timestamp(dt1, tz=tz1), Timestamp(dt2)), + (Timestamp(dt1), Timestamp(dt2, tz=tz2)), + (Timestamp(dt1, tz=tz1), Timestamp(dt2, tz=tz2)), + (Timestamp(dt1, tz=tz2), Timestamp(dt2, tz=tz1)), ], ) def test_mismatching_tz_raises_err(self, start, end): @@ -859,15 +859,15 @@ def test_bdays_and_open_boundaries(self, closed): def test_bday_near_overflow(self): # GH#24252 avoid doing unnecessary addition that _would_ overflow - start = pd.Timestamp.max.floor("D").to_pydatetime() + start = Timestamp.max.floor("D").to_pydatetime() rng = pd.date_range(start, end=None, periods=1, freq="B") - expected = pd.DatetimeIndex([start], freq="B") + expected = DatetimeIndex([start], freq="B") tm.assert_index_equal(rng, expected) def test_bday_overflow_error(self): # GH#24252 check that we get OutOfBoundsDatetime and not OverflowError msg = "Out of bounds nanosecond timestamp" - start = pd.Timestamp.max.floor("D").to_pydatetime() + start = Timestamp.max.floor("D").to_pydatetime() with pytest.raises(OutOfBoundsDatetime, match=msg): pd.date_range(start, periods=2, freq="B") @@ -1004,7 +1004,7 @@ def test_date_range_with_custom_holidays(): # GH 30593 freq = pd.offsets.CustomBusinessHour(start="15:00", holidays=["2020-11-26"]) result = pd.date_range(start="2020-11-25 15:00", periods=4, freq=freq) - expected = pd.DatetimeIndex( + expected = DatetimeIndex( [ "2020-11-25 15:00:00", "2020-11-25 16:00:00", diff --git a/pandas/tests/indexes/datetimes/test_datetime.py b/pandas/tests/indexes/datetimes/test_datetime.py index 8e2ac4feb7ded..b801f750718ac 100644 --- a/pandas/tests/indexes/datetimes/test_datetime.py +++ b/pandas/tests/indexes/datetimes/test_datetime.py @@ -152,7 +152,7 @@ def test_iteration_preserves_tz(self): assert result == expected # 9100 - index = pd.DatetimeIndex( + index = DatetimeIndex( ["2014-12-01 03:32:39.987000-08:00", "2014-12-01 04:12:34.987000-08:00"] ) for i, ts in enumerate(index): @@ -254,7 +254,7 @@ def test_ns_index(self): dt = dtstart + np.arange(nsamples) * np.timedelta64(ns, "ns") freq = ns * offsets.Nano() - index = pd.DatetimeIndex(dt, freq=freq, name="time") + index = DatetimeIndex(dt, freq=freq, name="time") self.assert_index_parameters(index) new_index = pd.date_range(start=index[0], end=index[-1], freq=index.freq) @@ -284,7 +284,7 @@ def test_factorize(self): tm.assert_numpy_array_equal(arr, exp_arr) tm.assert_index_equal(idx, exp_idx) - idx2 = pd.DatetimeIndex( + idx2 = DatetimeIndex( ["2014-03", "2014-03", "2014-02", "2014-01", "2014-03", "2014-01"] ) @@ -340,10 +340,10 @@ def test_factorize_dst(self): @pytest.mark.parametrize( "arr, expected", [ - (pd.DatetimeIndex(["2017", "2017"]), pd.DatetimeIndex(["2017"])), + (DatetimeIndex(["2017", "2017"]), DatetimeIndex(["2017"])), ( - pd.DatetimeIndex(["2017", "2017"], tz="US/Eastern"), - pd.DatetimeIndex(["2017"], tz="US/Eastern"), + DatetimeIndex(["2017", "2017"], tz="US/Eastern"), + DatetimeIndex(["2017"], tz="US/Eastern"), ), ], ) diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index e0506df5cd939..4e46eb126894b 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -27,8 +27,8 @@ def test_ellipsis(self): def test_getitem_slice_keeps_name(self): # GH4226 - st = pd.Timestamp("2013-07-01 00:00:00", tz="America/Los_Angeles") - et = pd.Timestamp("2013-07-02 00:00:00", tz="America/Los_Angeles") + st = Timestamp("2013-07-01 00:00:00", tz="America/Los_Angeles") + et = Timestamp("2013-07-02 00:00:00", tz="America/Los_Angeles") dr = pd.date_range(st, et, freq="H", name="timebucket") assert dr[1:].name == dr.name @@ -321,23 +321,19 @@ def test_take2(self, tz): def test_take_fill_value(self): # GH#12631 - idx = pd.DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], name="xxx") + idx = DatetimeIndex(["2011-01-01", "2011-02-01", "2011-03-01"], name="xxx") result = idx.take(np.array([1, 0, -1])) - expected = pd.DatetimeIndex( - ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx" - ) + expected = DatetimeIndex(["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx") tm.assert_index_equal(result, expected) # fill_value result = idx.take(np.array([1, 0, -1]), fill_value=True) - expected = pd.DatetimeIndex(["2011-02-01", "2011-01-01", "NaT"], name="xxx") + expected = DatetimeIndex(["2011-02-01", "2011-01-01", "NaT"], name="xxx") tm.assert_index_equal(result, expected) # allow_fill=False result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) - expected = pd.DatetimeIndex( - ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx" - ) + expected = DatetimeIndex(["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx") tm.assert_index_equal(result, expected) msg = ( @@ -354,25 +350,25 @@ def test_take_fill_value(self): idx.take(np.array([1, -5])) def test_take_fill_value_with_timezone(self): - idx = pd.DatetimeIndex( + idx = DatetimeIndex( ["2011-01-01", "2011-02-01", "2011-03-01"], name="xxx", tz="US/Eastern" ) result = idx.take(np.array([1, 0, -1])) - expected = pd.DatetimeIndex( + expected = DatetimeIndex( ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx", tz="US/Eastern" ) tm.assert_index_equal(result, expected) # fill_value result = idx.take(np.array([1, 0, -1]), fill_value=True) - expected = pd.DatetimeIndex( + expected = DatetimeIndex( ["2011-02-01", "2011-01-01", "NaT"], name="xxx", tz="US/Eastern" ) tm.assert_index_equal(result, expected) # allow_fill=False result = idx.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) - expected = pd.DatetimeIndex( + expected = DatetimeIndex( ["2011-02-01", "2011-01-01", "2011-03-01"], name="xxx", tz="US/Eastern" ) tm.assert_index_equal(result, expected) @@ -475,7 +471,7 @@ def test_get_loc_time_nat(self): # GH#35114 # Case where key's total microseconds happens to match iNaT % 1e6 // 1000 tic = time(minute=12, second=43, microsecond=145224) - dti = pd.DatetimeIndex([pd.NaT]) + dti = DatetimeIndex([pd.NaT]) loc = dti.get_loc(tic) expected = np.array([], dtype=np.intp) @@ -484,11 +480,11 @@ def test_get_loc_time_nat(self): def test_get_loc_tz_aware(self): # https://github.com/pandas-dev/pandas/issues/32140 dti = pd.date_range( - pd.Timestamp("2019-12-12 00:00:00", tz="US/Eastern"), - pd.Timestamp("2019-12-13 00:00:00", tz="US/Eastern"), + Timestamp("2019-12-12 00:00:00", tz="US/Eastern"), + Timestamp("2019-12-13 00:00:00", tz="US/Eastern"), freq="5s", ) - key = pd.Timestamp("2019-12-12 10:19:25", tz="US/Eastern") + key = Timestamp("2019-12-12 10:19:25", tz="US/Eastern") result = dti.get_loc(key, method="nearest") assert result == 7433 @@ -589,15 +585,13 @@ def test_get_indexer(self): @pytest.mark.parametrize( "target", [ - [date(2020, 1, 1), pd.Timestamp("2020-01-02")], - [pd.Timestamp("2020-01-01"), date(2020, 1, 2)], + [date(2020, 1, 1), Timestamp("2020-01-02")], + [Timestamp("2020-01-01"), date(2020, 1, 2)], ], ) def test_get_indexer_mixed_dtypes(self, target): # https://github.com/pandas-dev/pandas/issues/33741 - values = pd.DatetimeIndex( - [pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")] - ) + values = DatetimeIndex([Timestamp("2020-01-01"), Timestamp("2020-01-02")]) result = values.get_indexer(target) expected = np.array([0, 1], dtype=np.intp) tm.assert_numpy_array_equal(result, expected) @@ -605,15 +599,13 @@ def test_get_indexer_mixed_dtypes(self, target): @pytest.mark.parametrize( "target, positions", [ - ([date(9999, 1, 1), pd.Timestamp("2020-01-01")], [-1, 0]), - ([pd.Timestamp("2020-01-01"), date(9999, 1, 1)], [0, -1]), + ([date(9999, 1, 1), Timestamp("2020-01-01")], [-1, 0]), + ([Timestamp("2020-01-01"), date(9999, 1, 1)], [0, -1]), ([date(9999, 1, 1), date(9999, 1, 1)], [-1, -1]), ], ) def test_get_indexer_out_of_bounds_date(self, target, positions): - values = pd.DatetimeIndex( - [pd.Timestamp("2020-01-01"), pd.Timestamp("2020-01-02")] - ) + values = DatetimeIndex([Timestamp("2020-01-01"), Timestamp("2020-01-02")]) result = values.get_indexer(target) expected = np.array(positions, dtype=np.intp) tm.assert_numpy_array_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index 4c632aba51c45..9cf0d2035fa67 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -48,7 +48,7 @@ def test_repeat_range(self, tz_naive_fixture): assert len(result) == 5 * len(rng) index = pd.date_range("2001-01-01", periods=2, freq="D", tz=tz) - exp = pd.DatetimeIndex( + exp = DatetimeIndex( ["2001-01-01", "2001-01-01", "2001-01-02", "2001-01-02"], tz=tz ) for res in [index.repeat(2), np.repeat(index, 2)]: @@ -56,15 +56,15 @@ def test_repeat_range(self, tz_naive_fixture): assert res.freq is None index = pd.date_range("2001-01-01", periods=2, freq="2D", tz=tz) - exp = pd.DatetimeIndex( + exp = DatetimeIndex( ["2001-01-01", "2001-01-01", "2001-01-03", "2001-01-03"], tz=tz ) for res in [index.repeat(2), np.repeat(index, 2)]: tm.assert_index_equal(res, exp) assert res.freq is None - index = pd.DatetimeIndex(["2001-01-01", "NaT", "2003-01-01"], tz=tz) - exp = pd.DatetimeIndex( + index = DatetimeIndex(["2001-01-01", "NaT", "2003-01-01"], tz=tz) + exp = DatetimeIndex( [ "2001-01-01", "2001-01-01", @@ -296,23 +296,23 @@ def test_drop_duplicates(self, freq_sample, keep, expected, index): def test_infer_freq(self, freq_sample): # GH 11018 idx = pd.date_range("2011-01-01 09:00:00", freq=freq_sample, periods=10) - result = pd.DatetimeIndex(idx.asi8, freq="infer") + result = DatetimeIndex(idx.asi8, freq="infer") tm.assert_index_equal(idx, result) assert result.freq == freq_sample def test_nat(self, tz_naive_fixture): tz = tz_naive_fixture - assert pd.DatetimeIndex._na_value is pd.NaT - assert pd.DatetimeIndex([])._na_value is pd.NaT + assert DatetimeIndex._na_value is pd.NaT + assert DatetimeIndex([])._na_value is pd.NaT - idx = pd.DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz) + idx = DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz) assert idx._can_hold_na tm.assert_numpy_array_equal(idx._isnan, np.array([False, False])) assert idx.hasnans is False tm.assert_numpy_array_equal(idx._nan_idxs, np.array([], dtype=np.intp)) - idx = pd.DatetimeIndex(["2011-01-01", "NaT"], tz=tz) + idx = DatetimeIndex(["2011-01-01", "NaT"], tz=tz) assert idx._can_hold_na tm.assert_numpy_array_equal(idx._isnan, np.array([False, True])) @@ -321,7 +321,7 @@ def test_nat(self, tz_naive_fixture): def test_equals(self): # GH 13107 - idx = pd.DatetimeIndex(["2011-01-01", "2011-01-02", "NaT"]) + idx = DatetimeIndex(["2011-01-01", "2011-01-02", "NaT"]) assert idx.equals(idx) assert idx.equals(idx.copy()) assert idx.equals(idx.astype(object)) @@ -330,7 +330,7 @@ def test_equals(self): assert not idx.equals(list(idx)) assert not idx.equals(Series(idx)) - idx2 = pd.DatetimeIndex(["2011-01-01", "2011-01-02", "NaT"], tz="US/Pacific") + idx2 = DatetimeIndex(["2011-01-01", "2011-01-02", "NaT"], tz="US/Pacific") assert not idx.equals(idx2) assert not idx.equals(idx2.copy()) assert not idx.equals(idx2.astype(object)) @@ -339,7 +339,7 @@ def test_equals(self): assert not idx.equals(Series(idx2)) # same internal, different tz - idx3 = pd.DatetimeIndex(idx.asi8, tz="US/Pacific") + idx3 = DatetimeIndex(idx.asi8, tz="US/Pacific") tm.assert_numpy_array_equal(idx.asi8, idx3.asi8) assert not idx.equals(idx3) assert not idx.equals(idx3.copy()) diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py index c02441b5883df..93c92c0b8f1ab 100644 --- a/pandas/tests/indexes/datetimes/test_setops.py +++ b/pandas/tests/indexes/datetimes/test_setops.py @@ -57,15 +57,15 @@ def test_union(self, tz, sort): rng1 = pd.date_range("1/1/2000", freq="D", periods=5, tz=tz) other1 = pd.date_range("1/6/2000", freq="D", periods=5, tz=tz) expected1 = pd.date_range("1/1/2000", freq="D", periods=10, tz=tz) - expected1_notsorted = pd.DatetimeIndex(list(other1) + list(rng1)) + expected1_notsorted = DatetimeIndex(list(other1) + list(rng1)) rng2 = pd.date_range("1/1/2000", freq="D", periods=5, tz=tz) other2 = pd.date_range("1/4/2000", freq="D", periods=5, tz=tz) expected2 = pd.date_range("1/1/2000", freq="D", periods=8, tz=tz) - expected2_notsorted = pd.DatetimeIndex(list(other2) + list(rng2[:3])) + expected2_notsorted = DatetimeIndex(list(other2) + list(rng2[:3])) rng3 = pd.date_range("1/1/2000", freq="D", periods=5, tz=tz) - other3 = pd.DatetimeIndex([], tz=tz) + other3 = DatetimeIndex([], tz=tz) expected3 = pd.date_range("1/1/2000", freq="D", periods=5, tz=tz) expected3_notsorted = rng3 @@ -307,17 +307,17 @@ def test_intersection_bug_1708(self): def test_difference(self, tz, sort): rng_dates = ["1/2/2000", "1/3/2000", "1/1/2000", "1/4/2000", "1/5/2000"] - rng1 = pd.DatetimeIndex(rng_dates, tz=tz) + rng1 = DatetimeIndex(rng_dates, tz=tz) other1 = pd.date_range("1/6/2000", freq="D", periods=5, tz=tz) - expected1 = pd.DatetimeIndex(rng_dates, tz=tz) + expected1 = DatetimeIndex(rng_dates, tz=tz) - rng2 = pd.DatetimeIndex(rng_dates, tz=tz) + rng2 = DatetimeIndex(rng_dates, tz=tz) other2 = pd.date_range("1/4/2000", freq="D", periods=5, tz=tz) - expected2 = pd.DatetimeIndex(rng_dates[:3], tz=tz) + expected2 = DatetimeIndex(rng_dates[:3], tz=tz) - rng3 = pd.DatetimeIndex(rng_dates, tz=tz) - other3 = pd.DatetimeIndex([], tz=tz) - expected3 = pd.DatetimeIndex(rng_dates, tz=tz) + rng3 = DatetimeIndex(rng_dates, tz=tz) + other3 = DatetimeIndex([], tz=tz) + expected3 = DatetimeIndex(rng_dates, tz=tz) for rng, other, expected in [ (rng1, other1, expected1), @@ -416,7 +416,7 @@ def test_union(self, sort): if sort is None: tm.assert_index_equal(right.union(left, sort=sort), the_union) else: - expected = pd.DatetimeIndex(list(right) + list(left)) + expected = DatetimeIndex(list(right) + list(left)) tm.assert_index_equal(right.union(left, sort=sort), expected) # overlapping, but different offset @@ -433,7 +433,7 @@ def test_union_not_cacheable(self, sort): if sort is None: tm.assert_index_equal(the_union, rng) else: - expected = pd.DatetimeIndex(list(rng[10:]) + list(rng[:10])) + expected = DatetimeIndex(list(rng[10:]) + list(rng[:10])) tm.assert_index_equal(the_union, expected) rng1 = rng[10:] @@ -471,7 +471,7 @@ def test_intersection_bug(self): def test_intersection_list(self): # GH#35876 values = [pd.Timestamp("2020-01-01"), pd.Timestamp("2020-02-01")] - idx = pd.DatetimeIndex(values, name="a") + idx = DatetimeIndex(values, name="a") res = idx.intersection(values) tm.assert_index_equal(res, idx.rename(None)) diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py index 233835bb4b5f7..8a73f564ef064 100644 --- a/pandas/tests/indexes/datetimes/test_timezones.py +++ b/pandas/tests/indexes/datetimes/test_timezones.py @@ -872,8 +872,8 @@ def test_drop_dst_boundary(self): tz = "Europe/Brussels" freq = "15min" - start = pd.Timestamp("201710290100", tz=tz) - end = pd.Timestamp("201710290300", tz=tz) + start = Timestamp("201710290100", tz=tz) + end = Timestamp("201710290300", tz=tz) index = pd.date_range(start=start, end=end, freq=freq) expected = DatetimeIndex( @@ -1142,15 +1142,15 @@ def test_dti_union_aware(self): def test_dti_union_mixed(self): # GH 21671 - rng = DatetimeIndex([pd.Timestamp("2011-01-01"), pd.NaT]) - rng2 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"], tz="Asia/Tokyo") + rng = DatetimeIndex([Timestamp("2011-01-01"), pd.NaT]) + rng2 = DatetimeIndex(["2012-01-01", "2012-01-02"], tz="Asia/Tokyo") result = rng.union(rng2) expected = Index( [ - pd.Timestamp("2011-01-01"), + Timestamp("2011-01-01"), pd.NaT, - pd.Timestamp("2012-01-01", tz="Asia/Tokyo"), - pd.Timestamp("2012-01-02", tz="Asia/Tokyo"), + Timestamp("2012-01-01", tz="Asia/Tokyo"), + Timestamp("2012-01-02", tz="Asia/Tokyo"), ], dtype=object, ) diff --git a/pandas/tests/indexes/interval/test_interval.py b/pandas/tests/indexes/interval/test_interval.py index 17a1c69858c11..1fbbb12b64dc5 100644 --- a/pandas/tests/indexes/interval/test_interval.py +++ b/pandas/tests/indexes/interval/test_interval.py @@ -868,7 +868,7 @@ def test_set_closed_errors(self, bad_closed): def test_is_all_dates(self): # GH 23576 year_2017 = pd.Interval( - pd.Timestamp("2017-01-01 00:00:00"), pd.Timestamp("2018-01-01 00:00:00") + Timestamp("2017-01-01 00:00:00"), Timestamp("2018-01-01 00:00:00") ) year_2017_index = pd.IntervalIndex([year_2017]) assert not year_2017_index._is_all_dates @@ -912,7 +912,7 @@ def test_searchsorted_different_argument_classes(klass): @pytest.mark.parametrize( - "arg", [[1, 2], ["a", "b"], [pd.Timestamp("2020-01-01", tz="Europe/London")] * 2] + "arg", [[1, 2], ["a", "b"], [Timestamp("2020-01-01", tz="Europe/London")] * 2] ) def test_searchsorted_invalid_argument(arg): values = IntervalIndex([Interval(0, 1), Interval(1, 2)]) diff --git a/pandas/tests/indexes/multi/conftest.py b/pandas/tests/indexes/multi/conftest.py index 67ebfcddf6c2d..a77af84ee1ed0 100644 --- a/pandas/tests/indexes/multi/conftest.py +++ b/pandas/tests/indexes/multi/conftest.py @@ -63,7 +63,7 @@ def narrow_multi_index(): n = 1000 ci = pd.CategoricalIndex(list("a" * n) + (["abc"] * n)) dti = pd.date_range("2000-01-01", freq="s", periods=n * 2) - return pd.MultiIndex.from_arrays([ci, ci.codes + 9, dti], names=["a", "b", "dti"]) + return MultiIndex.from_arrays([ci, ci.codes + 9, dti], names=["a", "b", "dti"]) @pytest.fixture @@ -76,4 +76,4 @@ def wide_multi_index(): dti = pd.date_range("2000-01-01", freq="s", periods=n * 2) levels = [ci, ci.codes + 9, dti, dti, dti] names = ["a", "b", "dti_1", "dti_2", "dti_3"] - return pd.MultiIndex.from_arrays(levels, names=names) + return MultiIndex.from_arrays(levels, names=names) diff --git a/pandas/tests/indexes/multi/test_constructors.py b/pandas/tests/indexes/multi/test_constructors.py index 63afd5e130508..a2ca686d0412d 100644 --- a/pandas/tests/indexes/multi/test_constructors.py +++ b/pandas/tests/indexes/multi/test_constructors.py @@ -192,11 +192,11 @@ def test_from_arrays_tuples(idx): def test_from_arrays_index_series_datetimetz(): idx1 = pd.date_range("2015-01-01 10:00", freq="D", periods=3, tz="US/Eastern") idx2 = pd.date_range("2015-01-01 10:00", freq="H", periods=3, tz="Asia/Tokyo") - result = pd.MultiIndex.from_arrays([idx1, idx2]) + result = MultiIndex.from_arrays([idx1, idx2]) tm.assert_index_equal(result.get_level_values(0), idx1) tm.assert_index_equal(result.get_level_values(1), idx2) - result2 = pd.MultiIndex.from_arrays([Series(idx1), Series(idx2)]) + result2 = MultiIndex.from_arrays([Series(idx1), Series(idx2)]) tm.assert_index_equal(result2.get_level_values(0), idx1) tm.assert_index_equal(result2.get_level_values(1), idx2) @@ -206,11 +206,11 @@ def test_from_arrays_index_series_datetimetz(): def test_from_arrays_index_series_timedelta(): idx1 = pd.timedelta_range("1 days", freq="D", periods=3) idx2 = pd.timedelta_range("2 hours", freq="H", periods=3) - result = pd.MultiIndex.from_arrays([idx1, idx2]) + result = MultiIndex.from_arrays([idx1, idx2]) tm.assert_index_equal(result.get_level_values(0), idx1) tm.assert_index_equal(result.get_level_values(1), idx2) - result2 = pd.MultiIndex.from_arrays([Series(idx1), Series(idx2)]) + result2 = MultiIndex.from_arrays([Series(idx1), Series(idx2)]) tm.assert_index_equal(result2.get_level_values(0), idx1) tm.assert_index_equal(result2.get_level_values(1), idx2) @@ -220,11 +220,11 @@ def test_from_arrays_index_series_timedelta(): def test_from_arrays_index_series_period(): idx1 = pd.period_range("2011-01-01", freq="D", periods=3) idx2 = pd.period_range("2015-01-01", freq="H", periods=3) - result = pd.MultiIndex.from_arrays([idx1, idx2]) + result = MultiIndex.from_arrays([idx1, idx2]) tm.assert_index_equal(result.get_level_values(0), idx1) tm.assert_index_equal(result.get_level_values(1), idx2) - result2 = pd.MultiIndex.from_arrays([Series(idx1), Series(idx2)]) + result2 = MultiIndex.from_arrays([Series(idx1), Series(idx2)]) tm.assert_index_equal(result2.get_level_values(0), idx1) tm.assert_index_equal(result2.get_level_values(1), idx2) @@ -237,13 +237,13 @@ def test_from_arrays_index_datetimelike_mixed(): idx3 = pd.timedelta_range("1 days", freq="D", periods=3) idx4 = pd.period_range("2011-01-01", freq="D", periods=3) - result = pd.MultiIndex.from_arrays([idx1, idx2, idx3, idx4]) + result = MultiIndex.from_arrays([idx1, idx2, idx3, idx4]) tm.assert_index_equal(result.get_level_values(0), idx1) tm.assert_index_equal(result.get_level_values(1), idx2) tm.assert_index_equal(result.get_level_values(2), idx3) tm.assert_index_equal(result.get_level_values(3), idx4) - result2 = pd.MultiIndex.from_arrays( + result2 = MultiIndex.from_arrays( [Series(idx1), Series(idx2), Series(idx3), Series(idx4)] ) tm.assert_index_equal(result2.get_level_values(0), idx1) @@ -259,15 +259,15 @@ def test_from_arrays_index_series_categorical(): idx1 = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=False) idx2 = pd.CategoricalIndex(list("abcaab"), categories=list("bac"), ordered=True) - result = pd.MultiIndex.from_arrays([idx1, idx2]) + result = MultiIndex.from_arrays([idx1, idx2]) tm.assert_index_equal(result.get_level_values(0), idx1) tm.assert_index_equal(result.get_level_values(1), idx2) - result2 = pd.MultiIndex.from_arrays([Series(idx1), Series(idx2)]) + result2 = MultiIndex.from_arrays([Series(idx1), Series(idx2)]) tm.assert_index_equal(result2.get_level_values(0), idx1) tm.assert_index_equal(result2.get_level_values(1), idx2) - result3 = pd.MultiIndex.from_arrays([idx1.values, idx2.values]) + result3 = MultiIndex.from_arrays([idx1.values, idx2.values]) tm.assert_index_equal(result3.get_level_values(0), idx1) tm.assert_index_equal(result3.get_level_values(1), idx2) @@ -412,7 +412,7 @@ def test_from_tuples_with_tuple_label(): expected = pd.DataFrame( [[2, 1, 2], [4, (1, 2), 3]], columns=["a", "b", "c"] ).set_index(["a", "b"]) - idx = pd.MultiIndex.from_tuples([(2, 1), (4, (1, 2))], names=("a", "b")) + idx = MultiIndex.from_tuples([(2, 1), (4, (1, 2))], names=("a", "b")) result = pd.DataFrame([2, 3], columns=["c"], index=idx) tm.assert_frame_equal(expected, result) @@ -465,13 +465,13 @@ def test_from_product_invalid_input(invalid_input): def test_from_product_datetimeindex(): dt_index = date_range("2000-01-01", periods=2) - mi = pd.MultiIndex.from_product([[1, 2], dt_index]) + mi = MultiIndex.from_product([[1, 2], dt_index]) etalon = construct_1d_object_array_from_listlike( [ - (1, pd.Timestamp("2000-01-01")), - (1, pd.Timestamp("2000-01-02")), - (2, pd.Timestamp("2000-01-01")), - (2, pd.Timestamp("2000-01-02")), + (1, Timestamp("2000-01-01")), + (1, Timestamp("2000-01-02")), + (2, Timestamp("2000-01-01")), + (2, Timestamp("2000-01-02")), ] ) tm.assert_numpy_array_equal(mi.values, etalon) @@ -488,7 +488,7 @@ def test_from_product_index_series_categorical(ordered, f): list("abcaab") + list("abcaab"), categories=list("bac"), ordered=ordered ) - result = pd.MultiIndex.from_product([first, f(idx)]) + result = MultiIndex.from_product([first, f(idx)]) tm.assert_index_equal(result.get_level_values(1), expected) @@ -639,10 +639,10 @@ def test_from_frame(): df = pd.DataFrame( [["a", "a"], ["a", "b"], ["b", "a"], ["b", "b"]], columns=["L1", "L2"] ) - expected = pd.MultiIndex.from_tuples( + expected = MultiIndex.from_tuples( [("a", "a"), ("a", "b"), ("b", "a"), ("b", "b")], names=["L1", "L2"] ) - result = pd.MultiIndex.from_frame(df) + result = MultiIndex.from_frame(df) tm.assert_index_equal(expected, result) @@ -660,7 +660,7 @@ def test_from_frame(): def test_from_frame_error(non_frame): # GH 22420 with pytest.raises(TypeError, match="Input must be a DataFrame"): - pd.MultiIndex.from_frame(non_frame) + MultiIndex.from_frame(non_frame) def test_from_frame_dtype_fidelity(): @@ -675,7 +675,7 @@ def test_from_frame_dtype_fidelity(): ) original_dtypes = df.dtypes.to_dict() - expected_mi = pd.MultiIndex.from_arrays( + expected_mi = MultiIndex.from_arrays( [ pd.date_range("19910905", periods=6, tz="US/Eastern"), [1, 1, 1, 2, 2, 2], @@ -684,7 +684,7 @@ def test_from_frame_dtype_fidelity(): ], names=["dates", "a", "b", "c"], ) - mi = pd.MultiIndex.from_frame(df) + mi = MultiIndex.from_frame(df) mi_dtypes = {name: mi.levels[i].dtype for i, name in enumerate(mi.names)} tm.assert_index_equal(expected_mi, mi) @@ -698,9 +698,9 @@ def test_from_frame_valid_names(names_in, names_out): # GH 22420 df = pd.DataFrame( [["a", "a"], ["a", "b"], ["b", "a"], ["b", "b"]], - columns=pd.MultiIndex.from_tuples([("L1", "x"), ("L2", "y")]), + columns=MultiIndex.from_tuples([("L1", "x"), ("L2", "y")]), ) - mi = pd.MultiIndex.from_frame(df, names=names_in) + mi = MultiIndex.from_frame(df, names=names_in) assert mi.names == names_out @@ -715,10 +715,10 @@ def test_from_frame_invalid_names(names, expected_error_msg): # GH 22420 df = pd.DataFrame( [["a", "a"], ["a", "b"], ["b", "a"], ["b", "b"]], - columns=pd.MultiIndex.from_tuples([("L1", "x"), ("L2", "y")]), + columns=MultiIndex.from_tuples([("L1", "x"), ("L2", "y")]), ) with pytest.raises(ValueError, match=expected_error_msg): - pd.MultiIndex.from_frame(df, names=names) + MultiIndex.from_frame(df, names=names) def test_index_equal_empty_iterable(): diff --git a/pandas/tests/indexes/multi/test_equivalence.py b/pandas/tests/indexes/multi/test_equivalence.py index e1b011b762fe7..c31c2416ff722 100644 --- a/pandas/tests/indexes/multi/test_equivalence.py +++ b/pandas/tests/indexes/multi/test_equivalence.py @@ -202,7 +202,7 @@ def test_equals_operator(idx): def test_equals_missing_values(): # make sure take is not using -1 - i = pd.MultiIndex.from_tuples([(0, pd.NaT), (0, pd.Timestamp("20130101"))]) + i = MultiIndex.from_tuples([(0, pd.NaT), (0, pd.Timestamp("20130101"))]) result = i[0:1].equals(i[0]) assert not result result = i[1:2].equals(i[1]) @@ -255,7 +255,7 @@ def test_multiindex_compare(): # Ensure comparison operations for MultiIndex with nlevels == 1 # behave consistently with those for MultiIndex with nlevels > 1 - midx = pd.MultiIndex.from_product([[0, 1]]) + midx = MultiIndex.from_product([[0, 1]]) # Equality self-test: MultiIndex object vs self expected = Series([True, True]) diff --git a/pandas/tests/indexes/multi/test_get_level_values.py b/pandas/tests/indexes/multi/test_get_level_values.py index ec65ec2c54689..f976515870259 100644 --- a/pandas/tests/indexes/multi/test_get_level_values.py +++ b/pandas/tests/indexes/multi/test_get_level_values.py @@ -42,7 +42,7 @@ def test_get_level_values(idx): def test_get_level_values_all_na(): # GH#17924 when level entirely consists of nan arrays = [[np.nan, np.nan, np.nan], ["a", np.nan, 1]] - index = pd.MultiIndex.from_arrays(arrays) + index = MultiIndex.from_arrays(arrays) result = index.get_level_values(0) expected = Index([np.nan, np.nan, np.nan], dtype=np.float64) tm.assert_index_equal(result, expected) @@ -55,13 +55,13 @@ def test_get_level_values_all_na(): def test_get_level_values_int_with_na(): # GH#17924 arrays = [["a", "b", "b"], [1, np.nan, 2]] - index = pd.MultiIndex.from_arrays(arrays) + index = MultiIndex.from_arrays(arrays) result = index.get_level_values(1) expected = Index([1, np.nan, 2]) tm.assert_index_equal(result, expected) arrays = [["a", "b", "b"], [np.nan, np.nan, 2]] - index = pd.MultiIndex.from_arrays(arrays) + index = MultiIndex.from_arrays(arrays) result = index.get_level_values(1) expected = Index([np.nan, np.nan, 2]) tm.assert_index_equal(result, expected) @@ -69,7 +69,7 @@ def test_get_level_values_int_with_na(): def test_get_level_values_na(): arrays = [[np.nan, np.nan, np.nan], ["a", np.nan, 1]] - index = pd.MultiIndex.from_arrays(arrays) + index = MultiIndex.from_arrays(arrays) result = index.get_level_values(0) expected = Index([np.nan, np.nan, np.nan]) tm.assert_index_equal(result, expected) @@ -79,13 +79,13 @@ def test_get_level_values_na(): tm.assert_index_equal(result, expected) arrays = [["a", "b", "b"], pd.DatetimeIndex([0, 1, pd.NaT])] - index = pd.MultiIndex.from_arrays(arrays) + index = MultiIndex.from_arrays(arrays) result = index.get_level_values(1) expected = pd.DatetimeIndex([0, 1, pd.NaT]) tm.assert_index_equal(result, expected) arrays = [[], []] - index = pd.MultiIndex.from_arrays(arrays) + index = MultiIndex.from_arrays(arrays) result = index.get_level_values(0) expected = Index([], dtype=object) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/multi/test_get_set.py b/pandas/tests/indexes/multi/test_get_set.py index 6f79878fd3ab1..63dd1b575284c 100644 --- a/pandas/tests/indexes/multi/test_get_set.py +++ b/pandas/tests/indexes/multi/test_get_set.py @@ -228,9 +228,9 @@ def test_set_codes(idx): assert_matching(idx.codes, codes) # label changing for levels of different magnitude of categories - ind = pd.MultiIndex.from_tuples([(0, i) for i in range(130)]) + ind = MultiIndex.from_tuples([(0, i) for i in range(130)]) new_codes = range(129, -1, -1) - expected = pd.MultiIndex.from_tuples([(0, i) for i in new_codes]) + expected = MultiIndex.from_tuples([(0, i) for i in new_codes]) # [w/o mutation] result = ind.set_codes(codes=new_codes, level=1) @@ -295,8 +295,8 @@ def test_set_names_with_nlevel_1(inplace): # GH 21149 # Ensure that .set_names for MultiIndex with # nlevels == 1 does not raise any errors - expected = pd.MultiIndex(levels=[[0, 1]], codes=[[0, 1]], names=["first"]) - m = pd.MultiIndex.from_product([[0, 1]]) + expected = MultiIndex(levels=[[0, 1]], codes=[[0, 1]], names=["first"]) + m = MultiIndex.from_product([[0, 1]]) result = m.set_names("first", level=0, inplace=inplace) if inplace: @@ -326,7 +326,7 @@ def test_set_value_keeps_names(): # motivating example from #3742 lev1 = ["hans", "hans", "hans", "grethe", "grethe", "grethe"] lev2 = ["1", "2", "3"] * 2 - idx = pd.MultiIndex.from_arrays([lev1, lev2], names=["Name", "Number"]) + idx = MultiIndex.from_arrays([lev1, lev2], names=["Name", "Number"]) df = pd.DataFrame( np.random.randn(6, 4), columns=["one", "two", "three", "four"], index=idx ) @@ -342,14 +342,12 @@ def test_set_levels_with_iterable(): # GH23273 sizes = [1, 2, 3] colors = ["black"] * 3 - index = pd.MultiIndex.from_arrays([sizes, colors], names=["size", "color"]) + index = MultiIndex.from_arrays([sizes, colors], names=["size", "color"]) result = index.set_levels(map(int, ["3", "2", "1"]), level="size") expected_sizes = [3, 2, 1] - expected = pd.MultiIndex.from_arrays( - [expected_sizes, colors], names=["size", "color"] - ) + expected = MultiIndex.from_arrays([expected_sizes, colors], names=["size", "color"]) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py index 57747f8274d85..e8e31aa0cef80 100644 --- a/pandas/tests/indexes/multi/test_indexing.py +++ b/pandas/tests/indexes/multi/test_indexing.py @@ -318,8 +318,8 @@ def test_get_indexer_three_or_more_levels(self): # 4: 2 7 6 # 5: 2 7 8 # 6: 3 6 8 - mult_idx_1 = pd.MultiIndex.from_product([[1, 3], [2, 4, 6], [5, 7]]) - mult_idx_2 = pd.MultiIndex.from_tuples( + mult_idx_1 = MultiIndex.from_product([[1, 3], [2, 4, 6], [5, 7]]) + mult_idx_2 = MultiIndex.from_tuples( [ (1, 1, 8), (1, 5, 9), @@ -418,8 +418,8 @@ def test_get_indexer_crossing_levels(self): # mult_idx_2: # 0: 1 3 2 2 # 1: 2 3 2 2 - mult_idx_1 = pd.MultiIndex.from_product([[1, 2]] * 4) - mult_idx_2 = pd.MultiIndex.from_tuples([(1, 3, 2, 2), (2, 3, 2, 2)]) + mult_idx_1 = MultiIndex.from_product([[1, 2]] * 4) + mult_idx_2 = MultiIndex.from_tuples([(1, 3, 2, 2), (2, 3, 2, 2)]) # show the tuple orderings, which get_indexer() should respect assert mult_idx_1[7] < mult_idx_2[0] < mult_idx_1[8] @@ -482,7 +482,7 @@ def test_getitem_bool_index_single(ind1, ind2): idx = MultiIndex.from_tuples([(10, 1)]) tm.assert_index_equal(idx[ind1], idx) - expected = pd.MultiIndex( + expected = MultiIndex( levels=[np.array([], dtype=np.int64), np.array([], dtype=np.int64)], codes=[[], []], ) @@ -572,7 +572,7 @@ def test_get_loc_level(self): def test_get_loc_multiple_dtypes(self, dtype1, dtype2): # GH 18520 levels = [np.array([0, 1]).astype(dtype1), np.array([0, 1]).astype(dtype2)] - idx = pd.MultiIndex.from_product(levels) + idx = MultiIndex.from_product(levels) assert idx.get_loc(idx[2]) == 2 @pytest.mark.parametrize("level", [0, 1]) @@ -755,7 +755,7 @@ def test_large_mi_contains(self): def test_timestamp_multiindex_indexer(): # https://github.com/pandas-dev/pandas/issues/26944 - idx = pd.MultiIndex.from_product( + idx = MultiIndex.from_product( [ pd.date_range("2019-01-01T00:15:33", periods=100, freq="H", name="date"), ["x"], @@ -764,7 +764,7 @@ def test_timestamp_multiindex_indexer(): ) df = pd.DataFrame({"foo": np.arange(len(idx))}, idx) result = df.loc[pd.IndexSlice["2019-1-2":, "x", :], "foo"] - qidx = pd.MultiIndex.from_product( + qidx = MultiIndex.from_product( [ pd.date_range( start="2019-01-02T00:15:33", diff --git a/pandas/tests/indexes/multi/test_integrity.py b/pandas/tests/indexes/multi/test_integrity.py index 6a353fe1ad6e7..f9ab0b3aceec4 100644 --- a/pandas/tests/indexes/multi/test_integrity.py +++ b/pandas/tests/indexes/multi/test_integrity.py @@ -24,7 +24,7 @@ def test_labels_dtypes(): i = MultiIndex.from_product([["a"], range(40000)]) assert i.codes[1].dtype == "int32" - i = pd.MultiIndex.from_product([["a"], range(1000)]) + i = MultiIndex.from_product([["a"], range(1000)]) assert (i.codes[0] >= 0).all() assert (i.codes[1] >= 0).all() @@ -38,7 +38,7 @@ def test_values_boxed(): (2, pd.Timestamp("2000-01-02")), (3, pd.Timestamp("2000-01-03")), ] - result = pd.MultiIndex.from_tuples(tuples) + result = MultiIndex.from_tuples(tuples) expected = construct_1d_object_array_from_listlike(tuples) tm.assert_numpy_array_equal(result.values, expected) # Check that code branches for boxed values produce identical results @@ -52,7 +52,7 @@ def test_values_multiindex_datetimeindex(): aware = pd.DatetimeIndex(ints, tz="US/Central") - idx = pd.MultiIndex.from_arrays([naive, aware]) + idx = MultiIndex.from_arrays([naive, aware]) result = idx.values outer = pd.DatetimeIndex([x[0] for x in result]) @@ -76,7 +76,7 @@ def test_values_multiindex_periodindex(): ints = np.arange(2007, 2012) pidx = pd.PeriodIndex(ints, freq="D") - idx = pd.MultiIndex.from_arrays([ints, pidx]) + idx = MultiIndex.from_arrays([ints, pidx]) result = idx.values outer = pd.Int64Index([x[0] for x in result]) @@ -139,7 +139,7 @@ def test_dims(): def take_invalid_kwargs(): vals = [["A", "B"], [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02")]] - idx = pd.MultiIndex.from_product(vals, names=["str", "dt"]) + idx = MultiIndex.from_product(vals, names=["str", "dt"]) indices = [1, 2] msg = r"take\(\) got an unexpected keyword argument 'foo'" @@ -167,14 +167,14 @@ def test_isna_behavior(idx): def test_large_multiindex_error(): # GH12527 df_below_1000000 = pd.DataFrame( - 1, index=pd.MultiIndex.from_product([[1, 2], range(499999)]), columns=["dest"] + 1, index=MultiIndex.from_product([[1, 2], range(499999)]), columns=["dest"] ) with pytest.raises(KeyError, match=r"^\(-1, 0\)$"): df_below_1000000.loc[(-1, 0), "dest"] with pytest.raises(KeyError, match=r"^\(3, 0\)$"): df_below_1000000.loc[(3, 0), "dest"] df_above_1000000 = pd.DataFrame( - 1, index=pd.MultiIndex.from_product([[1, 2], range(500001)]), columns=["dest"] + 1, index=MultiIndex.from_product([[1, 2], range(500001)]), columns=["dest"] ) with pytest.raises(KeyError, match=r"^\(-1, 0\)$"): df_above_1000000.loc[(-1, 0), "dest"] @@ -186,7 +186,7 @@ def test_million_record_attribute_error(): # GH 18165 r = list(range(1000000)) df = pd.DataFrame( - {"a": r, "b": r}, index=pd.MultiIndex.from_tuples([(x, x) for x in r]) + {"a": r, "b": r}, index=MultiIndex.from_tuples([(x, x) for x in r]) ) msg = "'Series' object has no attribute 'foo'" @@ -219,7 +219,7 @@ def test_metadata_immutable(idx): def test_level_setting_resets_attributes(): - ind = pd.MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]]) + ind = MultiIndex.from_arrays([["A", "A", "B", "B", "B"], [1, 2, 1, 2, 3]]) assert ind.is_monotonic with tm.assert_produces_warning(FutureWarning): ind.set_levels([["A", "B"], [1, 3, 2]], inplace=True) @@ -237,9 +237,7 @@ def test_rangeindex_fallback_coercion_bug(): str(df) expected = pd.DataFrame( {"bar": np.arange(100), "foo": np.arange(100)}, - index=pd.MultiIndex.from_product( - [range(10), range(10)], names=["fizz", "buzz"] - ), + index=MultiIndex.from_product([range(10), range(10)], names=["fizz", "buzz"]), ) tm.assert_frame_equal(df, expected, check_like=True) diff --git a/pandas/tests/indexes/multi/test_missing.py b/pandas/tests/indexes/multi/test_missing.py index 4c9d518778ceb..cd95802ac29c9 100644 --- a/pandas/tests/indexes/multi/test_missing.py +++ b/pandas/tests/indexes/multi/test_missing.py @@ -15,7 +15,7 @@ def test_fillna(idx): def test_dropna(): # GH 6194 - idx = pd.MultiIndex.from_arrays( + idx = MultiIndex.from_arrays( [ [1, np.nan, 3, np.nan, 5], [1, 2, np.nan, np.nan, 5], @@ -23,11 +23,11 @@ def test_dropna(): ] ) - exp = pd.MultiIndex.from_arrays([[1, 5], [1, 5], ["a", "e"]]) + exp = MultiIndex.from_arrays([[1, 5], [1, 5], ["a", "e"]]) tm.assert_index_equal(idx.dropna(), exp) tm.assert_index_equal(idx.dropna(how="any"), exp) - exp = pd.MultiIndex.from_arrays( + exp = MultiIndex.from_arrays( [[1, np.nan, 3, 5], [1, 2, np.nan, 5], ["a", "b", "c", "e"]] ) tm.assert_index_equal(idx.dropna(how="all"), exp) @@ -87,10 +87,8 @@ def test_hasnans_isnans(idx): def test_nan_stays_float(): # GH 7031 - idx0 = pd.MultiIndex( - levels=[["A", "B"], []], codes=[[1, 0], [-1, -1]], names=[0, 1] - ) - idx1 = pd.MultiIndex(levels=[["C"], ["D"]], codes=[[0], [0]], names=[0, 1]) + idx0 = MultiIndex(levels=[["A", "B"], []], codes=[[1, 0], [-1, -1]], names=[0, 1]) + idx1 = MultiIndex(levels=[["C"], ["D"]], codes=[[0], [0]], names=[0, 1]) idxm = idx0.join(idx1, how="outer") assert pd.isna(idx0.get_level_values(1)).all() # the following failed in 0.14.1 diff --git a/pandas/tests/indexes/multi/test_monotonic.py b/pandas/tests/indexes/multi/test_monotonic.py index 8659573d8123a..11bcd61383a7c 100644 --- a/pandas/tests/indexes/multi/test_monotonic.py +++ b/pandas/tests/indexes/multi/test_monotonic.py @@ -1,7 +1,6 @@ import numpy as np import pytest -import pandas as pd from pandas import Index, MultiIndex @@ -162,7 +161,7 @@ def test_is_monotonic_decreasing(): def test_is_strictly_monotonic_increasing(): - idx = pd.MultiIndex( + idx = MultiIndex( levels=[["bar", "baz"], ["mom", "next"]], codes=[[0, 0, 1, 1], [0, 0, 0, 1]] ) assert idx.is_monotonic_increasing is True @@ -170,7 +169,7 @@ def test_is_strictly_monotonic_increasing(): def test_is_strictly_monotonic_decreasing(): - idx = pd.MultiIndex( + idx = MultiIndex( levels=[["baz", "bar"], ["next", "mom"]], codes=[[0, 0, 1, 1], [0, 0, 0, 1]] ) assert idx.is_monotonic_decreasing is True @@ -184,5 +183,5 @@ def test_is_strictly_monotonic_decreasing(): ) def test_is_monotonic_with_nans(values, attr): # GH: 37220 - idx = pd.MultiIndex.from_tuples(values, names=["test"]) + idx = MultiIndex.from_tuples(values, names=["test"]) assert getattr(idx, attr) is False diff --git a/pandas/tests/indexes/multi/test_names.py b/pandas/tests/indexes/multi/test_names.py index f38da7ad2ae1c..891380b35a8be 100644 --- a/pandas/tests/indexes/multi/test_names.py +++ b/pandas/tests/indexes/multi/test_names.py @@ -127,14 +127,14 @@ def test_duplicate_level_names_access_raises(idx): def test_get_names_from_levels(): - idx = pd.MultiIndex.from_product([["a"], [1, 2]], names=["a", "b"]) + idx = MultiIndex.from_product([["a"], [1, 2]], names=["a", "b"]) assert idx.levels[0].name == "a" assert idx.levels[1].name == "b" def test_setting_names_from_levels_raises(): - idx = pd.MultiIndex.from_product([["a"], [1, 2]], names=["a", "b"]) + idx = MultiIndex.from_product([["a"], [1, 2]], names=["a", "b"]) with pytest.raises(RuntimeError, match="set_names"): idx.levels[0].name = "foo" diff --git a/pandas/tests/indexes/multi/test_sorting.py b/pandas/tests/indexes/multi/test_sorting.py index 3d7e6e9c32248..cd063a0c3f74b 100644 --- a/pandas/tests/indexes/multi/test_sorting.py +++ b/pandas/tests/indexes/multi/test_sorting.py @@ -5,7 +5,6 @@ from pandas.errors import PerformanceWarning, UnsortedIndexError -import pandas as pd from pandas import CategoricalIndex, DataFrame, Index, MultiIndex, RangeIndex import pandas._testing as tm @@ -94,7 +93,7 @@ def test_numpy_argsort(idx): def test_unsortedindex(): # GH 11897 - mi = pd.MultiIndex.from_tuples( + mi = MultiIndex.from_tuples( [("z", "a"), ("x", "a"), ("y", "b"), ("x", "b"), ("y", "a"), ("z", "b")], names=["one", "two"], ) @@ -160,7 +159,7 @@ def test_reconstruct_sort(): assert Index(mi.values).equals(Index(recons.values)) # cannot convert to lexsorted - mi = pd.MultiIndex.from_tuples( + mi = MultiIndex.from_tuples( [("z", "a"), ("x", "a"), ("y", "b"), ("x", "b"), ("y", "a"), ("z", "b")], names=["one", "two"], ) @@ -260,9 +259,7 @@ def test_remove_unused_levels_large(first_type, second_type): ) def test_remove_unused_nan(level0, level1): # GH 18417 - mi = pd.MultiIndex( - levels=[level0, level1], codes=[[0, 2, -1, 1, -1], [0, 1, 2, 3, 2]] - ) + mi = MultiIndex(levels=[level0, level1], codes=[[0, 2, -1, 1, -1], [0, 1, 2, 3, 2]]) result = mi.remove_unused_levels() tm.assert_index_equal(result, mi) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 9820b39e20651..f37c3dff1e338 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -112,7 +112,7 @@ def test_constructor_from_index_dtlike(self, cast_as_obj, index): tm.assert_index_equal(result, index) - if isinstance(index, pd.DatetimeIndex): + if isinstance(index, DatetimeIndex): assert result.tz == index.tz if cast_as_obj: # GH#23524 check that Index(dti, dtype=object) does not @@ -222,7 +222,7 @@ def test_constructor_no_pandas_array(self): "klass,dtype,na_val", [ (pd.Float64Index, np.float64, np.nan), - (pd.DatetimeIndex, "datetime64[ns]", pd.NaT), + (DatetimeIndex, "datetime64[ns]", pd.NaT), ], ) def test_index_ctor_infer_nan_nat(self, klass, dtype, na_val): @@ -336,7 +336,7 @@ def test_constructor_dtypes_to_timedelta(self, cast_index, vals): assert isinstance(index, TimedeltaIndex) @pytest.mark.parametrize("attr", ["values", "asi8"]) - @pytest.mark.parametrize("klass", [Index, pd.DatetimeIndex]) + @pytest.mark.parametrize("klass", [Index, DatetimeIndex]) def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass): # Test constructing with a datetimetz dtype # .values produces numpy datetimes, so these are considered naive @@ -349,25 +349,25 @@ def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass): dtype = index.dtype if attr == "asi8": - result = pd.DatetimeIndex(arg).tz_localize(tz_naive_fixture) + result = DatetimeIndex(arg).tz_localize(tz_naive_fixture) else: result = klass(arg, tz=tz_naive_fixture) tm.assert_index_equal(result, index) if attr == "asi8": - result = pd.DatetimeIndex(arg).astype(dtype) + result = DatetimeIndex(arg).astype(dtype) else: result = klass(arg, dtype=dtype) tm.assert_index_equal(result, index) if attr == "asi8": - result = pd.DatetimeIndex(list(arg)).tz_localize(tz_naive_fixture) + result = DatetimeIndex(list(arg)).tz_localize(tz_naive_fixture) else: result = klass(list(arg), tz=tz_naive_fixture) tm.assert_index_equal(result, index) if attr == "asi8": - result = pd.DatetimeIndex(list(arg)).astype(dtype) + result = DatetimeIndex(list(arg)).astype(dtype) else: result = klass(list(arg), dtype=dtype) tm.assert_index_equal(result, index) @@ -602,7 +602,7 @@ def test_empty_fancy(self, index, dtype): @pytest.mark.parametrize("index", ["string", "int", "float"], indirect=True) def test_empty_fancy_raises(self, index): - # pd.DatetimeIndex is excluded, because it overrides getitem and should + # DatetimeIndex is excluded, because it overrides getitem and should # be tested separately. empty_farr = np.array([], dtype=np.float_) empty_index = type(index)([]) @@ -1014,13 +1014,13 @@ def test_symmetric_difference(self, sort): @pytest.mark.parametrize("opname", ["difference", "symmetric_difference"]) def test_difference_incomparable(self, opname): - a = Index([3, pd.Timestamp("2000"), 1]) - b = Index([2, pd.Timestamp("1999"), 1]) + a = Index([3, Timestamp("2000"), 1]) + b = Index([2, Timestamp("1999"), 1]) op = operator.methodcaller(opname, b) # sort=None, the default result = op(a) - expected = Index([3, pd.Timestamp("2000"), 2, pd.Timestamp("1999")]) + expected = Index([3, Timestamp("2000"), 2, Timestamp("1999")]) if opname == "difference": expected = expected[:2] tm.assert_index_equal(result, expected) @@ -1035,8 +1035,8 @@ def test_difference_incomparable(self, opname): def test_difference_incomparable_true(self, opname): # TODO decide on True behaviour # # sort=True, raises - a = Index([3, pd.Timestamp("2000"), 1]) - b = Index([2, pd.Timestamp("1999"), 1]) + a = Index([3, Timestamp("2000"), 1]) + b = Index([2, Timestamp("1999"), 1]) op = operator.methodcaller(opname, b, sort=True) with pytest.raises(TypeError, match="Cannot compare"): @@ -2003,7 +2003,7 @@ def test_reindex_preserves_type_if_target_is_empty_list_or_array(self, labels): [ (pd.Int64Index([]), np.int64), (pd.Float64Index([]), np.float64), - (pd.DatetimeIndex([]), np.datetime64), + (DatetimeIndex([]), np.datetime64), ], ) def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self, labels, dtype): @@ -2014,7 +2014,7 @@ def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self, labels, dty def test_reindex_no_type_preserve_target_empty_mi(self): index = Index(list("abc")) result = index.reindex( - pd.MultiIndex([pd.Int64Index([]), pd.Float64Index([])], [[], []]) + MultiIndex([pd.Int64Index([]), pd.Float64Index([])], [[], []]) )[0] assert result.levels[0].dtype.type == np.int64 assert result.levels[1].dtype.type == np.float64 @@ -2346,12 +2346,12 @@ def test_dropna(self, how, dtype, vals, expected): "index,expected", [ ( - pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]), - pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]), + DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]), + DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]), ), ( - pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03", pd.NaT]), - pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]), + DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03", pd.NaT]), + DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"]), ), ( pd.TimedeltaIndex(["1 days", "2 days", "3 days"]), @@ -2615,7 +2615,7 @@ def test_get_indexer_non_unique_wrong_dtype(ldtype, rdtype): def construct(dtype): if dtype is dtlike_dtypes[-1]: # PeriodArray will try to cast ints to strings - return pd.DatetimeIndex(vals).astype(dtype) + return DatetimeIndex(vals).astype(dtype) return Index(vals, dtype=dtype) left = construct(ldtype) diff --git a/pandas/tests/indexes/timedeltas/test_astype.py b/pandas/tests/indexes/timedeltas/test_astype.py index d274aa0b06584..a908cada5b5dc 100644 --- a/pandas/tests/indexes/timedeltas/test_astype.py +++ b/pandas/tests/indexes/timedeltas/test_astype.py @@ -107,7 +107,7 @@ def test_astype_category(self): obj = pd.timedelta_range("1H", periods=2, freq="H") result = obj.astype("category") - expected = pd.CategoricalIndex([pd.Timedelta("1H"), pd.Timedelta("2H")]) + expected = pd.CategoricalIndex([Timedelta("1H"), Timedelta("2H")]) tm.assert_index_equal(result, expected) result = obj._data.astype("category") diff --git a/pandas/tests/indexes/timedeltas/test_constructors.py b/pandas/tests/indexes/timedeltas/test_constructors.py index 09344bb5054f6..1c0104f340f75 100644 --- a/pandas/tests/indexes/timedeltas/test_constructors.py +++ b/pandas/tests/indexes/timedeltas/test_constructors.py @@ -29,7 +29,7 @@ def test_infer_from_tdi(self): # has one tdi = pd.timedelta_range("1 second", periods=10 ** 7, freq="1s") - result = pd.TimedeltaIndex(tdi, freq="infer") + result = TimedeltaIndex(tdi, freq="infer") assert result.freq == tdi.freq # check that inferred_freq was not called by checking that the @@ -89,7 +89,7 @@ def test_float64_ns_rounded(self): # NaNs get converted to NaT tdi = TimedeltaIndex([2.0, np.nan]) - expected = TimedeltaIndex([pd.Timedelta(nanoseconds=2), pd.NaT]) + expected = TimedeltaIndex([Timedelta(nanoseconds=2), pd.NaT]) tm.assert_index_equal(tdi, expected) def test_float64_unit_conversion(self): @@ -99,13 +99,13 @@ def test_float64_unit_conversion(self): tm.assert_index_equal(tdi, expected) def test_construction_base_constructor(self): - arr = [pd.Timedelta("1 days"), pd.NaT, pd.Timedelta("3 days")] - tm.assert_index_equal(pd.Index(arr), pd.TimedeltaIndex(arr)) - tm.assert_index_equal(pd.Index(np.array(arr)), pd.TimedeltaIndex(np.array(arr))) + arr = [Timedelta("1 days"), pd.NaT, Timedelta("3 days")] + tm.assert_index_equal(pd.Index(arr), TimedeltaIndex(arr)) + tm.assert_index_equal(pd.Index(np.array(arr)), TimedeltaIndex(np.array(arr))) - arr = [np.nan, pd.NaT, pd.Timedelta("1 days")] - tm.assert_index_equal(pd.Index(arr), pd.TimedeltaIndex(arr)) - tm.assert_index_equal(pd.Index(np.array(arr)), pd.TimedeltaIndex(np.array(arr))) + arr = [np.nan, pd.NaT, Timedelta("1 days")] + tm.assert_index_equal(pd.Index(arr), TimedeltaIndex(arr)) + tm.assert_index_equal(pd.Index(np.array(arr)), TimedeltaIndex(np.array(arr))) def test_constructor(self): expected = TimedeltaIndex( @@ -218,7 +218,7 @@ def test_constructor_no_precision_raises(self): msg = "with no precision is not allowed" with pytest.raises(ValueError, match=msg): - pd.TimedeltaIndex(["2000"], dtype="timedelta64") + TimedeltaIndex(["2000"], dtype="timedelta64") with pytest.raises(ValueError, match=msg): pd.Index(["2000"], dtype="timedelta64") @@ -226,7 +226,7 @@ def test_constructor_no_precision_raises(self): def test_constructor_wrong_precision_raises(self): msg = r"dtype timedelta64\[us\] cannot be converted to timedelta64\[ns\]" with pytest.raises(ValueError, match=msg): - pd.TimedeltaIndex(["2000"], dtype="timedelta64[us]") + TimedeltaIndex(["2000"], dtype="timedelta64[us]") def test_explicit_none_freq(self): # Explicitly passing freq=None is respected diff --git a/pandas/tests/indexes/timedeltas/test_ops.py b/pandas/tests/indexes/timedeltas/test_ops.py index c4429137d17f0..b74160e7e0635 100644 --- a/pandas/tests/indexes/timedeltas/test_ops.py +++ b/pandas/tests/indexes/timedeltas/test_ops.py @@ -181,13 +181,13 @@ def test_drop_duplicates(self, freq_sample, keep, expected, index): def test_infer_freq(self, freq_sample): # GH#11018 idx = pd.timedelta_range("1", freq=freq_sample, periods=10) - result = pd.TimedeltaIndex(idx.asi8, freq="infer") + result = TimedeltaIndex(idx.asi8, freq="infer") tm.assert_index_equal(idx, result) assert result.freq == freq_sample def test_repeat(self): index = pd.timedelta_range("1 days", periods=2, freq="D") - exp = pd.TimedeltaIndex(["1 days", "1 days", "2 days", "2 days"]) + exp = TimedeltaIndex(["1 days", "1 days", "2 days", "2 days"]) for res in [index.repeat(2), np.repeat(index, 2)]: tm.assert_index_equal(res, exp) assert res.freq is None @@ -211,17 +211,17 @@ def test_repeat(self): assert res.freq is None def test_nat(self): - assert pd.TimedeltaIndex._na_value is pd.NaT - assert pd.TimedeltaIndex([])._na_value is pd.NaT + assert TimedeltaIndex._na_value is pd.NaT + assert TimedeltaIndex([])._na_value is pd.NaT - idx = pd.TimedeltaIndex(["1 days", "2 days"]) + idx = TimedeltaIndex(["1 days", "2 days"]) assert idx._can_hold_na tm.assert_numpy_array_equal(idx._isnan, np.array([False, False])) assert idx.hasnans is False tm.assert_numpy_array_equal(idx._nan_idxs, np.array([], dtype=np.intp)) - idx = pd.TimedeltaIndex(["1 days", "NaT"]) + idx = TimedeltaIndex(["1 days", "NaT"]) assert idx._can_hold_na tm.assert_numpy_array_equal(idx._isnan, np.array([False, True])) @@ -230,7 +230,7 @@ def test_nat(self): def test_equals(self): # GH 13107 - idx = pd.TimedeltaIndex(["1 days", "2 days", "NaT"]) + idx = TimedeltaIndex(["1 days", "2 days", "NaT"]) assert idx.equals(idx) assert idx.equals(idx.copy()) assert idx.equals(idx.astype(object)) @@ -239,7 +239,7 @@ def test_equals(self): assert not idx.equals(list(idx)) assert not idx.equals(Series(idx)) - idx2 = pd.TimedeltaIndex(["2 days", "1 days", "NaT"]) + idx2 = TimedeltaIndex(["2 days", "1 days", "NaT"]) assert not idx.equals(idx2) assert not idx.equals(idx2.copy()) assert not idx.equals(idx2.astype(object)) diff --git a/pandas/tests/indexes/timedeltas/test_setops.py b/pandas/tests/indexes/timedeltas/test_setops.py index 6a2f66cade733..16ac70d9f23f2 100644 --- a/pandas/tests/indexes/timedeltas/test_setops.py +++ b/pandas/tests/indexes/timedeltas/test_setops.py @@ -35,7 +35,7 @@ def test_union_sort_false(self): tm.assert_index_equal(result, tdi) result = left.union(right, sort=False) - expected = pd.TimedeltaIndex(["4 Days", "5 Days", "1 Days", "2 Day", "3 Days"]) + expected = TimedeltaIndex(["4 Days", "5 Days", "1 Days", "2 Day", "3 Days"]) tm.assert_index_equal(result, expected) def test_union_coverage(self): @@ -228,7 +228,7 @@ def test_difference_freq(self, sort): def test_difference_sort(self, sort): - index = pd.TimedeltaIndex( + index = TimedeltaIndex( ["5 days", "3 days", "2 days", "4 days", "1 days", "0 days"] ) diff --git a/pandas/tests/indexes/timedeltas/test_shift.py b/pandas/tests/indexes/timedeltas/test_shift.py index 1282bd510ec17..9864f7358018e 100644 --- a/pandas/tests/indexes/timedeltas/test_shift.py +++ b/pandas/tests/indexes/timedeltas/test_shift.py @@ -14,26 +14,26 @@ class TestTimedeltaIndexShift: def test_tdi_shift_empty(self): # GH#9903 - idx = pd.TimedeltaIndex([], name="xxx") + idx = TimedeltaIndex([], name="xxx") tm.assert_index_equal(idx.shift(0, freq="H"), idx) tm.assert_index_equal(idx.shift(3, freq="H"), idx) def test_tdi_shift_hours(self): # GH#9903 - idx = pd.TimedeltaIndex(["5 hours", "6 hours", "9 hours"], name="xxx") + idx = TimedeltaIndex(["5 hours", "6 hours", "9 hours"], name="xxx") tm.assert_index_equal(idx.shift(0, freq="H"), idx) - exp = pd.TimedeltaIndex(["8 hours", "9 hours", "12 hours"], name="xxx") + exp = TimedeltaIndex(["8 hours", "9 hours", "12 hours"], name="xxx") tm.assert_index_equal(idx.shift(3, freq="H"), exp) - exp = pd.TimedeltaIndex(["2 hours", "3 hours", "6 hours"], name="xxx") + exp = TimedeltaIndex(["2 hours", "3 hours", "6 hours"], name="xxx") tm.assert_index_equal(idx.shift(-3, freq="H"), exp) def test_tdi_shift_minutes(self): # GH#9903 - idx = pd.TimedeltaIndex(["5 hours", "6 hours", "9 hours"], name="xxx") + idx = TimedeltaIndex(["5 hours", "6 hours", "9 hours"], name="xxx") tm.assert_index_equal(idx.shift(0, freq="T"), idx) - exp = pd.TimedeltaIndex(["05:03:00", "06:03:00", "9:03:00"], name="xxx") + exp = TimedeltaIndex(["05:03:00", "06:03:00", "9:03:00"], name="xxx") tm.assert_index_equal(idx.shift(3, freq="T"), exp) - exp = pd.TimedeltaIndex(["04:57:00", "05:57:00", "8:57:00"], name="xxx") + exp = TimedeltaIndex(["04:57:00", "05:57:00", "8:57:00"], name="xxx") tm.assert_index_equal(idx.shift(-3, freq="T"), exp) def test_tdi_shift_int(self): diff --git a/pandas/tests/indexing/multiindex/test_loc.py b/pandas/tests/indexing/multiindex/test_loc.py index 2cb5b55f14596..d79af1ea6b804 100644 --- a/pandas/tests/indexing/multiindex/test_loc.py +++ b/pandas/tests/indexing/multiindex/test_loc.py @@ -447,7 +447,7 @@ def test_loc_period_string_indexing(): # GH 9892 a = pd.period_range("2013Q1", "2013Q4", freq="Q") i = (1111, 2222, 3333) - idx = pd.MultiIndex.from_product((a, i), names=("Periode", "CVR")) + idx = MultiIndex.from_product((a, i), names=("Periode", "CVR")) df = DataFrame( index=idx, columns=( @@ -467,7 +467,7 @@ def test_loc_period_string_indexing(): [np.nan], dtype=object, name="OMS", - index=pd.MultiIndex.from_tuples( + index=MultiIndex.from_tuples( [(pd.Period("2013Q1"), 1111)], names=["Periode", "CVR"] ), ) @@ -477,7 +477,7 @@ def test_loc_period_string_indexing(): def test_loc_datetime_mask_slicing(): # GH 16699 dt_idx = pd.to_datetime(["2017-05-04", "2017-05-05"]) - m_idx = pd.MultiIndex.from_product([dt_idx, dt_idx], names=["Idx1", "Idx2"]) + m_idx = MultiIndex.from_product([dt_idx, dt_idx], names=["Idx1", "Idx2"]) df = DataFrame( data=[[1, 2], [3, 4], [5, 6], [7, 6]], index=m_idx, columns=["C1", "C2"] ) @@ -498,7 +498,7 @@ def test_loc_datetime_series_tuple_slicing(): date = pd.Timestamp("2000") ser = Series( 1, - index=pd.MultiIndex.from_tuples([("a", date)], names=["a", "b"]), + index=MultiIndex.from_tuples([("a", date)], names=["a", "b"]), name="c", ) result = ser.loc[:, [date]] @@ -568,7 +568,7 @@ def test_3levels_leading_period_index(): ) lev2 = ["A", "A", "Z", "W"] lev3 = ["B", "C", "Q", "F"] - mi = pd.MultiIndex.from_arrays([pi, lev2, lev3]) + mi = MultiIndex.from_arrays([pi, lev2, lev3]) ser = Series(range(4), index=mi, dtype=np.float64) result = ser.loc[(pi[0], "A", "B")] @@ -586,7 +586,7 @@ def test_missing_keys_raises_keyerror(self): def test_missing_key_raises_keyerror2(self): # GH#21168 KeyError, not "IndexingError: Too many indexers" - ser = Series(-1, index=pd.MultiIndex.from_product([[0, 1]] * 2)) + ser = Series(-1, index=MultiIndex.from_product([[0, 1]] * 2)) with pytest.raises(KeyError, match=r"\(0, 3\)"): ser.loc[0, 3] diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py index 059f8543104a7..543416126f12c 100644 --- a/pandas/tests/indexing/multiindex/test_setitem.py +++ b/pandas/tests/indexing/multiindex/test_setitem.py @@ -427,7 +427,7 @@ def test_astype_assignment_with_dups(self): def test_setitem_nonmonotonic(self): # https://github.com/pandas-dev/pandas/issues/31449 - index = pd.MultiIndex.from_tuples( + index = MultiIndex.from_tuples( [("a", "c"), ("b", "x"), ("a", "d")], names=["l1", "l2"] ) df = DataFrame(data=[0, 1, 2], index=index, columns=["e"]) diff --git a/pandas/tests/indexing/test_datetime.py b/pandas/tests/indexing/test_datetime.py index 5e00056c33db7..4879f805b5a2d 100644 --- a/pandas/tests/indexing/test_datetime.py +++ b/pandas/tests/indexing/test_datetime.py @@ -304,12 +304,8 @@ def test_loc_getitem_across_dst(self): ) series2 = Series([0, 1, 2, 3, 4], index=idx) - t_1 = pd.Timestamp( - "2017-10-29 02:30:00+02:00", tz="Europe/Berlin", freq="30min" - ) - t_2 = pd.Timestamp( - "2017-10-29 02:00:00+01:00", tz="Europe/Berlin", freq="30min" - ) + t_1 = Timestamp("2017-10-29 02:30:00+02:00", tz="Europe/Berlin", freq="30min") + t_2 = Timestamp("2017-10-29 02:00:00+01:00", tz="Europe/Berlin", freq="30min") result = series2.loc[t_1:t_2] expected = Series([2, 3], index=idx[2:4]) tm.assert_series_equal(result, expected) @@ -330,9 +326,9 @@ def test_loc_incremental_setitem_with_dst(self): def test_loc_setitem_with_existing_dst(self): # GH 18308 - start = pd.Timestamp("2017-10-29 00:00:00+0200", tz="Europe/Madrid") - end = pd.Timestamp("2017-10-29 03:00:00+0100", tz="Europe/Madrid") - ts = pd.Timestamp("2016-10-10 03:00:00", tz="Europe/Madrid") + start = Timestamp("2017-10-29 00:00:00+0200", tz="Europe/Madrid") + end = Timestamp("2017-10-29 03:00:00+0100", tz="Europe/Madrid") + ts = Timestamp("2016-10-10 03:00:00", tz="Europe/Madrid") idx = pd.date_range(start, end, closed="left", freq="H") result = DataFrame(index=idx, columns=["value"]) result.loc[ts, "value"] = 12 diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 9d1a2bed5db12..689cdbce103e6 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -1072,7 +1072,7 @@ def test_datetime_block_can_hold_element(self): class TestShouldStore: def test_should_store_categorical(self): - cat = pd.Categorical(["A", "B", "C"]) + cat = Categorical(["A", "B", "C"]) df = DataFrame(cat) blk = df._mgr.blocks[0] @@ -1114,7 +1114,7 @@ def test_validate_ndim(): def test_block_shape(): idx = Index([0, 1, 2, 3, 4]) a = Series([1, 2, 3]).reindex(idx) - b = Series(pd.Categorical([1, 2, 3])).reindex(idx) + b = Series(Categorical([1, 2, 3])).reindex(idx) assert a._mgr.blocks[0].mgr_locs.indexer == b._mgr.blocks[0].mgr_locs.indexer diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index c474e67123ef7..ec0a32318ec34 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -992,7 +992,7 @@ def test_no_header_with_list_index_col(self, read_ext): # GH 31783 file_name = "testmultiindex" + read_ext data = [("B", "B"), ("key", "val"), (3, 4), (3, 4)] - idx = pd.MultiIndex.from_tuples( + idx = MultiIndex.from_tuples( [("A", "A"), ("key", "val"), (1, 2), (1, 2)], names=(0, 1) ) expected = DataFrame(data, index=idx, columns=(2, 3)) @@ -1168,9 +1168,7 @@ def test_excel_high_surrogate(self, engine): def test_header_with_index_col(self, engine, filename): # GH 33476 idx = Index(["Z"], name="I2") - cols = pd.MultiIndex.from_tuples( - [("A", "B"), ("A", "B.1")], names=["I11", "I12"] - ) + cols = MultiIndex.from_tuples([("A", "B"), ("A", "B.1")], names=["I11", "I12"]) expected = DataFrame([[1, 3]], index=idx, columns=cols, dtype="int64") result = pd.read_excel( filename, sheet_name="Sheet1", index_col=0, header=[0, 1] @@ -1185,7 +1183,7 @@ def test_read_datetime_multiindex(self, engine, read_ext): f = "test_datetime_mi" + read_ext with pd.ExcelFile(f) as excel: actual = pd.read_excel(excel, header=[0, 1], index_col=0, engine=engine) - expected_column_index = pd.MultiIndex.from_tuples( + expected_column_index = MultiIndex.from_tuples( [(pd.to_datetime("02/29/2020"), pd.to_datetime("03/01/2020"))], names=[ pd.to_datetime("02/29/2020").to_pydatetime(), diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index 72b28c71b6511..b3cf7a6828808 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -1009,7 +1009,7 @@ def test_datetimelike_frame(self): # GH 12211 df = DataFrame( - {"date": [pd.Timestamp("20130101").tz_localize("UTC")] + [pd.NaT] * 5} + {"date": [Timestamp("20130101").tz_localize("UTC")] + [pd.NaT] * 5} ) with option_context("display.max_rows", 5): @@ -1019,7 +1019,7 @@ def test_datetimelike_frame(self): assert "..." in result assert "[6 rows x 1 columns]" in result - dts = [pd.Timestamp("2011-01-01", tz="US/Eastern")] * 5 + [pd.NaT] * 5 + dts = [Timestamp("2011-01-01", tz="US/Eastern")] * 5 + [pd.NaT] * 5 df = DataFrame({"dt": dts, "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}) with option_context("display.max_rows", 5): expected = ( @@ -1033,7 +1033,7 @@ def test_datetimelike_frame(self): ) assert repr(df) == expected - dts = [pd.NaT] * 5 + [pd.Timestamp("2011-01-01", tz="US/Eastern")] * 5 + dts = [pd.NaT] * 5 + [Timestamp("2011-01-01", tz="US/Eastern")] * 5 df = DataFrame({"dt": dts, "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}) with option_context("display.max_rows", 5): expected = ( @@ -1047,8 +1047,8 @@ def test_datetimelike_frame(self): ) assert repr(df) == expected - dts = [pd.Timestamp("2011-01-01", tz="Asia/Tokyo")] * 5 + [ - pd.Timestamp("2011-01-01", tz="US/Eastern") + dts = [Timestamp("2011-01-01", tz="Asia/Tokyo")] * 5 + [ + Timestamp("2011-01-01", tz="US/Eastern") ] * 5 df = DataFrame({"dt": dts, "x": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]}) with option_context("display.max_rows", 5): @@ -2184,7 +2184,7 @@ def test_east_asian_unicode_series(self): # object dtype, longer than unicode repr s = Series( - [1, 22, 3333, 44444], index=[1, "AB", pd.Timestamp("2011-01-01"), "あああ"] + [1, 22, 3333, 44444], index=[1, "AB", Timestamp("2011-01-01"), "あああ"] ) expected = ( "1 1\n" @@ -2282,7 +2282,7 @@ def test_east_asian_unicode_series(self): # object dtype, longer than unicode repr s = Series( [1, 22, 3333, 44444], - index=[1, "AB", pd.Timestamp("2011-01-01"), "あああ"], + index=[1, "AB", Timestamp("2011-01-01"), "あああ"], ) expected = ( "1 1\n" diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index 71698a02285f9..6e35b224ef4c3 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -252,7 +252,7 @@ def test_read_json_from_to_json_results(self): } ) result1 = pd.read_json(df.to_json()) - result2 = pd.DataFrame.from_dict(json.loads(df.to_json())) + result2 = DataFrame.from_dict(json.loads(df.to_json())) tm.assert_frame_equal(result1, df) tm.assert_frame_equal(result2, df) diff --git a/pandas/tests/io/json/test_pandas.py b/pandas/tests/io/json/test_pandas.py index 92cc0f969ec87..47b7bd0983305 100644 --- a/pandas/tests/io/json/test_pandas.py +++ b/pandas/tests/io/json/test_pandas.py @@ -448,8 +448,8 @@ def test_v12_compat(self, datapath): columns=["A", "B", "C", "D"], index=dti, ) - df["date"] = pd.Timestamp("19920106 18:21:32.12") - df.iloc[3, df.columns.get_loc("date")] = pd.Timestamp("20130101") + df["date"] = Timestamp("19920106 18:21:32.12") + df.iloc[3, df.columns.get_loc("date")] = Timestamp("20130101") df["modified"] = df["date"] df.iloc[1, df.columns.get_loc("modified")] = pd.NaT @@ -788,9 +788,7 @@ def test_convert_dates(self, datetime_series, datetime_frame): @pytest.mark.parametrize("date_format", ["epoch", "iso"]) @pytest.mark.parametrize("as_object", [True, False]) - @pytest.mark.parametrize( - "date_typ", [datetime.date, datetime.datetime, pd.Timestamp] - ) + @pytest.mark.parametrize("date_typ", [datetime.date, datetime.datetime, Timestamp]) def test_date_index_and_values(self, date_format, as_object, date_typ): data = [date_typ(year=2020, month=1, day=1), pd.NaT] if as_object: @@ -1023,12 +1021,10 @@ def test_timedelta(self): tm.assert_frame_equal(frame, result) def test_mixed_timedelta_datetime(self): - frame = DataFrame( - {"a": [timedelta(23), pd.Timestamp("20130101")]}, dtype=object - ) + frame = DataFrame({"a": [timedelta(23), Timestamp("20130101")]}, dtype=object) expected = DataFrame( - {"a": [pd.Timedelta(frame.a[0]).value, pd.Timestamp(frame.a[1]).value]} + {"a": [pd.Timedelta(frame.a[0]).value, Timestamp(frame.a[1]).value]} ) result = pd.read_json(frame.to_json(date_unit="ns"), dtype={"a": "int64"}) tm.assert_frame_equal(result, expected, check_index_type=False) diff --git a/pandas/tests/io/parser/test_parse_dates.py b/pandas/tests/io/parser/test_parse_dates.py index 662659982c0b3..7a5203ca86520 100644 --- a/pandas/tests/io/parser/test_parse_dates.py +++ b/pandas/tests/io/parser/test_parse_dates.py @@ -641,7 +641,7 @@ def test_nat_parse(all_parsers): # see gh-3062 parser = all_parsers df = DataFrame( - dict({"A": np.arange(10, dtype="float64"), "B": pd.Timestamp("20010101")}) + dict({"A": np.arange(10, dtype="float64"), "B": Timestamp("20010101")}) ) df.iloc[3:6, :] = np.nan @@ -1472,7 +1472,7 @@ def test_parse_timezone(all_parsers): 2018-01-04 09:05:00+09:00,23400""" result = parser.read_csv(StringIO(data), parse_dates=["dt"]) - dti = pd.DatetimeIndex( + dti = DatetimeIndex( list( pd.date_range( start="2018-01-04 09:01:00", diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index 2437ba77532fa..f37b0aabd3aed 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -1918,7 +1918,7 @@ def test_select_columns_in_where(self, setup_path): def test_mi_data_columns(self, setup_path): # GH 14435 - idx = pd.MultiIndex.from_arrays( + idx = MultiIndex.from_arrays( [date_range("2000-01-01", periods=5), range(5)], names=["date", "id"] ) df = DataFrame({"a": [1.1, 1.2, 1.3, 1.4, 1.5]}, index=idx) @@ -2325,7 +2325,7 @@ def test_same_name_scoping(self, setup_path): np.random.randn(20, 2), index=pd.date_range("20130101", periods=20) ) store.put("df", df, format="table") - expected = df[df.index > pd.Timestamp("20130105")] + expected = df[df.index > Timestamp("20130105")] import datetime @@ -4152,7 +4152,7 @@ def test_legacy_table_fixed_format_read_datetime_py2(self, datapath, setup_path) ) as store: result = store.select("df") expected = DataFrame( - [[pd.Timestamp("2020-02-06T18:00")]], + [[Timestamp("2020-02-06T18:00")]], columns=["A"], index=Index(["date"]), ) @@ -4768,14 +4768,14 @@ def test_query_compare_column_type(self, setup_path): with ensure_clean_store(setup_path) as store: store.append("test", df, format="table", data_columns=True) - ts = pd.Timestamp("2014-01-01") # noqa + ts = Timestamp("2014-01-01") # noqa result = store.select("test", where="real_date > ts") expected = df.loc[[1], :] tm.assert_frame_equal(expected, result) for op in ["<", ">", "=="]: # non strings to string column always fail - for v in [2.1, True, pd.Timestamp("2014-01-01"), pd.Timedelta(1, "s")]: + for v in [2.1, True, Timestamp("2014-01-01"), pd.Timedelta(1, "s")]: query = f"date {op} v" with pytest.raises(TypeError): store.select("test", where=query) diff --git a/pandas/tests/io/pytables/test_timezones.py b/pandas/tests/io/pytables/test_timezones.py index e137bc2dca48e..cc418bc52cae1 100644 --- a/pandas/tests/io/pytables/test_timezones.py +++ b/pandas/tests/io/pytables/test_timezones.py @@ -212,7 +212,7 @@ def test_append_with_timezones_pytz(setup_path): def test_roundtrip_tz_aware_index(setup_path): # GH 17618 - time = pd.Timestamp("2000-01-01 01:00:00", tz="US/Eastern") + time = Timestamp("2000-01-01 01:00:00", tz="US/Eastern") df = DataFrame(data=[0], index=[time]) with ensure_clean_store(setup_path) as store: @@ -225,7 +225,7 @@ def test_roundtrip_tz_aware_index(setup_path): def test_store_index_name_with_tz(setup_path): # GH 13884 df = DataFrame({"A": [1, 2]}) - df.index = pd.DatetimeIndex([1234567890123456787, 1234567890123456788]) + df.index = DatetimeIndex([1234567890123456787, 1234567890123456788]) df.index = df.index.tz_localize("UTC") df.index.name = "foo" @@ -402,7 +402,7 @@ def test_py2_created_with_datetimez(datapath, setup_path): # Python 3. # # GH26443 - index = [pd.Timestamp("2019-01-01T18:00").tz_localize("America/New_York")] + index = [Timestamp("2019-01-01T18:00").tz_localize("America/New_York")] expected = DataFrame({"data": 123}, index=index) with ensure_clean_store( datapath("io", "data", "legacy_hdf", "gh26443.h5"), mode="r" diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index d6506d434d6a7..19eb64be1be29 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -697,8 +697,8 @@ def test_date_parsing(self): ) assert issubclass(df.DateCol.dtype.type, np.datetime64) assert df.DateCol.tolist() == [ - pd.Timestamp(2000, 1, 3, 0, 0, 0), - pd.Timestamp(2000, 1, 4, 0, 0, 0), + Timestamp(2000, 1, 3, 0, 0, 0), + Timestamp(2000, 1, 4, 0, 0, 0), ] df = sql.read_sql_query( @@ -708,8 +708,8 @@ def test_date_parsing(self): ) assert issubclass(df.DateCol.dtype.type, np.datetime64) assert df.DateCol.tolist() == [ - pd.Timestamp(2000, 1, 3, 0, 0, 0), - pd.Timestamp(2000, 1, 4, 0, 0, 0), + Timestamp(2000, 1, 3, 0, 0, 0), + Timestamp(2000, 1, 4, 0, 0, 0), ] df = sql.read_sql_query( @@ -717,8 +717,8 @@ def test_date_parsing(self): ) assert issubclass(df.IntDateCol.dtype.type, np.datetime64) assert df.IntDateCol.tolist() == [ - pd.Timestamp(1986, 12, 25, 0, 0, 0), - pd.Timestamp(2013, 1, 1, 0, 0, 0), + Timestamp(1986, 12, 25, 0, 0, 0), + Timestamp(2013, 1, 1, 0, 0, 0), ] df = sql.read_sql_query( @@ -726,8 +726,8 @@ def test_date_parsing(self): ) assert issubclass(df.IntDateCol.dtype.type, np.datetime64) assert df.IntDateCol.tolist() == [ - pd.Timestamp(1986, 12, 25, 0, 0, 0), - pd.Timestamp(2013, 1, 1, 0, 0, 0), + Timestamp(1986, 12, 25, 0, 0, 0), + Timestamp(2013, 1, 1, 0, 0, 0), ] df = sql.read_sql_query( @@ -737,8 +737,8 @@ def test_date_parsing(self): ) assert issubclass(df.IntDateOnlyCol.dtype.type, np.datetime64) assert df.IntDateOnlyCol.tolist() == [ - pd.Timestamp("2010-10-10"), - pd.Timestamp("2010-12-12"), + Timestamp("2010-10-10"), + Timestamp("2010-12-12"), ] def test_date_and_index(self): diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index fecffd75f9478..b065aa187f5fb 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -990,7 +990,7 @@ def test_categorical_writing(self, version): def test_categorical_warnings_and_errors(self): # Warning for non-string labels # Error for labels too long - original = pd.DataFrame.from_records( + original = DataFrame.from_records( [["a" * 10000], ["b" * 10000], ["c" * 10000], ["d" * 10000]], columns=["Too_long"], ) @@ -1006,7 +1006,7 @@ def test_categorical_warnings_and_errors(self): with pytest.raises(ValueError, match=msg): original.to_stata(path) - original = pd.DataFrame.from_records( + original = DataFrame.from_records( [["a"], ["b"], ["c"], ["d"], [1]], columns=["Too_long"] ) original = pd.concat( @@ -1021,7 +1021,7 @@ def test_categorical_warnings_and_errors(self): def test_categorical_with_stata_missing_values(self, version): values = [["a" + str(i)] for i in range(120)] values.append([np.nan]) - original = pd.DataFrame.from_records(values, columns=["many_labels"]) + original = DataFrame.from_records(values, columns=["many_labels"]) original = pd.concat( [original[col].astype("category") for col in original], axis=1 ) diff --git a/pandas/tests/reductions/test_reductions.py b/pandas/tests/reductions/test_reductions.py index cc86436ee8fa9..1e84ba1dbffd9 100644 --- a/pandas/tests/reductions/test_reductions.py +++ b/pandas/tests/reductions/test_reductions.py @@ -184,7 +184,7 @@ def test_same_tz_min_max_axis_1(self, op, expected_col): df = DataFrame( pd.date_range("2016-01-01 00:00:00", periods=3, tz="UTC"), columns=["a"] ) - df["b"] = df.a.subtract(pd.Timedelta(seconds=3600)) + df["b"] = df.a.subtract(Timedelta(seconds=3600)) result = getattr(df, op)(axis=1) expected = df[expected_col].rename(None) tm.assert_series_equal(result, expected) @@ -364,11 +364,11 @@ def test_invalid_td64_reductions(self, opname): def test_minmax_tz(self, tz_naive_fixture): tz = tz_naive_fixture # monotonic - idx1 = pd.DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"], tz=tz) + idx1 = DatetimeIndex(["2011-01-01", "2011-01-02", "2011-01-03"], tz=tz) assert idx1.is_monotonic # non-monotonic - idx2 = pd.DatetimeIndex( + idx2 = DatetimeIndex( ["2011-01-01", pd.NaT, "2011-01-03", "2011-01-02", pd.NaT], tz=tz ) assert not idx2.is_monotonic @@ -927,7 +927,7 @@ def test_timedelta64_analytics(self): # index min/max dti = pd.date_range("2012-1-1", periods=3, freq="D") - td = Series(dti) - pd.Timestamp("20120101") + td = Series(dti) - Timestamp("20120101") result = td.idxmin() assert result == 0 @@ -958,11 +958,11 @@ def test_timedelta64_analytics(self): # max/min result = td.max() - expected = pd.Timedelta("2 days") + expected = Timedelta("2 days") assert result == expected result = td.min() - expected = pd.Timedelta("1 days") + expected = Timedelta("1 days") assert result == expected @pytest.mark.parametrize( @@ -1017,8 +1017,8 @@ class TestDatetime64SeriesReductions: "nat_ser", [ Series([pd.NaT, pd.NaT]), - Series([pd.NaT, pd.Timedelta("nat")]), - Series([pd.Timedelta("nat"), pd.Timedelta("nat")]), + Series([pd.NaT, Timedelta("nat")]), + Series([Timedelta("nat"), Timedelta("nat")]), ], ) def test_minmax_nat_series(self, nat_ser): @@ -1032,8 +1032,8 @@ def test_minmax_nat_series(self, nat_ser): "nat_df", [ DataFrame([pd.NaT, pd.NaT]), - DataFrame([pd.NaT, pd.Timedelta("nat")]), - DataFrame([pd.Timedelta("nat"), pd.Timedelta("nat")]), + DataFrame([pd.NaT, Timedelta("nat")]), + DataFrame([Timedelta("nat"), Timedelta("nat")]), ], ) def test_minmax_nat_dataframe(self, nat_df): @@ -1049,8 +1049,8 @@ def test_min_max(self): the_min = rng2.min() the_max = rng2.max() - assert isinstance(the_min, pd.Timestamp) - assert isinstance(the_max, pd.Timestamp) + assert isinstance(the_min, Timestamp) + assert isinstance(the_max, Timestamp) assert the_min == rng[0] assert the_max == rng[-1] @@ -1063,13 +1063,13 @@ def test_min_max_series(self): df = DataFrame({"TS": rng, "V": np.random.randn(len(rng)), "L": lvls}) result = df.TS.max() - exp = pd.Timestamp(df.TS.iat[-1]) - assert isinstance(result, pd.Timestamp) + exp = Timestamp(df.TS.iat[-1]) + assert isinstance(result, Timestamp) assert result == exp result = df.TS.min() - exp = pd.Timestamp(df.TS.iat[0]) - assert isinstance(result, pd.Timestamp) + exp = Timestamp(df.TS.iat[0]) + assert isinstance(result, Timestamp) assert result == exp diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index 19e5a5dd7f5e7..7681807b60989 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -63,7 +63,7 @@ def test_custom_grouper(index): arr = [1] + [5] * 2592 idx = dti[0:-1:5] idx = idx.append(dti[-1:]) - idx = pd.DatetimeIndex(idx, freq="5T") + idx = DatetimeIndex(idx, freq="5T") expect = Series(arr, index=idx) # GH2763 - return in put dtype if we can @@ -440,7 +440,7 @@ def test_resample_how_method(): ) expected = Series( [11, np.NaN, np.NaN, np.NaN, np.NaN, np.NaN, 22], - index=pd.DatetimeIndex( + index=DatetimeIndex( [ Timestamp("2015-03-31 21:48:50"), Timestamp("2015-03-31 21:49:00"), @@ -722,7 +722,7 @@ def test_resample_single_group(): [30.1, 31.6], index=[Timestamp("20070915 15:30:00"), Timestamp("20070915 15:40:00")], ) - expected = Series([0.75], index=pd.DatetimeIndex([Timestamp("20070915")], freq="D")) + expected = Series([0.75], index=DatetimeIndex([Timestamp("20070915")], freq="D")) result = s.resample("D").apply(lambda x: np.std(x)) tm.assert_series_equal(result, expected) @@ -748,7 +748,7 @@ def test_resample_origin(): resampled = ts.resample("5min", origin="1999-12-31 23:57:00").mean() tm.assert_index_equal(resampled.index, exp_rng) - offset_timestamp = pd.Timestamp(0) + pd.Timedelta("2min") + offset_timestamp = Timestamp(0) + Timedelta("2min") resampled = ts.resample("5min", origin=offset_timestamp).mean() tm.assert_index_equal(resampled.index, exp_rng) @@ -879,14 +879,14 @@ def test_resample_origin_with_day_freq_on_dst(): def _create_series(values, timestamps, freq="D"): return Series( values, - index=pd.DatetimeIndex( + index=DatetimeIndex( [Timestamp(t, tz=tz) for t in timestamps], freq=freq, ambiguous=True ), ) # test classical behavior of origin in a DST context - start = pd.Timestamp("2013-11-02", tz=tz) - end = pd.Timestamp("2013-11-03 23:59", tz=tz) + start = Timestamp("2013-11-02", tz=tz) + end = Timestamp("2013-11-03 23:59", tz=tz) rng = pd.date_range(start, end, freq="1h") ts = Series(np.ones(len(rng)), index=rng) @@ -896,8 +896,8 @@ def _create_series(values, timestamps, freq="D"): tm.assert_series_equal(result, expected) # test complex behavior of origin/offset in a DST context - start = pd.Timestamp("2013-11-03", tz=tz) - end = pd.Timestamp("2013-11-03 23:59", tz=tz) + start = Timestamp("2013-11-03", tz=tz) + end = Timestamp("2013-11-03 23:59", tz=tz) rng = pd.date_range(start, end, freq="1h") ts = Series(np.ones(len(rng)), index=rng) @@ -1275,7 +1275,7 @@ def test_resample_timegrouper(): for dates in [dates1, dates2, dates3]: df = DataFrame(dict(A=dates, B=np.arange(len(dates)))) result = df.set_index("A").resample("M").count() - exp_idx = pd.DatetimeIndex( + exp_idx = DatetimeIndex( ["2014-07-31", "2014-08-31", "2014-09-30", "2014-10-31", "2014-11-30"], freq="M", name="A", @@ -1438,7 +1438,7 @@ def test_resample_across_dst(): def test_groupby_with_dst_time_change(): # GH 24972 - index = pd.DatetimeIndex( + index = DatetimeIndex( [1478064900001000000, 1480037118776792000], tz="UTC" ).tz_convert("America/Chicago") @@ -1448,7 +1448,7 @@ def test_groupby_with_dst_time_change(): "2016-11-02", "2016-11-24", freq="d", tz="America/Chicago" ) - index = pd.DatetimeIndex(expected_index_values) + index = DatetimeIndex(expected_index_values) expected = DataFrame([1.0] + ([np.nan] * 21) + [2.0], index=index) tm.assert_frame_equal(result, expected) @@ -1563,7 +1563,7 @@ def test_downsample_across_dst_weekly(): result = df.resample("1W").sum() expected = DataFrame( [23, 42], - index=pd.DatetimeIndex( + index=DatetimeIndex( ["2017-03-26", "2017-04-02"], tz="Europe/Amsterdam", freq="W" ), ) @@ -1592,7 +1592,7 @@ def test_downsample_dst_at_midnight(): dti = date_range("2018-11-03", periods=3).tz_localize( "America/Havana", ambiguous=True ) - dti = pd.DatetimeIndex(dti, freq="D") + dti = DatetimeIndex(dti, freq="D") expected = DataFrame([7.5, 28.0, 44.5], index=dti) tm.assert_frame_equal(result, expected) @@ -1714,8 +1714,8 @@ def test_get_timestamp_range_edges(first, last, freq, exp_first, exp_last): last = pd.Period(last) last = last.to_timestamp(last.freq) - exp_first = pd.Timestamp(exp_first, freq=freq) - exp_last = pd.Timestamp(exp_last, freq=freq) + exp_first = Timestamp(exp_first, freq=freq) + exp_last = Timestamp(exp_last, freq=freq) freq = pd.tseries.frequencies.to_offset(freq) result = _get_timestamp_range_edges(first, last, freq) diff --git a/pandas/tests/resample/test_resampler_grouper.py b/pandas/tests/resample/test_resampler_grouper.py index ca31ef684257d..15dd49f8bf182 100644 --- a/pandas/tests/resample/test_resampler_grouper.py +++ b/pandas/tests/resample/test_resampler_grouper.py @@ -155,7 +155,7 @@ def test_groupby_with_origin(): tm.assert_index_equal(count_ts.index, count_ts2.index) # test origin on 1970-01-01 00:00:00 - origin = pd.Timestamp(0) + origin = Timestamp(0) adjusted_grouper = pd.Grouper(freq=freq, origin=origin) adjusted_count_ts = ts.groupby(adjusted_grouper).agg("count") adjusted_count_ts = adjusted_count_ts[middle:end] @@ -163,7 +163,7 @@ def test_groupby_with_origin(): tm.assert_series_equal(adjusted_count_ts, adjusted_count_ts2) # test origin on 2049-10-18 20:00:00 - origin_future = pd.Timestamp(0) + pd.Timedelta("1399min") * 30_000 + origin_future = Timestamp(0) + pd.Timedelta("1399min") * 30_000 adjusted_grouper2 = pd.Grouper(freq=freq, origin=origin_future) adjusted2_count_ts = ts.groupby(adjusted_grouper2).agg("count") adjusted2_count_ts = adjusted2_count_ts[middle:end] diff --git a/pandas/tests/reshape/concat/test_append_common.py b/pandas/tests/reshape/concat/test_append_common.py index 395673e9a47ab..8b7fb69f7ee05 100644 --- a/pandas/tests/reshape/concat/test_append_common.py +++ b/pandas/tests/reshape/concat/test_append_common.py @@ -40,7 +40,7 @@ def setup_method(self, method): "bool": [True, False, True], "int64": [1, 2, 3], "float64": [1.1, np.nan, 3.3], - "category": pd.Categorical(["X", "Y", "Z"]), + "category": Categorical(["X", "Y", "Z"]), "object": ["a", "b", "c"], "datetime64[ns]": dt_data, "datetime64[ns, US/Eastern]": tz_data, @@ -80,8 +80,8 @@ def test_concatlike_same_dtypes(self): vals3 = vals1 if typ1 == "category": - exp_data = pd.Categorical(list(vals1) + list(vals2)) - exp_data3 = pd.Categorical(list(vals1) + list(vals2) + list(vals3)) + exp_data = Categorical(list(vals1) + list(vals2)) + exp_data3 = Categorical(list(vals1) + list(vals2) + list(vals3)) else: exp_data = vals1 + vals2 exp_data3 = vals1 + vals2 + vals3 @@ -637,16 +637,14 @@ def test_concat_categorical_multi_coercion(self): def test_concat_categorical_ordered(self): # GH 13524 - s1 = Series(pd.Categorical([1, 2, np.nan], ordered=True)) - s2 = Series(pd.Categorical([2, 1, 2], ordered=True)) + s1 = Series(Categorical([1, 2, np.nan], ordered=True)) + s2 = Series(Categorical([2, 1, 2], ordered=True)) - exp = Series(pd.Categorical([1, 2, np.nan, 2, 1, 2], ordered=True)) + exp = Series(Categorical([1, 2, np.nan, 2, 1, 2], ordered=True)) tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - exp = Series( - pd.Categorical([1, 2, np.nan, 2, 1, 2, 1, 2, np.nan], ordered=True) - ) + exp = Series(Categorical([1, 2, np.nan, 2, 1, 2, 1, 2, np.nan], ordered=True)) tm.assert_series_equal(pd.concat([s1, s2, s1], ignore_index=True), exp) tm.assert_series_equal(s1.append([s2, s1], ignore_index=True), exp) diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py index 90172abefb8c4..a1351ce782669 100644 --- a/pandas/tests/reshape/concat/test_concat.py +++ b/pandas/tests/reshape/concat/test_concat.py @@ -514,7 +514,7 @@ def test_duplicate_keys(keys): s2 = Series([10, 11, 12], name="d") result = concat([df, s1, s2], axis=1, keys=keys) expected_values = [[1, 4, 7, 10], [2, 5, 8, 11], [3, 6, 9, 12]] - expected_columns = pd.MultiIndex.from_tuples( + expected_columns = MultiIndex.from_tuples( [(keys[0], "a"), (keys[0], "b"), (keys[1], "c"), (keys[2], "d")] ) expected = DataFrame(expected_values, columns=expected_columns) diff --git a/pandas/tests/reshape/concat/test_datetimes.py b/pandas/tests/reshape/concat/test_datetimes.py index 8783f539faa65..a4d6b58307523 100644 --- a/pandas/tests/reshape/concat/test_datetimes.py +++ b/pandas/tests/reshape/concat/test_datetimes.py @@ -205,15 +205,15 @@ def test_concat_NaT_dataframes(self, tz): first = DataFrame([[pd.NaT], [pd.NaT]]) first = first.apply(lambda x: x.dt.tz_localize(tz)) second = DataFrame( - [[pd.Timestamp("2015/01/01", tz=tz)], [pd.Timestamp("2016/01/01", tz=tz)]], + [[Timestamp("2015/01/01", tz=tz)], [Timestamp("2016/01/01", tz=tz)]], index=[2, 3], ) expected = DataFrame( [ pd.NaT, pd.NaT, - pd.Timestamp("2015/01/01", tz=tz), - pd.Timestamp("2016/01/01", tz=tz), + Timestamp("2015/01/01", tz=tz), + Timestamp("2016/01/01", tz=tz), ] ) @@ -222,7 +222,7 @@ def test_concat_NaT_dataframes(self, tz): @pytest.mark.parametrize("tz1", [None, "UTC"]) @pytest.mark.parametrize("tz2", [None, "UTC"]) - @pytest.mark.parametrize("s", [pd.NaT, pd.Timestamp("20150101")]) + @pytest.mark.parametrize("s", [pd.NaT, Timestamp("20150101")]) def test_concat_NaT_dataframes_all_NaT_axis_0(self, tz1, tz2, s): # GH 12396 @@ -263,8 +263,8 @@ def test_concat_NaT_series_dataframe_all_NaT(self, tz1, tz2): first = Series([pd.NaT, pd.NaT]).dt.tz_localize(tz1) second = DataFrame( [ - [pd.Timestamp("2015/01/01", tz=tz2)], - [pd.Timestamp("2016/01/01", tz=tz2)], + [Timestamp("2015/01/01", tz=tz2)], + [Timestamp("2016/01/01", tz=tz2)], ], index=[2, 3], ) @@ -273,8 +273,8 @@ def test_concat_NaT_series_dataframe_all_NaT(self, tz1, tz2): [ pd.NaT, pd.NaT, - pd.Timestamp("2015/01/01", tz=tz2), - pd.Timestamp("2016/01/01", tz=tz2), + Timestamp("2015/01/01", tz=tz2), + Timestamp("2016/01/01", tz=tz2), ] ) if tz1 != tz2: @@ -344,12 +344,12 @@ def test_concat_tz_series(self): def test_concat_tz_series_tzlocal(self): # see gh-13583 x = [ - pd.Timestamp("2011-01-01", tz=dateutil.tz.tzlocal()), - pd.Timestamp("2011-02-01", tz=dateutil.tz.tzlocal()), + Timestamp("2011-01-01", tz=dateutil.tz.tzlocal()), + Timestamp("2011-02-01", tz=dateutil.tz.tzlocal()), ] y = [ - pd.Timestamp("2012-01-01", tz=dateutil.tz.tzlocal()), - pd.Timestamp("2012-02-01", tz=dateutil.tz.tzlocal()), + Timestamp("2012-01-01", tz=dateutil.tz.tzlocal()), + Timestamp("2012-02-01", tz=dateutil.tz.tzlocal()), ] result = concat([Series(x), Series(y)], ignore_index=True) @@ -359,8 +359,8 @@ def test_concat_tz_series_tzlocal(self): def test_concat_tz_series_with_datetimelike(self): # see gh-12620: tz and timedelta x = [ - pd.Timestamp("2011-01-01", tz="US/Eastern"), - pd.Timestamp("2011-02-01", tz="US/Eastern"), + Timestamp("2011-01-01", tz="US/Eastern"), + Timestamp("2011-02-01", tz="US/Eastern"), ] y = [pd.Timedelta("1 day"), pd.Timedelta("2 day")] result = concat([Series(x), Series(y)], ignore_index=True) @@ -374,8 +374,8 @@ def test_concat_tz_series_with_datetimelike(self): def test_concat_tz_frame(self): df2 = DataFrame( dict( - A=pd.Timestamp("20130102", tz="US/Eastern"), - B=pd.Timestamp("20130603", tz="CET"), + A=Timestamp("20130102", tz="US/Eastern"), + B=Timestamp("20130603", tz="CET"), ), index=range(5), ) @@ -501,7 +501,7 @@ def test_concat_period_other_series(self): # non-period x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) - y = Series(pd.DatetimeIndex(["2015-11-01", "2015-12-01"])) + y = Series(DatetimeIndex(["2015-11-01", "2015-12-01"])) expected = Series([x[0], x[1], y[0], y[1]], dtype="object") result = concat([x, y], ignore_index=True) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/reshape/concat/test_index.py b/pandas/tests/reshape/concat/test_index.py index e283212b4e60c..3fc886893b55a 100644 --- a/pandas/tests/reshape/concat/test_index.py +++ b/pandas/tests/reshape/concat/test_index.py @@ -204,11 +204,11 @@ def test_concat_multiindex_with_keys(self): def test_concat_multiindex_with_none_in_index_names(self): # GH 15787 - index = pd.MultiIndex.from_product([[1], range(5)], names=["level1", None]) + index = MultiIndex.from_product([[1], range(5)], names=["level1", None]) df = DataFrame({"col": range(5)}, index=index, dtype=np.int32) result = concat([df, df], keys=[1, 2], names=["level2"]) - index = pd.MultiIndex.from_product( + index = MultiIndex.from_product( [[1, 2], [1], range(5)], names=["level2", "level1", None] ) expected = DataFrame({"col": list(range(5)) * 2}, index=index, dtype=np.int32) @@ -219,7 +219,7 @@ def test_concat_multiindex_with_none_in_index_names(self): level1 = [1] * 7 no_name = list(range(5)) + list(range(2)) tuples = list(zip(level2, level1, no_name)) - index = pd.MultiIndex.from_tuples(tuples, names=["level2", "level1", None]) + index = MultiIndex.from_tuples(tuples, names=["level2", "level1", None]) expected = DataFrame({"col": no_name}, index=index, dtype=np.int32) tm.assert_frame_equal(result, expected) @@ -242,14 +242,14 @@ def test_concat_multiindex_dfs_with_deepcopy(self): # GH 9967 from copy import deepcopy - example_multiindex1 = pd.MultiIndex.from_product([["a"], ["b"]]) + example_multiindex1 = MultiIndex.from_product([["a"], ["b"]]) example_dataframe1 = DataFrame([0], index=example_multiindex1) - example_multiindex2 = pd.MultiIndex.from_product([["a"], ["c"]]) + example_multiindex2 = MultiIndex.from_product([["a"], ["c"]]) example_dataframe2 = DataFrame([1], index=example_multiindex2) example_dict = {"s1": example_dataframe1, "s2": example_dataframe2} - expected_index = pd.MultiIndex( + expected_index = MultiIndex( levels=[["s1", "s2"], ["a"], ["b", "c"]], codes=[[0, 1], [0, 0], [0, 1]], names=["testname", None, None], diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index 5968fd1834f8c..7db92eb55fa0b 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -792,14 +792,14 @@ def test_join_inner_multiindex_deterministic_order(): # GH: 36910 left = DataFrame( data={"e": 5}, - index=pd.MultiIndex.from_tuples([(1, 2, 4)], names=("a", "b", "d")), + index=MultiIndex.from_tuples([(1, 2, 4)], names=("a", "b", "d")), ) right = DataFrame( - data={"f": 6}, index=pd.MultiIndex.from_tuples([(2, 3)], names=("b", "c")) + data={"f": 6}, index=MultiIndex.from_tuples([(2, 3)], names=("b", "c")) ) result = left.join(right, how="inner") expected = DataFrame( {"e": [5], "f": [6]}, - index=pd.MultiIndex.from_tuples([(2, 1, 4, 3)], names=("b", "a", "d", "c")), + index=MultiIndex.from_tuples([(2, 1, 4, 3)], names=("b", "a", "d", "c")), ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index c4c9b0e516192..bb2860b88b288 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -1334,15 +1334,15 @@ def test_merge_take_missing_values_from_index_of_other_dtype(self): left = DataFrame( { "a": [1, 2, 3], - "key": pd.Categorical(["a", "a", "b"], categories=list("abc")), + "key": Categorical(["a", "a", "b"], categories=list("abc")), } ) - right = DataFrame({"b": [1, 2, 3]}, index=pd.CategoricalIndex(["a", "b", "c"])) + right = DataFrame({"b": [1, 2, 3]}, index=CategoricalIndex(["a", "b", "c"])) result = left.merge(right, left_on="key", right_index=True, how="right") expected = DataFrame( { "a": [1, 2, 3, None], - "key": pd.Categorical(["a", "a", "b", "c"]), + "key": Categorical(["a", "a", "b", "c"]), "b": [1, 1, 2, 3], }, index=[0, 1, 2, np.nan], @@ -1687,7 +1687,7 @@ def tests_merge_categorical_unordered_equal(self): result = pd.merge(df1, df2, on=["Foo"]) expected = DataFrame( { - "Foo": pd.Categorical(["A", "B", "C"]), + "Foo": Categorical(["A", "B", "C"]), "Left": ["A0", "B0", "C0"], "Right": ["A1", "B1", "C1"], } diff --git a/pandas/tests/reshape/merge/test_multi.py b/pandas/tests/reshape/merge/test_multi.py index 65673bdde4257..b1922241c7843 100644 --- a/pandas/tests/reshape/merge/test_multi.py +++ b/pandas/tests/reshape/merge/test_multi.py @@ -196,7 +196,7 @@ def test_merge_multiple_cols_with_mixed_cols_index(self): # GH29522 s = pd.Series( range(6), - pd.MultiIndex.from_product([["A", "B"], [1, 2, 3]], names=["lev1", "lev2"]), + MultiIndex.from_product([["A", "B"], [1, 2, 3]], names=["lev1", "lev2"]), name="Amount", ) df = DataFrame({"lev1": list("AAABBB"), "lev2": [1, 2, 3, 1, 2, 3], "col": 0}) @@ -794,7 +794,7 @@ def test_merge_datetime_index(self, box): tm.assert_frame_equal(result, expected) def test_single_common_level(self): - index_left = pd.MultiIndex.from_tuples( + index_left = MultiIndex.from_tuples( [("K0", "X0"), ("K0", "X1"), ("K1", "X2")], names=["key", "X"] ) @@ -802,7 +802,7 @@ def test_single_common_level(self): {"A": ["A0", "A1", "A2"], "B": ["B0", "B1", "B2"]}, index=index_left ) - index_right = pd.MultiIndex.from_tuples( + index_right = MultiIndex.from_tuples( [("K0", "Y0"), ("K1", "Y1"), ("K2", "Y2"), ("K2", "Y3")], names=["key", "Y"] ) @@ -822,8 +822,8 @@ def test_join_multi_wrong_order(self): # GH 25760 # GH 28956 - midx1 = pd.MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"]) - midx3 = pd.MultiIndex.from_tuples([(4, 1), (3, 2), (3, 1)], names=["b", "a"]) + midx1 = MultiIndex.from_product([[1, 2], [3, 4]], names=["a", "b"]) + midx3 = MultiIndex.from_tuples([(4, 1), (3, 2), (3, 1)], names=["b", "a"]) left = DataFrame(index=midx1, data={"x": [10, 20, 30, 40]}) right = DataFrame(index=midx3, data={"y": ["foo", "bar", "fing"]}) diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py index 99beff39e8e09..1f39302845ae9 100644 --- a/pandas/tests/reshape/test_melt.py +++ b/pandas/tests/reshape/test_melt.py @@ -1049,7 +1049,7 @@ def test_col_substring_of_stubname(self): "PA1": {0: 0.77, 1: 0.64, 2: 0.52, 3: 0.98, 4: 0.67}, "PA3": {0: 0.34, 1: 0.70, 2: 0.52, 3: 0.98, 4: 0.67}, } - wide_df = pd.DataFrame.from_dict(wide_data) + wide_df = DataFrame.from_dict(wide_data) expected = pd.wide_to_long( wide_df, stubnames=["PA"], i=["node_id", "A"], j="time" ) diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 642e6a691463e..adab64577ee7a 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -197,7 +197,7 @@ def test_pivot_table_categorical(self): df = DataFrame({"A": cat1, "B": cat2, "values": [1, 2, 3, 4]}) result = pd.pivot_table(df, values="values", index=["A", "B"], dropna=True) - exp_index = pd.MultiIndex.from_arrays([cat1, cat2], names=["A", "B"]) + exp_index = MultiIndex.from_arrays([cat1, cat2], names=["A", "B"]) expected = DataFrame({"values": [1, 2, 3, 4]}, index=exp_index) tm.assert_frame_equal(result, expected) @@ -233,7 +233,7 @@ def test_pivot_with_non_observable_dropna(self, dropna): # gh-21133 df = DataFrame( { - "A": pd.Categorical( + "A": Categorical( [np.nan, "low", "high", "low", "high"], categories=["low", "high"], ordered=True, @@ -246,7 +246,7 @@ def test_pivot_with_non_observable_dropna(self, dropna): expected = DataFrame( {"B": [2, 3]}, index=Index( - pd.Categorical.from_codes( + Categorical.from_codes( [0, 1], categories=["low", "high"], ordered=True ), name="A", @@ -258,7 +258,7 @@ def test_pivot_with_non_observable_dropna(self, dropna): # gh-21378 df = DataFrame( { - "A": pd.Categorical( + "A": Categorical( ["left", "low", "high", "low", "high"], categories=["low", "high", "left"], ordered=True, @@ -271,7 +271,7 @@ def test_pivot_with_non_observable_dropna(self, dropna): expected = DataFrame( {"B": [2, 3, 0]}, index=Index( - pd.Categorical.from_codes( + Categorical.from_codes( [0, 1, 2], categories=["low", "high", "left"], ordered=True ), name="A", @@ -294,7 +294,7 @@ def test_pivot_with_interval_index_margins(self): { "A": np.arange(4, 0, -1, dtype=np.intp), "B": ["a", "b", "a", "b"], - "C": pd.Categorical(ordered_cat, ordered=True).sort_values( + "C": Categorical(ordered_cat, ordered=True).sort_values( ascending=False ), } @@ -400,7 +400,7 @@ def test_pivot_no_values(self): df = DataFrame({"A": [1, 2, 3, 4, 5]}, index=idx) res = df.pivot_table(index=df.index.month, columns=df.index.day) - exp_columns = pd.MultiIndex.from_tuples([("A", 1), ("A", 2)]) + exp_columns = MultiIndex.from_tuples([("A", 1), ("A", 2)]) exp = DataFrame([[2.5, 4.0], [2.0, np.nan]], index=[1, 2], columns=exp_columns) tm.assert_frame_equal(res, exp) @@ -414,7 +414,7 @@ def test_pivot_no_values(self): res = df.pivot_table( index=df.index.month, columns=pd.Grouper(key="dt", freq="M") ) - exp_columns = pd.MultiIndex.from_tuples([("A", pd.Timestamp("2011-01-31"))]) + exp_columns = MultiIndex.from_tuples([("A", pd.Timestamp("2011-01-31"))]) exp_columns.names = [None, "dt"] exp = DataFrame([3.25, 2.0], index=[1, 2], columns=exp_columns) tm.assert_frame_equal(res, exp) @@ -544,7 +544,7 @@ def test_pivot_with_tz(self, method): exp_col2 = pd.DatetimeIndex( ["2014/01/01 09:00", "2014/01/02 09:00"] * 2, name="dt2", tz="Asia/Tokyo" ) - exp_col = pd.MultiIndex.from_arrays([exp_col1, exp_col2]) + exp_col = MultiIndex.from_arrays([exp_col1, exp_col2]) expected = DataFrame( [[0, 2, 0, 2], [1, 3, 1, 3]], index=pd.DatetimeIndex( @@ -653,7 +653,7 @@ def test_pivot_periods(self, method): exp_col1 = Index(["data1", "data1", "data2", "data2"]) exp_col2 = pd.PeriodIndex(["2013-01", "2013-02"] * 2, name="p2", freq="M") - exp_col = pd.MultiIndex.from_arrays([exp_col1, exp_col2]) + exp_col = MultiIndex.from_arrays([exp_col1, exp_col2]) expected = DataFrame( [[0, 2, 0, 2], [1, 3, 1, 3]], index=pd.PeriodIndex(["2013-01-01", "2013-01-02"], name="p1", freq="D"), @@ -1705,7 +1705,7 @@ def test_pivot_table_margins_name_with_aggfunc_list(self): ("max", "cost", "T"), ("max", "cost", margins_name), ] - cols = pd.MultiIndex.from_tuples(tups, names=[None, None, "day"]) + cols = MultiIndex.from_tuples(tups, names=[None, None, "day"]) expected = DataFrame(table.values, index=ix, columns=cols) tm.assert_frame_equal(table, expected) @@ -1762,8 +1762,8 @@ def test_pivot_with_categorical(self, observed, ordered): col = [np.nan, "A", "B", np.nan, "A"] df = DataFrame( { - "In": pd.Categorical(idx, categories=["low", "high"], ordered=ordered), - "Col": pd.Categorical(col, categories=["A", "B"], ordered=ordered), + "In": Categorical(idx, categories=["low", "high"], ordered=ordered), + "Col": Categorical(col, categories=["A", "B"], ordered=ordered), "Val": range(1, 6), } ) @@ -1776,9 +1776,7 @@ def test_pivot_with_categorical(self, observed, ordered): expected = DataFrame(data=[[2.0, np.nan], [np.nan, 3.0]], columns=expected_cols) expected.index = Index( - pd.Categorical( - ["low", "high"], categories=["low", "high"], ordered=ordered - ), + Categorical(["low", "high"], categories=["low", "high"], ordered=ordered), name="In", ) @@ -2013,7 +2011,7 @@ def ret_none(x): ) data = [[3, 1, np.nan, np.nan, 1, 1], [13, 6, np.nan, np.nan, 1, 1]] - col = pd.MultiIndex.from_product( + col = MultiIndex.from_product( [["ret_sum", "ret_none", "ret_one"], ["apple", "peach"]], names=[None, "fruit"], ) @@ -2143,7 +2141,7 @@ def test_pivot_index_none(self): # omit values result = frame.pivot(columns="columns") - expected.columns = pd.MultiIndex.from_tuples( + expected.columns = MultiIndex.from_tuples( [("values", "One"), ("values", "Two")], names=[None, "columns"] ) expected.index.name = "index" diff --git a/pandas/tests/reshape/test_union_categoricals.py b/pandas/tests/reshape/test_union_categoricals.py index f6a4f8c0cf601..b44f4844b8e2d 100644 --- a/pandas/tests/reshape/test_union_categoricals.py +++ b/pandas/tests/reshape/test_union_categoricals.py @@ -72,13 +72,13 @@ def test_union_categorical(self): def test_union_categoricals_nan(self): # GH 13759 res = union_categoricals( - [pd.Categorical([1, 2, np.nan]), pd.Categorical([3, 2, np.nan])] + [Categorical([1, 2, np.nan]), Categorical([3, 2, np.nan])] ) exp = Categorical([1, 2, np.nan, 3, 2, np.nan]) tm.assert_categorical_equal(res, exp) res = union_categoricals( - [pd.Categorical(["A", "B"]), pd.Categorical(["B", "B", np.nan])] + [Categorical(["A", "B"]), Categorical(["B", "B", np.nan])] ) exp = Categorical(["A", "B", "B", "B", np.nan]) tm.assert_categorical_equal(res, exp) @@ -86,7 +86,7 @@ def test_union_categoricals_nan(self): val1 = [pd.Timestamp("2011-01-01"), pd.Timestamp("2011-03-01"), pd.NaT] val2 = [pd.NaT, pd.Timestamp("2011-01-01"), pd.Timestamp("2011-02-01")] - res = union_categoricals([pd.Categorical(val1), pd.Categorical(val2)]) + res = union_categoricals([Categorical(val1), Categorical(val2)]) exp = Categorical( val1 + val2, categories=[ @@ -100,22 +100,22 @@ def test_union_categoricals_nan(self): # all NaN res = union_categoricals( [ - pd.Categorical(np.array([np.nan, np.nan], dtype=object)), - pd.Categorical(["X"]), + Categorical(np.array([np.nan, np.nan], dtype=object)), + Categorical(["X"]), ] ) exp = Categorical([np.nan, np.nan, "X"]) tm.assert_categorical_equal(res, exp) res = union_categoricals( - [pd.Categorical([np.nan, np.nan]), pd.Categorical([np.nan, np.nan])] + [Categorical([np.nan, np.nan]), Categorical([np.nan, np.nan])] ) exp = Categorical([np.nan, np.nan, np.nan, np.nan]) tm.assert_categorical_equal(res, exp) def test_union_categoricals_empty(self): # GH 13759 - res = union_categoricals([pd.Categorical([]), pd.Categorical([])]) + res = union_categoricals([Categorical([]), Categorical([])]) exp = Categorical([]) tm.assert_categorical_equal(res, exp) diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index 5006e16b6a7e0..f150e5e5b18b2 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -655,7 +655,7 @@ def test_to_timestamp_business_end(self): per = pd.Period("1990-01-05", "B") # Friday result = per.to_timestamp("B", how="E") - expected = pd.Timestamp("1990-01-06") - pd.Timedelta(nanoseconds=1) + expected = Timestamp("1990-01-06") - Timedelta(nanoseconds=1) assert result == expected @pytest.mark.parametrize( @@ -866,7 +866,7 @@ def test_end_time_business_friday(self): per = Period("1990-01-05", "B") result = per.end_time - expected = pd.Timestamp("1990-01-06") - pd.Timedelta(nanoseconds=1) + expected = Timestamp("1990-01-06") - Timedelta(nanoseconds=1) assert result == expected def test_anchor_week_end_time(self): diff --git a/pandas/tests/scalar/timedelta/test_arithmetic.py b/pandas/tests/scalar/timedelta/test_arithmetic.py index d4d7e4b85268f..8ec8f1e0457fb 100644 --- a/pandas/tests/scalar/timedelta/test_arithmetic.py +++ b/pandas/tests/scalar/timedelta/test_arithmetic.py @@ -927,7 +927,7 @@ def test_compare_timedelta_ndarray(self): def test_compare_td64_ndarray(self): # GG#33441 arr = np.arange(5).astype("timedelta64[ns]") - td = pd.Timedelta(arr[1]) + td = Timedelta(arr[1]) expected = np.array([False, True, False, False, False], dtype=bool) diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py index 6aee8b3ab34fa..c25b8936c1b29 100644 --- a/pandas/tests/series/indexing/test_datetime.py +++ b/pandas/tests/series/indexing/test_datetime.py @@ -264,8 +264,8 @@ def test_getitem_setitem_datetimeindex(): # see GH#18376, GH#18162 ts[(ts.index >= lb) & (ts.index <= rb)] - lb = pd.Timestamp(datetime(1990, 1, 1, 4)).tz_localize(rng.tzinfo) - rb = pd.Timestamp(datetime(1990, 1, 1, 7)).tz_localize(rng.tzinfo) + lb = Timestamp(datetime(1990, 1, 1, 4)).tz_localize(rng.tzinfo) + rb = Timestamp(datetime(1990, 1, 1, 7)).tz_localize(rng.tzinfo) result = ts[(ts.index >= lb) & (ts.index <= rb)] expected = ts[4:8] tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index 214694443ba2a..88087110fc221 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -133,10 +133,10 @@ def test_getitem_fancy(string_series, object_series): def test_type_promotion(): # GH12599 s = Series(dtype=object) - s["a"] = pd.Timestamp("2016-01-01") + s["a"] = Timestamp("2016-01-01") s["b"] = 3.0 s["c"] = "foo" - expected = Series([pd.Timestamp("2016-01-01"), 3.0, "foo"], index=["a", "b", "c"]) + expected = Series([Timestamp("2016-01-01"), 3.0, "foo"], index=["a", "b", "c"]) tm.assert_series_equal(s, expected) @@ -181,13 +181,13 @@ def test_series_box_timestamp(): rng = pd.date_range("20090415", "20090519", freq="B") ser = Series(rng) - assert isinstance(ser[5], pd.Timestamp) + assert isinstance(ser[5], Timestamp) rng = pd.date_range("20090415", "20090519", freq="B") ser = Series(rng, index=rng) - assert isinstance(ser[5], pd.Timestamp) + assert isinstance(ser[5], Timestamp) - assert isinstance(ser.iat[5], pd.Timestamp) + assert isinstance(ser.iat[5], Timestamp) def test_series_box_timedelta(): @@ -354,27 +354,27 @@ def test_setitem_with_tz(tz): # scalar s = orig.copy() - s[1] = pd.Timestamp("2011-01-01", tz=tz) + s[1] = Timestamp("2011-01-01", tz=tz) exp = Series( [ - pd.Timestamp("2016-01-01 00:00", tz=tz), - pd.Timestamp("2011-01-01 00:00", tz=tz), - pd.Timestamp("2016-01-01 02:00", tz=tz), + Timestamp("2016-01-01 00:00", tz=tz), + Timestamp("2011-01-01 00:00", tz=tz), + Timestamp("2016-01-01 02:00", tz=tz), ] ) tm.assert_series_equal(s, exp) s = orig.copy() - s.loc[1] = pd.Timestamp("2011-01-01", tz=tz) + s.loc[1] = Timestamp("2011-01-01", tz=tz) tm.assert_series_equal(s, exp) s = orig.copy() - s.iloc[1] = pd.Timestamp("2011-01-01", tz=tz) + s.iloc[1] = Timestamp("2011-01-01", tz=tz) tm.assert_series_equal(s, exp) # vector vals = Series( - [pd.Timestamp("2011-01-01", tz=tz), pd.Timestamp("2012-01-01", tz=tz)], + [Timestamp("2011-01-01", tz=tz), Timestamp("2012-01-01", tz=tz)], index=[1, 2], ) assert vals.dtype == f"datetime64[ns, {tz}]" @@ -382,9 +382,9 @@ def test_setitem_with_tz(tz): s[[1, 2]] = vals exp = Series( [ - pd.Timestamp("2016-01-01 00:00", tz=tz), - pd.Timestamp("2011-01-01 00:00", tz=tz), - pd.Timestamp("2012-01-01 00:00", tz=tz), + Timestamp("2016-01-01 00:00", tz=tz), + Timestamp("2011-01-01 00:00", tz=tz), + Timestamp("2012-01-01 00:00", tz=tz), ] ) tm.assert_series_equal(s, exp) @@ -406,27 +406,27 @@ def test_setitem_with_tz_dst(): # scalar s = orig.copy() - s[1] = pd.Timestamp("2011-01-01", tz=tz) + s[1] = Timestamp("2011-01-01", tz=tz) exp = Series( [ - pd.Timestamp("2016-11-06 00:00-04:00", tz=tz), - pd.Timestamp("2011-01-01 00:00-05:00", tz=tz), - pd.Timestamp("2016-11-06 01:00-05:00", tz=tz), + Timestamp("2016-11-06 00:00-04:00", tz=tz), + Timestamp("2011-01-01 00:00-05:00", tz=tz), + Timestamp("2016-11-06 01:00-05:00", tz=tz), ] ) tm.assert_series_equal(s, exp) s = orig.copy() - s.loc[1] = pd.Timestamp("2011-01-01", tz=tz) + s.loc[1] = Timestamp("2011-01-01", tz=tz) tm.assert_series_equal(s, exp) s = orig.copy() - s.iloc[1] = pd.Timestamp("2011-01-01", tz=tz) + s.iloc[1] = Timestamp("2011-01-01", tz=tz) tm.assert_series_equal(s, exp) # vector vals = Series( - [pd.Timestamp("2011-01-01", tz=tz), pd.Timestamp("2012-01-01", tz=tz)], + [Timestamp("2011-01-01", tz=tz), Timestamp("2012-01-01", tz=tz)], index=[1, 2], ) assert vals.dtype == f"datetime64[ns, {tz}]" @@ -434,9 +434,9 @@ def test_setitem_with_tz_dst(): s[[1, 2]] = vals exp = Series( [ - pd.Timestamp("2016-11-06 00:00", tz=tz), - pd.Timestamp("2011-01-01 00:00", tz=tz), - pd.Timestamp("2012-01-01 00:00", tz=tz), + Timestamp("2016-11-06 00:00", tz=tz), + Timestamp("2011-01-01 00:00", tz=tz), + Timestamp("2012-01-01 00:00", tz=tz), ] ) tm.assert_series_equal(s, exp) @@ -568,7 +568,7 @@ def test_timedelta_assignment(): s = Series(10 * [np.timedelta64(10, "m")]) s.loc[[1, 2, 3]] = np.timedelta64(20, "m") expected = Series(10 * [np.timedelta64(10, "m")]) - expected.loc[[1, 2, 3]] = pd.Timedelta(np.timedelta64(20, "m")) + expected.loc[[1, 2, 3]] = Timedelta(np.timedelta64(20, "m")) tm.assert_series_equal(s, expected) @@ -637,9 +637,9 @@ def test_td64_series_assign_nat(nat_val, should_cast): @pytest.mark.parametrize( "td", [ - pd.Timedelta("9 days"), - pd.Timedelta("9 days").to_timedelta64(), - pd.Timedelta("9 days").to_pytimedelta(), + Timedelta("9 days"), + Timedelta("9 days").to_timedelta64(), + Timedelta("9 days").to_pytimedelta(), ], ) def test_append_timedelta_does_not_cast(td): @@ -649,12 +649,12 @@ def test_append_timedelta_does_not_cast(td): ser = Series(["x"]) ser["td"] = td tm.assert_series_equal(ser, expected) - assert isinstance(ser["td"], pd.Timedelta) + assert isinstance(ser["td"], Timedelta) ser = Series(["x"]) - ser.loc["td"] = pd.Timedelta("9 days") + ser.loc["td"] = Timedelta("9 days") tm.assert_series_equal(ser, expected) - assert isinstance(ser["td"], pd.Timedelta) + assert isinstance(ser["td"], Timedelta) def test_underlying_data_conversion(): diff --git a/pandas/tests/series/indexing/test_where.py b/pandas/tests/series/indexing/test_where.py index 404136bdfa2db..27bbb47e1d0d1 100644 --- a/pandas/tests/series/indexing/test_where.py +++ b/pandas/tests/series/indexing/test_where.py @@ -418,7 +418,7 @@ def test_where_datetime_conversion(): # GH 15701 timestamps = ["2016-12-31 12:00:04+00:00", "2016-12-31 12:00:04.010000+00:00"] - s = Series([pd.Timestamp(t) for t in timestamps]) + s = Series([Timestamp(t) for t in timestamps]) rs = s.where(Series([False, True])) expected = Series([pd.NaT, s[1]]) tm.assert_series_equal(rs, expected) diff --git a/pandas/tests/series/methods/test_quantile.py b/pandas/tests/series/methods/test_quantile.py index 964d62602edaa..1d3e91d07afe3 100644 --- a/pandas/tests/series/methods/test_quantile.py +++ b/pandas/tests/series/methods/test_quantile.py @@ -121,27 +121,27 @@ def test_quantile_nan(self): "case", [ [ - pd.Timestamp("2011-01-01"), - pd.Timestamp("2011-01-02"), - pd.Timestamp("2011-01-03"), + Timestamp("2011-01-01"), + Timestamp("2011-01-02"), + Timestamp("2011-01-03"), ], [ - pd.Timestamp("2011-01-01", tz="US/Eastern"), - pd.Timestamp("2011-01-02", tz="US/Eastern"), - pd.Timestamp("2011-01-03", tz="US/Eastern"), + Timestamp("2011-01-01", tz="US/Eastern"), + Timestamp("2011-01-02", tz="US/Eastern"), + Timestamp("2011-01-03", tz="US/Eastern"), ], [pd.Timedelta("1 days"), pd.Timedelta("2 days"), pd.Timedelta("3 days")], # NaT [ - pd.Timestamp("2011-01-01"), - pd.Timestamp("2011-01-02"), - pd.Timestamp("2011-01-03"), + Timestamp("2011-01-01"), + Timestamp("2011-01-02"), + Timestamp("2011-01-03"), pd.NaT, ], [ - pd.Timestamp("2011-01-01", tz="US/Eastern"), - pd.Timestamp("2011-01-02", tz="US/Eastern"), - pd.Timestamp("2011-01-03", tz="US/Eastern"), + Timestamp("2011-01-01", tz="US/Eastern"), + Timestamp("2011-01-02", tz="US/Eastern"), + Timestamp("2011-01-03", tz="US/Eastern"), pd.NaT, ], [ diff --git a/pandas/tests/series/methods/test_unstack.py b/pandas/tests/series/methods/test_unstack.py index 38955ea7f06c4..ded4500ba478a 100644 --- a/pandas/tests/series/methods/test_unstack.py +++ b/pandas/tests/series/methods/test_unstack.py @@ -40,7 +40,7 @@ def test_unstack(): tm.assert_frame_equal(unstacked, expected) # GH5873 - idx = pd.MultiIndex.from_arrays([[101, 102], [3.5, np.nan]]) + idx = MultiIndex.from_arrays([[101, 102], [3.5, np.nan]]) ts = Series([1, 2], index=idx) left = ts.unstack() right = DataFrame( @@ -48,7 +48,7 @@ def test_unstack(): ) tm.assert_frame_equal(left, right) - idx = pd.MultiIndex.from_arrays( + idx = MultiIndex.from_arrays( [ ["cat", "cat", "cat", "dog", "dog"], ["a", "a", "b", "a", "b"], @@ -61,13 +61,13 @@ def test_unstack(): columns=["cat", "dog"], ) tpls = [("a", 1), ("a", 2), ("b", np.nan), ("b", 1)] - right.index = pd.MultiIndex.from_tuples(tpls) + right.index = MultiIndex.from_tuples(tpls) tm.assert_frame_equal(ts.unstack(level=0), right) def test_unstack_tuplename_in_multiindex(): # GH 19966 - idx = pd.MultiIndex.from_product( + idx = MultiIndex.from_product( [["a", "b", "c"], [1, 2, 3]], names=[("A", "a"), ("B", "b")] ) ser = Series(1, index=idx) @@ -75,7 +75,7 @@ def test_unstack_tuplename_in_multiindex(): expected = DataFrame( [[1, 1, 1], [1, 1, 1], [1, 1, 1]], - columns=pd.MultiIndex.from_tuples([("a",), ("b",), ("c",)], names=[("A", "a")]), + columns=MultiIndex.from_tuples([("a",), ("b",), ("c",)], names=[("A", "a")]), index=pd.Index([1, 2, 3], name=("B", "b")), ) tm.assert_frame_equal(result, expected) @@ -87,16 +87,14 @@ def test_unstack_tuplename_in_multiindex(): ( ("A", "a"), [[1, 1], [1, 1], [1, 1], [1, 1]], - pd.MultiIndex.from_tuples( - [(1, 3), (1, 4), (2, 3), (2, 4)], names=["B", "C"] - ), - pd.MultiIndex.from_tuples([("a",), ("b",)], names=[("A", "a")]), + MultiIndex.from_tuples([(1, 3), (1, 4), (2, 3), (2, 4)], names=["B", "C"]), + MultiIndex.from_tuples([("a",), ("b",)], names=[("A", "a")]), ), ( (("A", "a"), "B"), [[1, 1, 1, 1], [1, 1, 1, 1]], pd.Index([3, 4], name="C"), - pd.MultiIndex.from_tuples( + MultiIndex.from_tuples( [("a", 1), ("a", 2), ("b", 1), ("b", 2)], names=[("A", "a"), "B"] ), ), @@ -106,7 +104,7 @@ def test_unstack_mixed_type_name_in_multiindex( unstack_idx, expected_values, expected_index, expected_columns ): # GH 19966 - idx = pd.MultiIndex.from_product( + idx = MultiIndex.from_product( [["a", "b"], [1, 2], [3, 4]], names=[("A", "a"), "B", "C"] ) ser = Series(1, index=idx) diff --git a/pandas/tests/series/methods/test_value_counts.py b/pandas/tests/series/methods/test_value_counts.py index 37da31fb2329a..e4fdfb2838b70 100644 --- a/pandas/tests/series/methods/test_value_counts.py +++ b/pandas/tests/series/methods/test_value_counts.py @@ -85,15 +85,15 @@ def test_value_counts_period(self): def test_value_counts_categorical_ordered(self): # most dtypes are tested in tests/base - values = pd.Categorical([1, 2, 3, 1, 1, 3], ordered=True) + values = Categorical([1, 2, 3, 1, 1, 3], ordered=True) - exp_idx = pd.CategoricalIndex([1, 3, 2], categories=[1, 2, 3], ordered=True) + exp_idx = CategoricalIndex([1, 3, 2], categories=[1, 2, 3], ordered=True) exp = Series([3, 2, 1], index=exp_idx, name="xxx") ser = Series(values, name="xxx") tm.assert_series_equal(ser.value_counts(), exp) # check CategoricalIndex outputs the same result - idx = pd.CategoricalIndex(values, name="xxx") + idx = CategoricalIndex(values, name="xxx") tm.assert_series_equal(idx.value_counts(), exp) # normalize @@ -102,15 +102,15 @@ def test_value_counts_categorical_ordered(self): tm.assert_series_equal(idx.value_counts(normalize=True), exp) def test_value_counts_categorical_not_ordered(self): - values = pd.Categorical([1, 2, 3, 1, 1, 3], ordered=False) + values = Categorical([1, 2, 3, 1, 1, 3], ordered=False) - exp_idx = pd.CategoricalIndex([1, 3, 2], categories=[1, 2, 3], ordered=False) + exp_idx = CategoricalIndex([1, 3, 2], categories=[1, 2, 3], ordered=False) exp = Series([3, 2, 1], index=exp_idx, name="xxx") ser = Series(values, name="xxx") tm.assert_series_equal(ser.value_counts(), exp) # check CategoricalIndex outputs the same result - idx = pd.CategoricalIndex(values, name="xxx") + idx = CategoricalIndex(values, name="xxx") tm.assert_series_equal(idx.value_counts(), exp) # normalize diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index bb091ba1beb2d..5c4118bc40f4d 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -71,7 +71,7 @@ def test_empty_constructor(self, constructor, check_index_type): def test_invalid_dtype(self): # GH15520 msg = "not understood" - invalid_list = [pd.Timestamp, "pd.Timestamp", list] + invalid_list = [Timestamp, "Timestamp", list] for dtype in invalid_list: with pytest.raises(TypeError, match=msg): Series([], name="time", dtype=dtype) @@ -310,17 +310,17 @@ def test_constructor_map(self): tm.assert_series_equal(result, exp) def test_constructor_categorical(self): - cat = pd.Categorical([0, 1, 2, 0, 1, 2], ["a", "b", "c"], fastpath=True) + cat = Categorical([0, 1, 2, 0, 1, 2], ["a", "b", "c"], fastpath=True) res = Series(cat) tm.assert_categorical_equal(res.values, cat) # can cast to a new dtype - result = Series(pd.Categorical([1, 2, 3]), dtype="int64") + result = Series(Categorical([1, 2, 3]), dtype="int64") expected = Series([1, 2, 3], dtype="int64") tm.assert_series_equal(result, expected) # GH12574 - cat = Series(pd.Categorical([1, 2, 3]), dtype="category") + cat = Series(Categorical([1, 2, 3]), dtype="category") assert is_categorical_dtype(cat) assert is_categorical_dtype(cat.dtype) s = Series([1, 2, 3], dtype="category") @@ -453,7 +453,7 @@ def test_categorical_sideeffects_free(self): def test_unordered_compare_equal(self): left = Series(["a", "b", "c"], dtype=CategoricalDtype(["a", "b"])) - right = Series(pd.Categorical(["a", "b", np.nan], categories=["a", "b"])) + right = Series(Categorical(["a", "b", np.nan], categories=["a", "b"])) tm.assert_series_equal(left, right) def test_constructor_maskedarray(self): @@ -557,7 +557,7 @@ def test_constructor_default_index(self): [1, 2, 3], (1, 2, 3), list(range(3)), - pd.Categorical(["a", "b", "a"]), + Categorical(["a", "b", "a"]), (i for i in range(3)), map(lambda x: x, range(3)), ], @@ -940,8 +940,8 @@ def test_constructor_with_datetime_tz(self): # inference s = Series( [ - pd.Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"), - pd.Timestamp("2013-01-02 14:00:00-0800", tz="US/Pacific"), + Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"), + Timestamp("2013-01-02 14:00:00-0800", tz="US/Pacific"), ] ) assert s.dtype == "datetime64[ns, US/Pacific]" @@ -949,8 +949,8 @@ def test_constructor_with_datetime_tz(self): s = Series( [ - pd.Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"), - pd.Timestamp("2013-01-02 14:00:00-0800", tz="US/Eastern"), + Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"), + Timestamp("2013-01-02 14:00:00-0800", tz="US/Eastern"), ] ) assert s.dtype == "object" @@ -979,7 +979,7 @@ def test_construction_to_datetimelike_unit(self, arr_dtype, dtype, unit): def test_constructor_with_naive_string_and_datetimetz_dtype(self, arg): # GH 17415: With naive string result = Series([arg], dtype="datetime64[ns, CET]") - expected = Series(pd.Timestamp(arg)).dt.tz_localize("CET") + expected = Series(Timestamp(arg)).dt.tz_localize("CET") tm.assert_series_equal(result, expected) def test_constructor_datetime64_bigendian(self): diff --git a/pandas/tests/series/test_dt_accessor.py b/pandas/tests/series/test_dt_accessor.py index 2f30c0621cc06..7a84f642aebc2 100644 --- a/pandas/tests/series/test_dt_accessor.py +++ b/pandas/tests/series/test_dt_accessor.py @@ -633,7 +633,7 @@ def test_dt_accessor_updates_on_inplace(self): def test_date_tz(self): # GH11757 - rng = pd.DatetimeIndex( + rng = DatetimeIndex( ["2014-04-04 23:56", "2014-07-18 21:24", "2015-11-22 22:14"], tz="US/Eastern", ) @@ -646,7 +646,7 @@ def test_dt_timetz_accessor(self, tz_naive_fixture): # GH21358 tz = maybe_get_tz(tz_naive_fixture) - dtindex = pd.DatetimeIndex( + dtindex = DatetimeIndex( ["2014-04-04 23:56", "2014-07-18 21:24", "2015-11-22 22:14"], tz=tz ) s = Series(dtindex) diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 6f5345f802a7c..189c792ac228b 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -412,7 +412,7 @@ def test_subsets_multiindex_dtype(self): # GH 20757 data = [["x", 1]] columns = [("a", "b", np.nan), ("a", "c", 0.0)] - df = DataFrame(data, columns=pd.MultiIndex.from_tuples(columns)) + df = DataFrame(data, columns=MultiIndex.from_tuples(columns)) expected = df.dtypes.a.b result = df.a.b.dtypes tm.assert_series_equal(result, expected) diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 13c8987c66977..ebe118252c8cf 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -272,7 +272,7 @@ def test_to_datetime_format_weeks(self, cache): [ "%Y-%m-%d %H:%M:%S %Z", ["2010-01-01 12:00:00 UTC"] * 2, - [pd.Timestamp("2010-01-01 12:00:00", tz="UTC")] * 2, + [Timestamp("2010-01-01 12:00:00", tz="UTC")] * 2, ], [ "%Y-%m-%d %H:%M:%S %Z", @@ -282,37 +282,37 @@ def test_to_datetime_format_weeks(self, cache): "2010-01-01 12:00:00 US/Pacific", ], [ - pd.Timestamp("2010-01-01 12:00:00", tz="UTC"), - pd.Timestamp("2010-01-01 12:00:00", tz="GMT"), - pd.Timestamp("2010-01-01 12:00:00", tz="US/Pacific"), + Timestamp("2010-01-01 12:00:00", tz="UTC"), + Timestamp("2010-01-01 12:00:00", tz="GMT"), + Timestamp("2010-01-01 12:00:00", tz="US/Pacific"), ], ], [ "%Y-%m-%d %H:%M:%S%z", ["2010-01-01 12:00:00+0100"] * 2, - [pd.Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(60))] * 2, + [Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(60))] * 2, ], [ "%Y-%m-%d %H:%M:%S %z", ["2010-01-01 12:00:00 +0100"] * 2, - [pd.Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(60))] * 2, + [Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(60))] * 2, ], [ "%Y-%m-%d %H:%M:%S %z", ["2010-01-01 12:00:00 +0100", "2010-01-01 12:00:00 -0100"], [ - pd.Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(60)), - pd.Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(-60)), + Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(60)), + Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(-60)), ], ], [ "%Y-%m-%d %H:%M:%S %z", ["2010-01-01 12:00:00 Z", "2010-01-01 12:00:00 Z"], [ - pd.Timestamp( + Timestamp( "2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(0) ), # pytz coerces to UTC - pd.Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(0)), + Timestamp("2010-01-01 12:00:00", tzinfo=pytz.FixedOffset(0)), ], ], ], @@ -340,7 +340,7 @@ def test_to_datetime_parse_tzname_or_tzoffset_different_tz_to_utc(self): fmt = "%Y-%m-%d %H:%M:%S %z" result = pd.to_datetime(dates, format=fmt, utc=True) - expected = pd.DatetimeIndex(expected_dates) + expected = DatetimeIndex(expected_dates) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( @@ -359,7 +359,7 @@ def test_to_datetime_parse_timezone_keeps_name(self): fmt = "%Y-%m-%d %H:%M:%S %z" arg = Index(["2010-01-01 12:00:00 Z"], name="foo") result = pd.to_datetime(arg, format=fmt) - expected = pd.DatetimeIndex(["2010-01-01 12:00:00"], tz="UTC", name="foo") + expected = DatetimeIndex(["2010-01-01 12:00:00"], tz="UTC", name="foo") tm.assert_index_equal(result, expected) @@ -528,8 +528,8 @@ def test_to_datetime_today(self): pdtoday = pd.to_datetime("today") pdtoday2 = pd.to_datetime(["today"])[0] - tstoday = pd.Timestamp("today") - tstoday2 = pd.Timestamp.today() + tstoday = Timestamp("today") + tstoday2 = Timestamp.today() # These should all be equal with infinite perf; this gives # a generous margin of 10 seconds @@ -590,7 +590,7 @@ def test_to_datetime_array_of_dt64s(self, cache, unit): # an array that is equal to Timestamp() parsing tm.assert_index_equal( pd.to_datetime(dts, cache=cache), - pd.DatetimeIndex([Timestamp(x).asm8 for x in dts]), + DatetimeIndex([Timestamp(x).asm8 for x in dts]), ) # A list of datetimes where the last one is out of bounds @@ -602,7 +602,7 @@ def test_to_datetime_array_of_dt64s(self, cache, unit): tm.assert_index_equal( pd.to_datetime(dts_with_oob, errors="coerce", cache=cache), - pd.DatetimeIndex( + DatetimeIndex( [Timestamp(dts_with_oob[0]).asm8, Timestamp(dts_with_oob[1]).asm8] * 30 + [pd.NaT], ), @@ -622,8 +622,8 @@ def test_to_datetime_tz(self, cache): # xref 8260 # uniform returns a DatetimeIndex arr = [ - pd.Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"), - pd.Timestamp("2013-01-02 14:00:00-0800", tz="US/Pacific"), + Timestamp("2013-01-01 13:00:00-0800", tz="US/Pacific"), + Timestamp("2013-01-02 14:00:00-0800", tz="US/Pacific"), ] result = pd.to_datetime(arr, cache=cache) expected = DatetimeIndex( @@ -633,8 +633,8 @@ def test_to_datetime_tz(self, cache): # mixed tzs will raise arr = [ - pd.Timestamp("2013-01-01 13:00:00", tz="US/Pacific"), - pd.Timestamp("2013-01-02 14:00:00", tz="US/Eastern"), + Timestamp("2013-01-01 13:00:00", tz="US/Pacific"), + Timestamp("2013-01-02 14:00:00", tz="US/Eastern"), ] msg = ( "Tz-aware datetime.datetime cannot be " @@ -693,8 +693,8 @@ def test_to_datetime_utc_true( # See gh-11934 & gh-6415 data = ["20100102 121314", "20100102 121315"] expected_data = [ - pd.Timestamp("2010-01-02 12:13:14", tz="utc"), - pd.Timestamp("2010-01-02 12:13:15", tz="utc"), + Timestamp("2010-01-02 12:13:14", tz="utc"), + Timestamp("2010-01-02 12:13:15", tz="utc"), ] result = pd.to_datetime( @@ -715,7 +715,7 @@ def test_to_datetime_utc_true_with_series_single_value(self, cache): # GH 15760 UTC=True with Series ts = 1.5e18 result = pd.to_datetime(Series([ts]), utc=True, cache=cache) - expected = Series([pd.Timestamp(ts, tz="utc")]) + expected = Series([Timestamp(ts, tz="utc")]) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) @@ -724,7 +724,7 @@ def test_to_datetime_utc_true_with_series_tzaware_string(self, cache): expected_ts = "2013-01-01 01:00:00" data = Series([ts] * 3) result = pd.to_datetime(data, utc=True, cache=cache) - expected = Series([pd.Timestamp(expected_ts, tz="utc")] * 3) + expected = Series([Timestamp(expected_ts, tz="utc")] * 3) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) @@ -736,7 +736,7 @@ def test_to_datetime_utc_true_with_series_tzaware_string(self, cache): ], ) def test_to_datetime_utc_true_with_series_datetime_ns(self, cache, date, dtype): - expected = Series([pd.Timestamp("2013-01-01 01:00:00", tz="UTC")]) + expected = Series([Timestamp("2013-01-01 01:00:00", tz="UTC")]) result = pd.to_datetime(Series([date], dtype=dtype), utc=True, cache=cache) tm.assert_series_equal(result, expected) @@ -767,7 +767,7 @@ def test_to_datetime_tz_psycopg2(self, cache): tm.assert_index_equal(result, expected) # dtype coercion - i = pd.DatetimeIndex( + i = DatetimeIndex( ["2000-01-01 08:00:00"], tz=psycopg2.tz.FixedOffsetTimezone(offset=-300, name=None), ) @@ -778,9 +778,7 @@ def test_to_datetime_tz_psycopg2(self, cache): tm.assert_index_equal(result, i) result = pd.to_datetime(i, errors="coerce", utc=True, cache=cache) - expected = pd.DatetimeIndex( - ["2000-01-01 13:00:00"], dtype="datetime64[ns, UTC]" - ) + expected = DatetimeIndex(["2000-01-01 13:00:00"], dtype="datetime64[ns, UTC]") tm.assert_index_equal(result, expected) @pytest.mark.parametrize("cache", [True, False]) @@ -881,7 +879,7 @@ def test_datetime_invalid_index(self, values, format, infer): res = pd.to_datetime( values, errors="coerce", format=format, infer_datetime_format=infer ) - tm.assert_index_equal(res, pd.DatetimeIndex([pd.NaT] * len(values))) + tm.assert_index_equal(res, DatetimeIndex([pd.NaT] * len(values))) msg = ( "is a bad directive in format|" @@ -909,9 +907,9 @@ def test_to_datetime_cache(self, utc, format, constructor): @pytest.mark.parametrize( "listlike", [ - (deque([pd.Timestamp("2010-06-02 09:30:00")] * 51)), - ([pd.Timestamp("2010-06-02 09:30:00")] * 51), - (tuple([pd.Timestamp("2010-06-02 09:30:00")] * 51)), + (deque([Timestamp("2010-06-02 09:30:00")] * 51)), + ([Timestamp("2010-06-02 09:30:00")] * 51), + (tuple([Timestamp("2010-06-02 09:30:00")] * 51)), ], ) def test_no_slicing_errors_in_should_cache(self, listlike): @@ -920,8 +918,8 @@ def test_no_slicing_errors_in_should_cache(self, listlike): def test_to_datetime_from_deque(self): # GH 29403 - result = pd.to_datetime(deque([pd.Timestamp("2010-06-02 09:30:00")] * 51)) - expected = pd.to_datetime([pd.Timestamp("2010-06-02 09:30:00")] * 51) + result = pd.to_datetime(deque([Timestamp("2010-06-02 09:30:00")] * 51)) + expected = pd.to_datetime([Timestamp("2010-06-02 09:30:00")] * 51) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("utc", [True, None]) @@ -937,7 +935,7 @@ def test_to_datetime_cache_series(self, utc, format): def test_to_datetime_cache_scalar(self): date = "20130101 00:00:00" result = pd.to_datetime(date, cache=True) - expected = pd.Timestamp("20130101 00:00:00") + expected = Timestamp("20130101 00:00:00") assert result == expected @pytest.mark.parametrize( @@ -1052,7 +1050,7 @@ def test_mixed_offsets_with_native_datetime_raises(self): s = Series( [ "nan", - pd.Timestamp("1990-01-01"), + Timestamp("1990-01-01"), "2015-03-14T16:15:14.123-08:00", "2019-03-04T21:56:32.620-07:00", None, @@ -1219,7 +1217,7 @@ def test_unit_mixed(self, cache): # mixed integers/datetimes expected = DatetimeIndex(["2013-01-01", "NaT", "NaT"]) - arr = [pd.Timestamp("20130101"), 1.434692e18, 1.432766e18] + arr = [Timestamp("20130101"), 1.434692e18, 1.432766e18] result = pd.to_datetime(arr, errors="coerce", cache=cache) tm.assert_index_equal(result, expected) @@ -1228,7 +1226,7 @@ def test_unit_mixed(self, cache): pd.to_datetime(arr, errors="raise", cache=cache) expected = DatetimeIndex(["NaT", "NaT", "2013-01-01"]) - arr = [1.434692e18, 1.432766e18, pd.Timestamp("20130101")] + arr = [1.434692e18, 1.432766e18, Timestamp("20130101")] result = pd.to_datetime(arr, errors="coerce", cache=cache) tm.assert_index_equal(result, expected) @@ -1240,7 +1238,7 @@ def test_unit_rounding(self, cache): # GH 14156 & GH 20445: argument will incur floating point errors # but no premature rounding result = pd.to_datetime(1434743731.8770001, unit="s", cache=cache) - expected = pd.Timestamp("2015-06-19 19:55:31.877000192") + expected = Timestamp("2015-06-19 19:55:31.877000192") assert result == expected @pytest.mark.parametrize("cache", [True, False]) @@ -1899,7 +1897,7 @@ def test_infer_datetime_format_tz_name(self, tz_name, offset): s = Series([f"2019-02-02 08:07:13 {tz_name}"]) result = to_datetime(s, infer_datetime_format=True) expected = Series( - [pd.Timestamp("2019-02-02 08:07:13").tz_localize(pytz.FixedOffset(offset))] + [Timestamp("2019-02-02 08:07:13").tz_localize(pytz.FixedOffset(offset))] ) tm.assert_series_equal(result, expected) @@ -1909,9 +1907,9 @@ def test_to_datetime_iso8601_noleading_0s(self, cache): s = Series(["2014-1-1", "2014-2-2", "2015-3-3"]) expected = Series( [ - pd.Timestamp("2014-01-01"), - pd.Timestamp("2014-02-02"), - pd.Timestamp("2015-03-03"), + Timestamp("2014-01-01"), + Timestamp("2014-02-02"), + Timestamp("2015-03-03"), ] ) tm.assert_series_equal(pd.to_datetime(s, cache=cache), expected) @@ -2046,7 +2044,7 @@ def test_parsers(self, date_str, expected, cache): for res in [result1, result2]: assert res == expected for res in [result3, result4, result6, result8, result9]: - exp = DatetimeIndex([pd.Timestamp(expected)]) + exp = DatetimeIndex([Timestamp(expected)]) tm.assert_index_equal(res, exp) # these really need to have yearfirst, but we don't support @@ -2242,7 +2240,7 @@ def units_from_epochs(): def epochs(epoch_1960, request): """Timestamp at 1960-01-01 in various forms. - * pd.Timestamp + * Timestamp * datetime.datetime * numpy.datetime64 * str @@ -2270,7 +2268,7 @@ def test_to_basic(self, julian_dates): result = Series(pd.to_datetime(julian_dates, unit="D", origin="julian")) expected = Series( - pd.to_datetime(julian_dates - pd.Timestamp(0).to_julian_date(), unit="D") + pd.to_datetime(julian_dates - Timestamp(0).to_julian_date(), unit="D") ) tm.assert_series_equal(result, expected)
https://api.github.com/repos/pandas-dev/pandas/pulls/37401
2020-10-25T14:43:14Z
2020-10-30T23:15:23Z
2020-10-30T23:15:23Z
2020-10-31T00:42:12Z
REGR/PERF: Index.is_ performance regression
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 006469f79780d..24caf6ee49b4a 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -545,7 +545,7 @@ def is_(self, other) -> bool: return True elif not hasattr(other, "_id"): return False - elif com.any_none(self._id, other._id): + elif self._id is None or other._id is None: return False else: return self._id is other._id
Fixes https://github.com/pandas-dev/pandas/pull/37321#issuecomment-715878012 The offender is actually #37321. Apparantly is's a bit slow to do the check using a generator like `com.any_none`. ```python In [1]: from pandas import * In [2]: idx_large_fast = RangeIndex(100000) ...: idx_small_slow = date_range(start="1/1/2012", periods=1) ...: mi_large_slow = MultiIndex.from_product([idx_large_fast, idx_small_slow]) ...: ...: idx_non_object = RangeIndex(1) In[3]: %timeit mi_large_slow.equals(idx_non_object) 3.13 µs ± 79.4 ns per loop # master 2.09 µs ± 31.1 ns per loop # This PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/37400
2020-10-25T11:30:35Z
2020-10-26T03:06:07Z
2020-10-26T03:06:07Z
2020-10-26T08:03:30Z
CLN: nanops
diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index b101da196fdd8..c7b6e132f9a74 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -381,18 +381,16 @@ def _na_for_min_count( if is_numeric_dtype(values): values = values.astype("float64") fill_value = na_value_for_dtype(values.dtype) + if fill_value is NaT: + fill_value = values.dtype.type("NaT", "ns") if values.ndim == 1: return fill_value else: assert axis is not None # assertion to make mypy happy result_shape = values.shape[:axis] + values.shape[axis + 1 :] - # calling np.full with dtype parameter throws an ValueError when called - # with dtype=np.datetime64 and and fill_value=pd.NaT - try: - result = np.full(result_shape, fill_value, dtype=values.dtype) - except ValueError: - result = np.full(result_shape, fill_value) + + result = np.full(result_shape, fill_value, dtype=values.dtype) return result @@ -526,11 +524,9 @@ def nansum( def _mask_datetimelike_result( result: Union[np.ndarray, np.datetime64, np.timedelta64], axis: Optional[int], - mask: Optional[np.ndarray], + mask: np.ndarray, orig_values: np.ndarray, ): - if mask is None: - mask = isna(orig_values) if isinstance(result, np.ndarray): # we need to apply the mask result = result.astype("i8").view(orig_values.dtype)
This sits on top of #37394. The cleanup in _maybe_get_mask means that we end up getting a correctly-dtyped result instead of object-dtype, which becomes important in the upcoming nanmean PR.
https://api.github.com/repos/pandas-dev/pandas/pulls/37396
2020-10-25T03:19:21Z
2020-10-26T12:13:15Z
2020-10-26T12:13:15Z
2020-10-26T15:11:01Z
TST/REF: collect tests by method
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 87c6ae09aac11..c317e90181a8f 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -10,10 +10,12 @@ Interval, NaT, Period, + PeriodIndex, Series, Timestamp, date_range, notna, + period_range, ) import pandas._testing as tm from pandas.core.arrays import SparseArray @@ -213,3 +215,17 @@ def test_setitem_dt64tz(self, timezone_frame): result = df2["B"] tm.assert_series_equal(notna(result), Series([True, False, True], name="B")) tm.assert_series_equal(df2.dtypes, df.dtypes) + + def test_setitem_periodindex(self): + rng = period_range("1/1/2000", periods=5, name="index") + df = DataFrame(np.random.randn(5, 3), index=rng) + + df["Index"] = rng + rs = Index(df["Index"]) + tm.assert_index_equal(rs, rng, check_names=False) + assert rs.name == "Index" + assert rng.name == "index" + + rs = df.reset_index().set_index("index") + assert isinstance(rs.index, PeriodIndex) + tm.assert_index_equal(rs.index, rng) diff --git a/pandas/tests/frame/test_period.py b/pandas/tests/frame/test_period.py index 37a4d7ffcf04f..cf467e3eda60a 100644 --- a/pandas/tests/frame/test_period.py +++ b/pandas/tests/frame/test_period.py @@ -1,6 +1,6 @@ import numpy as np -from pandas import DataFrame, Index, PeriodIndex, period_range +from pandas import DataFrame, period_range import pandas._testing as tm @@ -17,17 +17,3 @@ def test_as_frame_columns(self): ts = df["1/1/2000"] tm.assert_series_equal(ts, df.iloc[:, 0]) - - def test_frame_setitem(self): - rng = period_range("1/1/2000", periods=5, name="index") - df = DataFrame(np.random.randn(5, 3), index=rng) - - df["Index"] = rng - rs = Index(df["Index"]) - tm.assert_index_equal(rs, rng, check_names=False) - assert rs.name == "Index" - assert rng.name == "index" - - rs = df.reset_index().set_index("index") - assert isinstance(rs.index, PeriodIndex) - tm.assert_index_equal(rs.index, rng) diff --git a/pandas/tests/groupby/test_counting.py b/pandas/tests/groupby/test_counting.py index c03ed00e1a081..04b73b16ae2c7 100644 --- a/pandas/tests/groupby/test_counting.py +++ b/pandas/tests/groupby/test_counting.py @@ -241,6 +241,20 @@ def test_count_groupby_column_with_nan_in_groupby_column(self): ) tm.assert_frame_equal(expected, res) + def test_groupby_count_dateparseerror(self): + dr = date_range(start="1/1/2012", freq="5min", periods=10) + + # BAD Example, datetimes first + ser = Series(np.arange(10), index=[dr, np.arange(10)]) + grouped = ser.groupby(lambda x: x[1] % 2 == 0) + result = grouped.count() + + ser = Series(np.arange(10), index=[np.arange(10), dr]) + grouped = ser.groupby(lambda x: x[0] % 2 == 0) + expected = grouped.count() + + tm.assert_series_equal(result, expected) + def test_groupby_timedelta_cython_count(): df = DataFrame( diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index c069b689c1710..3ea5f3729d793 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -107,3 +107,38 @@ def test_setitem_boolean_different_order(self, string_series): expected[expected > 0] = 0 tm.assert_series_equal(copy, expected) + + +class TestSetitemViewCopySemantics: + def test_setitem_invalidates_datetime_index_freq(self): + # GH#24096 altering a datetime64tz Series inplace invalidates the + # `freq` attribute on the underlying DatetimeIndex + + dti = date_range("20130101", periods=3, tz="US/Eastern") + ts = dti[1] + ser = Series(dti) + assert ser._values is not dti + assert ser._values._data.base is not dti._data._data.base + assert dti.freq == "D" + ser.iloc[1] = NaT + assert ser._values.freq is None + + # check that the DatetimeIndex was not altered in place + assert ser._values is not dti + assert ser._values._data.base is not dti._data._data.base + assert dti[1] == ts + assert dti.freq == "D" + + def test_dt64tz_setitem_does_not_mutate_dti(self): + # GH#21907, GH#24096 + dti = date_range("2016-01-01", periods=10, tz="US/Pacific") + ts = dti[0] + ser = Series(dti) + assert ser._values is not dti + assert ser._values._data.base is not dti._data._data.base + assert ser._mgr.blocks[0].values is not dti + assert ser._mgr.blocks[0].values._data.base is not dti._data._data.base + + ser[::3] = NaT + assert ser[0] is NaT + assert dti[0] == ts diff --git a/pandas/tests/series/methods/test_astype.py b/pandas/tests/series/methods/test_astype.py index dc9edccb640b5..8044b590b3463 100644 --- a/pandas/tests/series/methods/test_astype.py +++ b/pandas/tests/series/methods/test_astype.py @@ -14,6 +14,7 @@ CategoricalDtype, Index, Interval, + NaT, Series, Timedelta, Timestamp, @@ -75,6 +76,19 @@ def test_astype_dict_like(self, dtype_class): class TestAstype: + def test_astype_float_to_period(self): + result = Series([np.nan]).astype("period[D]") + expected = Series([NaT], dtype="period[D]") + tm.assert_series_equal(result, expected) + + def test_astype_no_pandas_dtype(self): + # https://github.com/pandas-dev/pandas/pull/24866 + ser = Series([1, 2], dtype="int64") + # Don't have PandasDtype in the public API, so we use `.array.dtype`, + # which is a PandasDtype. + result = ser.astype(ser.array.dtype) + tm.assert_series_equal(result, ser) + @pytest.mark.parametrize("dtype", [np.datetime64, np.timedelta64]) def test_astype_generic_timestamp_no_frequency(self, dtype, request): # see GH#15524, GH#15987 diff --git a/pandas/tests/series/methods/test_isna.py b/pandas/tests/series/methods/test_isna.py new file mode 100644 index 0000000000000..1760b0b9726e0 --- /dev/null +++ b/pandas/tests/series/methods/test_isna.py @@ -0,0 +1,32 @@ +""" +We also test Series.notna in this file. +""" +import numpy as np + +from pandas import Period, Series +import pandas._testing as tm + + +class TestIsna: + def test_isna_period_dtype(self): + # GH#13737 + ser = Series([Period("2011-01", freq="M"), Period("NaT", freq="M")]) + + expected = Series([False, True]) + + result = ser.isna() + tm.assert_series_equal(result, expected) + + result = ser.notna() + tm.assert_series_equal(result, ~expected) + + def test_isna(self): + ser = Series([0, 5.4, 3, np.nan, -0.001]) + expected = Series([False, False, False, True, False]) + tm.assert_series_equal(ser.isna(), expected) + tm.assert_series_equal(ser.notna(), ~expected) + + ser = Series(["hi", "", np.nan]) + expected = Series([False, False, True]) + tm.assert_series_equal(ser.isna(), expected) + tm.assert_series_equal(ser.notna(), ~expected) diff --git a/pandas/tests/series/test_block_internals.py b/pandas/tests/series/test_block_internals.py deleted file mode 100644 index d0dfbe6f5b569..0000000000000 --- a/pandas/tests/series/test_block_internals.py +++ /dev/null @@ -1,39 +0,0 @@ -import pandas as pd - -# Segregated collection of methods that require the BlockManager internal data -# structure - - -class TestSeriesBlockInternals: - def test_setitem_invalidates_datetime_index_freq(self): - # GH#24096 altering a datetime64tz Series inplace invalidates the - # `freq` attribute on the underlying DatetimeIndex - - dti = pd.date_range("20130101", periods=3, tz="US/Eastern") - ts = dti[1] - ser = pd.Series(dti) - assert ser._values is not dti - assert ser._values._data.base is not dti._data._data.base - assert dti.freq == "D" - ser.iloc[1] = pd.NaT - assert ser._values.freq is None - - # check that the DatetimeIndex was not altered in place - assert ser._values is not dti - assert ser._values._data.base is not dti._data._data.base - assert dti[1] == ts - assert dti.freq == "D" - - def test_dt64tz_setitem_does_not_mutate_dti(self): - # GH#21907, GH#24096 - dti = pd.date_range("2016-01-01", periods=10, tz="US/Pacific") - ts = dti[0] - ser = pd.Series(dti) - assert ser._values is not dti - assert ser._values._data.base is not dti._data._data.base - assert ser._mgr.blocks[0].values is not dti - assert ser._mgr.blocks[0].values._data.base is not dti._data._data.base - - ser[::3] = pd.NaT - assert ser[0] is pd.NaT - assert dti[0] == ts diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 1958e44b6d1a3..25ef82c8eecbc 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -35,6 +35,7 @@ ) import pandas._testing as tm from pandas.core.arrays import IntervalArray, period_array +from pandas.core.internals.blocks import IntBlock class TestSeriesConstructors: @@ -1527,3 +1528,25 @@ def test_series_constructor_datetimelike_index_coercion(self): with tm.assert_produces_warning(FutureWarning): assert ser.index.is_all_dates assert isinstance(ser.index, DatetimeIndex) + + +class TestSeriesConstructorInternals: + def test_constructor_no_pandas_array(self): + ser = Series([1, 2, 3]) + result = Series(ser.array) + tm.assert_series_equal(ser, result) + assert isinstance(result._mgr.blocks[0], IntBlock) + + def test_from_array(self): + result = Series(pd.array(["1H", "2H"], dtype="timedelta64[ns]")) + assert result._mgr.blocks[0].is_extension is False + + result = Series(pd.array(["2015"], dtype="datetime64[ns]")) + assert result._mgr.blocks[0].is_extension is False + + def test_from_list_dtype(self): + result = Series(["1H", "2H"], dtype="timedelta64[ns]") + assert result._mgr.blocks[0].is_extension is False + + result = Series(["2015"], dtype="datetime64[ns]") + assert result._mgr.blocks[0].is_extension is False diff --git a/pandas/tests/series/test_internals.py b/pandas/tests/series/test_internals.py deleted file mode 100644 index be106e8b1fef4..0000000000000 --- a/pandas/tests/series/test_internals.py +++ /dev/null @@ -1,49 +0,0 @@ -import numpy as np - -import pandas as pd -from pandas import Series -import pandas._testing as tm -from pandas.core.internals.blocks import IntBlock - - -class TestSeriesInternals: - def test_constructor_no_pandas_array(self): - ser = Series([1, 2, 3]) - result = Series(ser.array) - tm.assert_series_equal(ser, result) - assert isinstance(result._mgr.blocks[0], IntBlock) - - def test_astype_no_pandas_dtype(self): - # https://github.com/pandas-dev/pandas/pull/24866 - ser = Series([1, 2], dtype="int64") - # Don't have PandasDtype in the public API, so we use `.array.dtype`, - # which is a PandasDtype. - result = ser.astype(ser.array.dtype) - tm.assert_series_equal(result, ser) - - def test_from_array(self): - result = Series(pd.array(["1H", "2H"], dtype="timedelta64[ns]")) - assert result._mgr.blocks[0].is_extension is False - - result = Series(pd.array(["2015"], dtype="datetime64[ns]")) - assert result._mgr.blocks[0].is_extension is False - - def test_from_list_dtype(self): - result = Series(["1H", "2H"], dtype="timedelta64[ns]") - assert result._mgr.blocks[0].is_extension is False - - result = Series(["2015"], dtype="datetime64[ns]") - assert result._mgr.blocks[0].is_extension is False - - -def test_hasnans_uncached_for_series(): - # GH#19700 - idx = pd.Index([0, 1]) - assert idx.hasnans is False - assert "hasnans" in idx._cache - ser = idx.to_series() - assert ser.hasnans is False - assert not hasattr(ser, "_cache") - ser.iloc[-1] = np.nan - assert ser.hasnans is True - assert Series.hasnans.__doc__ == pd.Index.hasnans.__doc__ diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index f601d7cb655b3..6fefeaa818a77 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -92,20 +92,15 @@ def test_valid(self, datetime_series): tm.assert_series_equal(result, ts[1::2]) tm.assert_series_equal(result, ts[pd.notna(ts)]) - def test_isna(self): - ser = Series([0, 5.4, 3, np.nan, -0.001]) - expected = Series([False, False, False, True, False]) - tm.assert_series_equal(ser.isna(), expected) - - ser = Series(["hi", "", np.nan]) - expected = Series([False, False, True]) - tm.assert_series_equal(ser.isna(), expected) - - def test_notna(self): - ser = Series([0, 5.4, 3, np.nan, -0.001]) - expected = Series([True, True, True, False, True]) - tm.assert_series_equal(ser.notna(), expected) - - ser = Series(["hi", "", np.nan]) - expected = Series([True, True, False]) - tm.assert_series_equal(ser.notna(), expected) + +def test_hasnans_uncached_for_series(): + # GH#19700 + idx = Index([0, 1]) + assert idx.hasnans is False + assert "hasnans" in idx._cache + ser = idx.to_series() + assert ser.hasnans is False + assert not hasattr(ser, "_cache") + ser.iloc[-1] = np.nan + assert ser.hasnans is True + assert Series.hasnans.__doc__ == Index.hasnans.__doc__ diff --git a/pandas/tests/series/test_period.py b/pandas/tests/series/test_period.py index c73c57c3d2d91..d079111aa12d6 100644 --- a/pandas/tests/series/test_period.py +++ b/pandas/tests/series/test_period.py @@ -3,19 +3,12 @@ import pandas as pd from pandas import DataFrame, Series, period_range -import pandas._testing as tm class TestSeriesPeriod: def setup_method(self, method): self.series = Series(period_range("2000-01-01", periods=10, freq="D")) - def test_isna(self): - # GH 13737 - s = Series([pd.Period("2011-01", freq="M"), pd.Period("NaT", freq="M")]) - tm.assert_series_equal(s.isna(), Series([False, True])) - tm.assert_series_equal(s.notna(), Series([True, False])) - # --------------------------------------------------------------------- # NaT support @@ -29,11 +22,6 @@ def test_NaT_scalar(self): series[2] = val assert pd.isna(series[2]) - def test_NaT_cast(self): - result = Series([np.nan]).astype("period[D]") - expected = Series([pd.NaT], dtype="period[D]") - tm.assert_series_equal(result, expected) - def test_intercept_astype_object(self): expected = self.series.astype("object") diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index ba270448c19ed..295f70935a786 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -46,20 +46,6 @@ def test_promote_datetime_date(self): expected = rng.get_indexer(ts_slice.index) tm.assert_numpy_array_equal(result, expected) - def test_groupby_count_dateparseerror(self): - dr = date_range(start="1/1/2012", freq="5min", periods=10) - - # BAD Example, datetimes first - s = Series(np.arange(10), index=[dr, np.arange(10)]) - grouped = s.groupby(lambda x: x[1] % 2 == 0) - result = grouped.count() - - s = Series(np.arange(10), index=[np.arange(10), dr]) - grouped = s.groupby(lambda x: x[0] % 2 == 0) - expected = grouped.count() - - tm.assert_series_equal(result, expected) - def test_series_map_box_timedelta(self): # GH 11349 s = Series(timedelta_range("1 day 1 s", periods=5, freq="h"))
https://api.github.com/repos/pandas-dev/pandas/pulls/37395
2020-10-25T02:37:34Z
2020-10-26T03:07:17Z
2020-10-26T03:07:17Z
2020-10-26T03:33:00Z
BUG: Series[td64].sum() wrong on empty series, closes #37151
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index a9b4ad2e5374a..1e2747d3bc463 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -374,6 +374,7 @@ Datetimelike - Bug in :class:`DatetimeIndex.shift` incorrectly raising when shifting empty indexes (:issue:`14811`) - :class:`Timestamp` and :class:`DatetimeIndex` comparisons between timezone-aware and timezone-naive objects now follow the standard library ``datetime`` behavior, returning ``True``/``False`` for ``!=``/``==`` and raising for inequality comparisons (:issue:`28507`) - Bug in :meth:`DatetimeIndex.equals` and :meth:`TimedeltaIndex.equals` incorrectly considering ``int64`` indexes as equal (:issue:`36744`) +- Bug in :meth:`TimedeltaIndex.sum` and :meth:`Series.sum` with ``timedelta64`` dtype on an empty index or series returning ``NaT`` instead of ``Timedelta(0)`` (:issue:`31751`) Timedelta ^^^^^^^^^ diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index 64e5f78d961d1..17fcd00b7b251 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -381,14 +381,12 @@ def sum( nv.validate_sum( (), dict(dtype=dtype, out=out, keepdims=keepdims, initial=initial) ) - if not self.size and (self.ndim == 1 or axis is None): - return NaT result = nanops.nansum( - self._data, axis=axis, skipna=skipna, min_count=min_count + self._ndarray, axis=axis, skipna=skipna, min_count=min_count ) - if is_scalar(result): - return Timedelta(result) + if axis is None or self.ndim == 1: + return self._box_func(result) return self._from_backing_data(result) def std( @@ -403,13 +401,11 @@ def std( nv.validate_stat_ddof_func( (), dict(dtype=dtype, out=out, keepdims=keepdims), fname="std" ) - if not len(self): - return NaT - if not skipna and self._hasnans: - return NaT - result = nanops.nanstd(self._data, axis=axis, skipna=skipna, ddof=ddof) - return Timedelta(result) + result = nanops.nanstd(self._ndarray, axis=axis, skipna=skipna, ddof=ddof) + if axis is None or self.ndim == 1: + return self._box_func(result) + return self._from_backing_data(result) # ---------------------------------------------------------------- # Rendering Methods diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 83399a87e5667..b101da196fdd8 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -228,7 +228,7 @@ def _maybe_get_mask( # Boolean data cannot contain nulls, so signal via mask being None return None - if skipna: + if skipna or needs_i8_conversion(values.dtype): mask = isna(values) return mask diff --git a/pandas/tests/arrays/test_timedeltas.py b/pandas/tests/arrays/test_timedeltas.py index 976f5d0c90f19..f9584e29d47bc 100644 --- a/pandas/tests/arrays/test_timedeltas.py +++ b/pandas/tests/arrays/test_timedeltas.py @@ -2,6 +2,7 @@ import pytest import pandas as pd +from pandas import Timedelta import pandas._testing as tm from pandas.core.arrays import TimedeltaArray @@ -175,7 +176,7 @@ def test_neg_freq(self): class TestReductions: - @pytest.mark.parametrize("name", ["sum", "std", "min", "max", "median"]) + @pytest.mark.parametrize("name", ["std", "min", "max", "median"]) @pytest.mark.parametrize("skipna", [True, False]) def test_reductions_empty(self, name, skipna): tdi = pd.TimedeltaIndex([]) @@ -187,6 +188,19 @@ def test_reductions_empty(self, name, skipna): result = getattr(arr, name)(skipna=skipna) assert result is pd.NaT + @pytest.mark.parametrize("skipna", [True, False]) + def test_sum_empty(self, skipna): + tdi = pd.TimedeltaIndex([]) + arr = tdi.array + + result = tdi.sum(skipna=skipna) + assert isinstance(result, Timedelta) + assert result == Timedelta(0) + + result = arr.sum(skipna=skipna) + assert isinstance(result, Timedelta) + assert result == Timedelta(0) + def test_min_max(self): arr = TimedeltaArray._from_sequence(["3H", "3H", "NaT", "2H", "5H", "4H"]) diff --git a/pandas/tests/series/test_reductions.py b/pandas/tests/series/test_reductions.py index 0c946b2cbccc9..0e8bf8f052206 100644 --- a/pandas/tests/series/test_reductions.py +++ b/pandas/tests/series/test_reductions.py @@ -15,6 +15,16 @@ def test_reductions_td64_with_nat(): assert ser.max() == exp +@pytest.mark.parametrize("skipna", [True, False]) +def test_td64_sum_empty(skipna): + # GH#37151 + ser = Series([], dtype="timedelta64[ns]") + + result = ser.sum(skipna=skipna) + assert isinstance(result, pd.Timedelta) + assert result == pd.Timedelta(0) + + def test_td64_summation_overflow(): # GH#9442 ser = Series(pd.date_range("20130101", periods=100000, freq="H"))
- [x] closes #37151 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Will handle min_count on the next pass.
https://api.github.com/repos/pandas-dev/pandas/pulls/37394
2020-10-25T02:32:00Z
2020-10-26T12:06:46Z
2020-10-26T12:06:46Z
2020-10-26T15:19:15Z
BUG: DataFrame.std(skipna=False) with td64 dtype
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index a9b4ad2e5374a..f54fa9d98a592 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -402,6 +402,7 @@ Numeric - Bug in :class:`DataFrame` arithmetic ops incorrectly accepting keyword arguments (:issue:`36843`) - Bug in :class:`IntervalArray` comparisons with :class:`Series` not returning :class:`Series` (:issue:`36908`) - Bug in :class:`DataFrame` allowing arithmetic operations with list of array-likes with undefined results. Behavior changed to raising ``ValueError`` (:issue:`36702`) +- Bug in :meth:`DataFrame.std`` with ``timedelta64`` dtype and ``skipna=False`` (:issue:`37392`) Conversion ^^^^^^^^^^ diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index 83399a87e5667..b101da196fdd8 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -228,7 +228,7 @@ def _maybe_get_mask( # Boolean data cannot contain nulls, so signal via mask being None return None - if skipna: + if skipna or needs_i8_conversion(values.dtype): mask = isna(values) return mask diff --git a/pandas/tests/arrays/test_timedeltas.py b/pandas/tests/arrays/test_timedeltas.py index 976f5d0c90f19..f67a554a435ef 100644 --- a/pandas/tests/arrays/test_timedeltas.py +++ b/pandas/tests/arrays/test_timedeltas.py @@ -3,6 +3,7 @@ import pandas as pd import pandas._testing as tm +from pandas.core import nanops from pandas.core.arrays import TimedeltaArray @@ -288,12 +289,19 @@ def test_std(self): assert isinstance(result, pd.Timedelta) assert result == expected + result = nanops.nanstd(np.asarray(arr), skipna=True) + assert isinstance(result, pd.Timedelta) + assert result == expected + result = arr.std(skipna=False) assert result is pd.NaT result = tdi.std(skipna=False) assert result is pd.NaT + result = nanops.nanstd(np.asarray(arr), skipna=False) + assert result is pd.NaT + def test_median(self): tdi = pd.TimedeltaIndex(["0H", "3H", "NaT", "5H06m", "0H", "2H"]) arr = tdi.array @@ -307,8 +315,8 @@ def test_median(self): assert isinstance(result, pd.Timedelta) assert result == expected - result = arr.std(skipna=False) + result = arr.median(skipna=False) assert result is pd.NaT - result = tdi.std(skipna=False) + result = tdi.median(skipna=False) assert result is pd.NaT diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index ddca67306d804..ee4da37ce10f3 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -753,6 +753,22 @@ def test_operators_timedelta64(self): assert df["off1"].dtype == "timedelta64[ns]" assert df["off2"].dtype == "timedelta64[ns]" + def test_std_timedelta64_skipna_false(self): + # GH#37392 + tdi = pd.timedelta_range("1 Day", periods=10) + df = DataFrame({"A": tdi, "B": tdi}) + df.iloc[-2, -1] = pd.NaT + + result = df.std(skipna=False) + expected = Series( + [df["A"].std(), pd.NaT], index=["A", "B"], dtype="timedelta64[ns]" + ) + tm.assert_series_equal(result, expected) + + result = df.std(axis=1, skipna=False) + expected = Series([pd.Timedelta(0)] * 8 + [pd.NaT, pd.Timedelta(0)]) + tm.assert_series_equal(result, expected) + def test_sum_corner(self): empty_frame = DataFrame()
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37392
2020-10-25T00:36:44Z
2020-10-26T03:14:07Z
2020-10-26T03:14:07Z
2020-10-26T03:33:43Z
CLN: Deprecate dayofweek/hello day_of_week (#9606)
diff --git a/doc/redirects.csv b/doc/redirects.csv index bceb4b5961324..de69d0168835d 100644 --- a/doc/redirects.csv +++ b/doc/redirects.csv @@ -542,7 +542,9 @@ generated/pandas.DatetimeIndex.date,../reference/api/pandas.DatetimeIndex.date generated/pandas.DatetimeIndex.day,../reference/api/pandas.DatetimeIndex.day generated/pandas.DatetimeIndex.day_name,../reference/api/pandas.DatetimeIndex.day_name generated/pandas.DatetimeIndex.dayofweek,../reference/api/pandas.DatetimeIndex.dayofweek +generated/pandas.DatetimeIndex.day_of_week,../reference/api/pandas.DatetimeIndex.day_of_week generated/pandas.DatetimeIndex.dayofyear,../reference/api/pandas.DatetimeIndex.dayofyear +generated/pandas.DatetimeIndex.day_of_year,../reference/api/pandas.DatetimeIndex.day_of_year generated/pandas.DatetimeIndex.floor,../reference/api/pandas.DatetimeIndex.floor generated/pandas.DatetimeIndex.freq,../reference/api/pandas.DatetimeIndex.freq generated/pandas.DatetimeIndex.freqstr,../reference/api/pandas.DatetimeIndex.freqstr @@ -839,7 +841,9 @@ generated/pandas.option_context,../reference/api/pandas.option_context generated/pandas.Period.asfreq,../reference/api/pandas.Period.asfreq generated/pandas.Period.day,../reference/api/pandas.Period.day generated/pandas.Period.dayofweek,../reference/api/pandas.Period.dayofweek +generated/pandas.Period.day_of_week,../reference/api/pandas.Period.day_of_week generated/pandas.Period.dayofyear,../reference/api/pandas.Period.dayofyear +generated/pandas.Period.day_of_year,../reference/api/pandas.Period.day_of_year generated/pandas.Period.days_in_month,../reference/api/pandas.Period.days_in_month generated/pandas.Period.daysinmonth,../reference/api/pandas.Period.daysinmonth generated/pandas.Period.end_time,../reference/api/pandas.Period.end_time @@ -850,7 +854,9 @@ generated/pandas.Period,../reference/api/pandas.Period generated/pandas.PeriodIndex.asfreq,../reference/api/pandas.PeriodIndex.asfreq generated/pandas.PeriodIndex.day,../reference/api/pandas.PeriodIndex.day generated/pandas.PeriodIndex.dayofweek,../reference/api/pandas.PeriodIndex.dayofweek +generated/pandas.PeriodIndex.day_of_week,../reference/api/pandas.PeriodIndex.day_of_week generated/pandas.PeriodIndex.dayofyear,../reference/api/pandas.PeriodIndex.dayofyear +generated/pandas.PeriodIndex.day_of_year,../reference/api/pandas.PeriodIndex.day_of_year generated/pandas.PeriodIndex.days_in_month,../reference/api/pandas.PeriodIndex.days_in_month generated/pandas.PeriodIndex.daysinmonth,../reference/api/pandas.PeriodIndex.daysinmonth generated/pandas.PeriodIndex.end_time,../reference/api/pandas.PeriodIndex.end_time @@ -993,7 +999,9 @@ generated/pandas.Series.dt.date,../reference/api/pandas.Series.dt.date generated/pandas.Series.dt.day,../reference/api/pandas.Series.dt.day generated/pandas.Series.dt.day_name,../reference/api/pandas.Series.dt.day_name generated/pandas.Series.dt.dayofweek,../reference/api/pandas.Series.dt.dayofweek +generated/pandas.Series.dt.day_of_week,../reference/api/pandas.Series.dt.day_of_week generated/pandas.Series.dt.dayofyear,../reference/api/pandas.Series.dt.dayofyear +generated/pandas.Series.dt.day_of_year,../reference/api/pandas.Series.dt.day_of_year generated/pandas.Series.dt.days,../reference/api/pandas.Series.dt.days generated/pandas.Series.dt.days_in_month,../reference/api/pandas.Series.dt.days_in_month generated/pandas.Series.dt.daysinmonth,../reference/api/pandas.Series.dt.daysinmonth @@ -1326,7 +1334,9 @@ generated/pandas.Timestamp.date,../reference/api/pandas.Timestamp.date generated/pandas.Timestamp.day,../reference/api/pandas.Timestamp.day generated/pandas.Timestamp.day_name,../reference/api/pandas.Timestamp.day_name generated/pandas.Timestamp.dayofweek,../reference/api/pandas.Timestamp.dayofweek +generated/pandas.Timestamp.day_of_week,../reference/api/pandas.Timestamp.day_of_week generated/pandas.Timestamp.dayofyear,../reference/api/pandas.Timestamp.dayofyear +generated/pandas.Timestamp.day_of_year,../reference/api/pandas.Timestamp.day_of_year generated/pandas.Timestamp.days_in_month,../reference/api/pandas.Timestamp.days_in_month generated/pandas.Timestamp.daysinmonth,../reference/api/pandas.Timestamp.daysinmonth generated/pandas.Timestamp.dst,../reference/api/pandas.Timestamp.dst diff --git a/doc/source/reference/arrays.rst b/doc/source/reference/arrays.rst index 5c068d8404cd6..43e2509469488 100644 --- a/doc/source/reference/arrays.rst +++ b/doc/source/reference/arrays.rst @@ -63,7 +63,9 @@ Properties Timestamp.asm8 Timestamp.day Timestamp.dayofweek + Timestamp.day_of_week Timestamp.dayofyear + Timestamp.day_of_year Timestamp.days_in_month Timestamp.daysinmonth Timestamp.fold @@ -233,7 +235,9 @@ Properties Period.day Period.dayofweek + Period.day_of_week Period.dayofyear + Period.day_of_year Period.days_in_month Period.daysinmonth Period.end_time diff --git a/doc/source/reference/indexing.rst b/doc/source/reference/indexing.rst index ba12c19763605..d3f9413dae565 100644 --- a/doc/source/reference/indexing.rst +++ b/doc/source/reference/indexing.rst @@ -345,9 +345,11 @@ Time/date components DatetimeIndex.time DatetimeIndex.timetz DatetimeIndex.dayofyear + DatetimeIndex.day_of_year DatetimeIndex.weekofyear DatetimeIndex.week DatetimeIndex.dayofweek + DatetimeIndex.day_of_week DatetimeIndex.weekday DatetimeIndex.quarter DatetimeIndex.tz @@ -461,7 +463,9 @@ Properties PeriodIndex.day PeriodIndex.dayofweek + PeriodIndex.day_of_week PeriodIndex.dayofyear + PeriodIndex.day_of_year PeriodIndex.days_in_month PeriodIndex.daysinmonth PeriodIndex.end_time diff --git a/doc/source/reference/series.rst b/doc/source/reference/series.rst index b4a72c030f7cb..8d74c288bf801 100644 --- a/doc/source/reference/series.rst +++ b/doc/source/reference/series.rst @@ -319,8 +319,10 @@ Datetime properties Series.dt.week Series.dt.weekofyear Series.dt.dayofweek + Series.dt.day_of_week Series.dt.weekday Series.dt.dayofyear + Series.dt.day_of_year Series.dt.quarter Series.dt.is_month_start Series.dt.is_month_end diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst index 9fbd02df50d10..af5e172658386 100644 --- a/doc/source/user_guide/timeseries.rst +++ b/doc/source/user_guide/timeseries.rst @@ -803,9 +803,11 @@ There are several time/date properties that one can access from ``Timestamp`` or time,"Returns datetime.time (does not contain timezone information)" timetz,"Returns datetime.time as local time with timezone information" dayofyear,"The ordinal day of year" + day_of_year,"The ordinal day of year" weekofyear,"The week ordinal of the year" week,"The week ordinal of the year" dayofweek,"The number of the day of the week with Monday=0, Sunday=6" + day_of_week,"The number of the day of the week with Monday=0, Sunday=6" weekday,"The number of the day of the week with Monday=0, Sunday=6" quarter,"Quarter of the date: Jan-Mar = 1, Apr-Jun = 2, etc." days_in_month,"The number of days in the month of the datetime" diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index a9b4ad2e5374a..e399ff1741d19 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -207,6 +207,8 @@ level-by-level basis. Other enhancements ^^^^^^^^^^^^^^^^^^ +- Added ``day_of_week``(compatibility alias ``dayofweek``) property to ``Timestamp``, ``DatetimeIndex``, ``Period``, ``PeriodIndex`` (:issue:`9605`) +- Added ``day_of_year`` (compatibility alias ``dayofyear``) property to ``Timestamp``, ``DatetimeIndex``, ``Period``, ``PeriodIndex`` (:issue:`9605`) - Added :meth:`~DataFrame.set_flags` for setting table-wide flags on a ``Series`` or ``DataFrame`` (:issue:`28394`) - :meth:`DataFrame.applymap` now supports ``na_action`` (:issue:`23803`) - :class:`Index` with object dtype supports division and multiplication (:issue:`34160`) diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index 3a628f997e5d6..88ad008b42c21 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -357,10 +357,12 @@ class NaTType(_NaT): week = property(fget=lambda self: np.nan) dayofyear = property(fget=lambda self: np.nan) + day_of_year = property(fget=lambda self: np.nan) weekofyear = property(fget=lambda self: np.nan) days_in_month = property(fget=lambda self: np.nan) daysinmonth = property(fget=lambda self: np.nan) dayofweek = property(fget=lambda self: np.nan) + day_of_week = property(fget=lambda self: np.nan) # inject Timedelta properties days = property(fget=lambda self: np.nan) diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 27402c8d255b6..b1f9ff71f5faa 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1373,7 +1373,7 @@ cdef accessor _get_accessor_func(str field): return <accessor>pweek elif field == "day_of_year": return <accessor>pday_of_year - elif field == "weekday": + elif field == "weekday" or field == "day_of_week": return <accessor>pweekday elif field == "days_in_month": return <accessor>pdays_in_month @@ -1475,6 +1475,9 @@ cdef class _Period(PeriodMixin): PeriodDtypeBase _dtype BaseOffset freq + dayofweek = _Period.day_of_week + dayofyear = _Period.day_of_year + def __cinit__(self, int64_t ordinal, BaseOffset freq): self.ordinal = ordinal self.freq = freq @@ -1882,7 +1885,7 @@ cdef class _Period(PeriodMixin): return self.weekofyear @property - def dayofweek(self) -> int: + def day_of_week(self) -> int: """ Day of the week the period lies in, with Monday=0 and Sunday=6. @@ -1900,33 +1903,33 @@ cdef class _Period(PeriodMixin): See Also -------- - Period.dayofweek : Day of the week the period lies in. - Period.weekday : Alias of Period.dayofweek. + Period.day_of_week : Day of the week the period lies in. + Period.weekday : Alias of Period.day_of_week. Period.day : Day of the month. Period.dayofyear : Day of the year. Examples -------- >>> per = pd.Period('2017-12-31 22:00', 'H') - >>> per.dayofweek + >>> per.day_of_week 6 For periods that span over multiple days, the day at the beginning of the period is returned. >>> per = pd.Period('2017-12-31 22:00', '4H') - >>> per.dayofweek + >>> per.day_of_week 6 - >>> per.start_time.dayofweek + >>> per.start_time.day_of_week 6 For periods with a frequency higher than days, the last day of the period is returned. >>> per = pd.Period('2018-01', 'M') - >>> per.dayofweek + >>> per.day_of_week 2 - >>> per.end_time.dayofweek + >>> per.end_time.day_of_week 2 """ base = self._dtype._dtype_code @@ -1986,7 +1989,7 @@ cdef class _Period(PeriodMixin): return self.dayofweek @property - def dayofyear(self) -> int: + def day_of_year(self) -> int: """ Return the day of the year. @@ -2002,19 +2005,19 @@ cdef class _Period(PeriodMixin): See Also -------- Period.day : Return the day of the month. - Period.dayofweek : Return the day of week. - PeriodIndex.dayofyear : Return the day of year of all indexes. + Period.day_of_week : Return the day of week. + PeriodIndex.day_of_year : Return the day of year of all indexes. Examples -------- >>> period = pd.Period("2015-10-23", freq='H') - >>> period.dayofyear + >>> period.day_of_year 296 >>> period = pd.Period("2012-12-31", freq='D') - >>> period.dayofyear + >>> period.day_of_year 366 >>> period = pd.Period("2013-01-01", freq='D') - >>> period.dayofyear + >>> period.day_of_year 1 """ base = self._dtype._dtype_code diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index a8f6c60bcb300..9076325d01bab 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -230,6 +230,8 @@ cdef class _Timestamp(ABCTimestamp): # higher than np.ndarray and np.matrix __array_priority__ = 100 + dayofweek = _Timestamp.day_of_week + dayofyear = _Timestamp.day_of_year def __hash__(_Timestamp self): if self.nanosecond: @@ -538,14 +540,14 @@ cdef class _Timestamp(ABCTimestamp): return bool(ccalendar.is_leapyear(self.year)) @property - def dayofweek(self) -> int: + def day_of_week(self) -> int: """ Return day of the week. """ return self.weekday() @property - def dayofyear(self) -> int: + def day_of_year(self) -> int: """ Return the day of the year. """ diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 0780dcfef23cc..d020279ccf49d 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -177,7 +177,9 @@ class DatetimeArray(dtl.TimelikeOps, dtl.DatelikeOps): "week", "weekday", "dayofweek", + "day_of_week", "dayofyear", + "day_of_year", "quarter", "days_in_month", "daysinmonth", @@ -1533,16 +1535,18 @@ def weekofyear(self): 2017-01-08 6 Freq: D, dtype: int64 """ - dayofweek = _field_accessor("dayofweek", "dow", _dayofweek_doc) - weekday = dayofweek + day_of_week = _field_accessor("day_of_week", "dow", _dayofweek_doc) + dayofweek = day_of_week + weekday = day_of_week - dayofyear = _field_accessor( + day_of_year = _field_accessor( "dayofyear", "doy", """ The ordinal day of the year. """, ) + dayofyear = day_of_year quarter = _field_accessor( "quarter", "q", diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index c77350d5f54bf..ef8093660b413 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -140,7 +140,9 @@ class PeriodArray(PeriodMixin, dtl.DatelikeOps): "weekday", "week", "dayofweek", + "day_of_week", "dayofyear", + "day_of_year", "quarter", "qyear", "days_in_month", @@ -381,12 +383,13 @@ def __arrow_array__(self, type=None): """, ) week = weekofyear - dayofweek = _field_accessor( - "weekday", + day_of_week = _field_accessor( + "day_of_week", """ The day of the week with Monday=0, Sunday=6. """, ) + dayofweek = day_of_week weekday = dayofweek dayofyear = day_of_year = _field_accessor( "day_of_year", diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 11417e0b3317e..3da1057ff8b03 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -158,9 +158,11 @@ class DatetimeIndex(DatetimeTimedeltaMixin): time timetz dayofyear + day_of_year weekofyear week dayofweek + day_of_week weekday quarter tz diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index 41968c5972ea5..dbe15ef4bed8c 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -95,7 +95,9 @@ class PeriodIndex(DatetimeIndexOpsMixin, Int64Index): ---------- day dayofweek + day_of_week dayofyear + day_of_year days_in_month daysinmonth end_time diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py index 211d86c89cde7..d7aadda990f53 100644 --- a/pandas/tests/generic/test_finalize.py +++ b/pandas/tests/generic/test_finalize.py @@ -678,7 +678,9 @@ def test_datetime_method(method): "microsecond", "nanosecond", "dayofweek", + "day_of_week", "dayofyear", + "day_of_year", "quarter", "is_month_start", "is_month_end", diff --git a/pandas/tests/indexes/datetimes/test_scalar_compat.py b/pandas/tests/indexes/datetimes/test_scalar_compat.py index 0d39e034905d2..d6016b9e14743 100644 --- a/pandas/tests/indexes/datetimes/test_scalar_compat.py +++ b/pandas/tests/indexes/datetimes/test_scalar_compat.py @@ -38,7 +38,9 @@ def test_dti_date_out_of_range(self, data): "field", [ "dayofweek", + "day_of_week", "dayofyear", + "day_of_year", "quarter", "days_in_month", "is_month_start", diff --git a/pandas/tests/indexes/period/test_period.py b/pandas/tests/indexes/period/test_period.py index 8467fde0f7021..f4773e885829e 100644 --- a/pandas/tests/indexes/period/test_period.py +++ b/pandas/tests/indexes/period/test_period.py @@ -249,7 +249,9 @@ def _check_all_fields(self, periodindex): "weekofyear", "week", "dayofweek", + "day_of_week", "dayofyear", + "day_of_year", "quarter", "qyear", "days_in_month", diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index cee7ac450e411..92675f387fe1e 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -26,6 +26,7 @@ def test_properties_business(self): ts = Timestamp("2017-10-01", freq="B") control = Timestamp("2017-10-01") assert ts.dayofweek == 6 + assert ts.day_of_week == 6 assert not ts.is_month_start # not a weekday assert not ts.is_quarter_start # not a weekday # Control case: non-business is month/qtr start @@ -35,6 +36,7 @@ def test_properties_business(self): ts = Timestamp("2017-09-30", freq="B") control = Timestamp("2017-09-30") assert ts.dayofweek == 5 + assert ts.day_of_week == 5 assert not ts.is_month_end # not a weekday assert not ts.is_quarter_end # not a weekday # Control case: non-business is month/qtr start @@ -61,8 +63,10 @@ def check(value, equal): check(ts.microsecond, 100) check(ts.nanosecond, 1) check(ts.dayofweek, 6) + check(ts.day_of_week, 6) check(ts.quarter, 2) check(ts.dayofyear, 130) + check(ts.day_of_year, 130) check(ts.week, 19) check(ts.daysinmonth, 31) check(ts.daysinmonth, 31) @@ -81,8 +85,10 @@ def check(value, equal): check(ts.microsecond, 0) check(ts.nanosecond, 0) check(ts.dayofweek, 2) + check(ts.day_of_week, 2) check(ts.quarter, 4) check(ts.dayofyear, 365) + check(ts.day_of_year, 365) check(ts.week, 1) check(ts.daysinmonth, 31)
Rename dayofweek properties in Period, Datetime, and PeriodArray classes. Add day_of_week property to respective tests for each class. - [x] closes #9606 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37390
2020-10-24T22:39:20Z
2020-10-29T01:18:57Z
2020-10-29T01:18:57Z
2020-10-29T01:19:03Z
PERF: release gil for ewma_time
diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx index b2dbf7802e6f0..3556085bb300b 100644 --- a/pandas/_libs/window/aggregations.pyx +++ b/pandas/_libs/window/aggregations.pyx @@ -1,14 +1,13 @@ # cython: boundscheck=False, wraparound=False, cdivision=True import cython -from cython import Py_ssize_t from libcpp.deque cimport deque import numpy as np cimport numpy as cnp -from numpy cimport float32_t, float64_t, int64_t, ndarray, uint8_t +from numpy cimport float32_t, float64_t, int64_t, ndarray cnp.import_array() @@ -1398,7 +1397,7 @@ def roll_weighted_var(float64_t[:] values, float64_t[:] weights, # ---------------------------------------------------------------------- # Exponentially weighted moving average -def ewma_time(ndarray[float64_t] vals, int minp, ndarray[int64_t] times, +def ewma_time(const float64_t[:] vals, int minp, ndarray[int64_t] times, int64_t halflife): """ Compute exponentially-weighted moving average using halflife and time @@ -1416,30 +1415,40 @@ def ewma_time(ndarray[float64_t] vals, int minp, ndarray[int64_t] times, ndarray """ cdef: - Py_ssize_t i, num_not_nan = 0, N = len(vals) + Py_ssize_t i, j, num_not_nan = 0, N = len(vals) bint is_not_nan - float64_t last_result - ndarray[uint8_t] mask = np.zeros(N, dtype=np.uint8) - ndarray[float64_t] weights, observations, output = np.empty(N, dtype=np.float64) + float64_t last_result, weights_dot, weights_sum, weight, halflife_float + float64_t[:] times_float + float64_t[:] observations = np.zeros(N, dtype=float) + float64_t[:] times_masked = np.zeros(N, dtype=float) + ndarray[float64_t] output = np.empty(N, dtype=float) if N == 0: return output + halflife_float = <float64_t>halflife + times_float = times.astype(float) last_result = vals[0] - for i in range(N): - is_not_nan = vals[i] == vals[i] - num_not_nan += is_not_nan - if is_not_nan: - mask[i] = 1 - weights = 0.5 ** ((times[i] - times[mask.view(np.bool_)]) / halflife) - observations = vals[mask.view(np.bool_)] - last_result = np.sum(weights * observations) / np.sum(weights) - - if num_not_nan >= minp: - output[i] = last_result - else: - output[i] = NaN + with nogil: + for i in range(N): + is_not_nan = vals[i] == vals[i] + num_not_nan += is_not_nan + if is_not_nan: + times_masked[num_not_nan-1] = times_float[i] + observations[num_not_nan-1] = vals[i] + + weights_sum = 0 + weights_dot = 0 + for j in range(num_not_nan): + weight = 0.5 ** ( + (times_float[i] - times_masked[j]) / halflife_float) + weights_sum += weight + weights_dot += weight * observations[j] + + last_result = weights_dot / weights_sum + + output[i] = last_result if num_not_nan >= minp else NaN return output
The performance changes for `rolling.EWMMethods` are not stable. I've seen those and no changes in separate runs. ``` + 1.35±0.02ms 2.17±0.5ms 1.61 rolling.EWMMethods.time_ewm('Series', 1000, 'float', 'std') ``` ``` - 2.58±0.2ms 1.36±0.01ms 0.53 rolling.EWMMethods.time_ewm('Series', 10, 'float', 'std') ``` ``` + 1.39±0.01ms 2.17±0.5ms 1.56 rolling.EWMMethods.time_ewm('DataFrame', 10, 'float', 'std') - 1.71±0.3ms 1.35±0.01ms 0.79 rolling.EWMMethods.time_ewm('Series', 10, 'float', 'std') ```
https://api.github.com/repos/pandas-dev/pandas/pulls/37389
2020-10-24T18:50:04Z
2020-11-04T02:57:03Z
2020-11-04T02:57:03Z
2022-11-18T02:21:02Z
TST: split up test_concat.py #37243 - more follows up
diff --git a/pandas/tests/reshape/concat/__init__.py b/pandas/tests/reshape/concat/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/pandas/tests/reshape/concat/conftest.py b/pandas/tests/reshape/concat/conftest.py new file mode 100644 index 0000000000000..62b8c59ba8855 --- /dev/null +++ b/pandas/tests/reshape/concat/conftest.py @@ -0,0 +1,7 @@ +import pytest + + +@pytest.fixture(params=[True, False]) +def sort(request): + """Boolean sort keyword for concat and DataFrame.append.""" + return request.param diff --git a/pandas/tests/reshape/concat/test_append.py b/pandas/tests/reshape/concat/test_append.py index 2f9228bc84394..ffeda703cd890 100644 --- a/pandas/tests/reshape/concat/test_append.py +++ b/pandas/tests/reshape/concat/test_append.py @@ -11,12 +11,6 @@ import pandas._testing as tm -@pytest.fixture(params=[True, False]) -def sort(request): - """Boolean sort keyword for concat and DataFrame.append.""" - return request.param - - class TestAppend: def test_append(self, sort, float_frame): mixed_frame = float_frame.copy() diff --git a/pandas/tests/reshape/concat/test_append_common.py b/pandas/tests/reshape/concat/test_append_common.py index 7ca3ae65706fe..395673e9a47ab 100644 --- a/pandas/tests/reshape/concat/test_append_common.py +++ b/pandas/tests/reshape/concat/test_append_common.py @@ -725,3 +725,26 @@ def test_concat_categorical_empty(self): tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) + + def test_categorical_concat_append(self): + cat = Categorical(["a", "b"], categories=["a", "b"]) + vals = [1, 2] + df = DataFrame({"cats": cat, "vals": vals}) + cat2 = Categorical(["a", "b", "a", "b"], categories=["a", "b"]) + vals2 = [1, 2, 1, 2] + exp = DataFrame({"cats": cat2, "vals": vals2}, index=Index([0, 1, 0, 1])) + + tm.assert_frame_equal(pd.concat([df, df]), exp) + tm.assert_frame_equal(df.append(df), exp) + + # GH 13524 can concat different categories + cat3 = Categorical(["a", "b"], categories=["a", "b", "c"]) + vals3 = [1, 2] + df_different_categories = DataFrame({"cats": cat3, "vals": vals3}) + + res = pd.concat([df, df_different_categories], ignore_index=True) + exp = DataFrame({"cats": list("abab"), "vals": [1, 2, 1, 2]}) + tm.assert_frame_equal(res, exp) + + res = df.append(df_different_categories, ignore_index=True) + tm.assert_frame_equal(res, exp) diff --git a/pandas/tests/reshape/concat/test_categorical.py b/pandas/tests/reshape/concat/test_categorical.py new file mode 100644 index 0000000000000..388575c5a3b86 --- /dev/null +++ b/pandas/tests/reshape/concat/test_categorical.py @@ -0,0 +1,195 @@ +import numpy as np +import pytest + +from pandas.core.dtypes.dtypes import CategoricalDtype + +import pandas as pd +from pandas import Categorical, DataFrame, Series +import pandas._testing as tm + + +class TestCategoricalConcat: + def test_categorical_concat(self, sort): + # See GH 10177 + df1 = DataFrame( + np.arange(18, dtype="int64").reshape(6, 3), columns=["a", "b", "c"] + ) + + df2 = DataFrame(np.arange(14, dtype="int64").reshape(7, 2), columns=["a", "c"]) + + cat_values = ["one", "one", "two", "one", "two", "two", "one"] + df2["h"] = Series(Categorical(cat_values)) + + res = pd.concat((df1, df2), axis=0, ignore_index=True, sort=sort) + exp = DataFrame( + { + "a": [0, 3, 6, 9, 12, 15, 0, 2, 4, 6, 8, 10, 12], + "b": [ + 1, + 4, + 7, + 10, + 13, + 16, + np.nan, + np.nan, + np.nan, + np.nan, + np.nan, + np.nan, + np.nan, + ], + "c": [2, 5, 8, 11, 14, 17, 1, 3, 5, 7, 9, 11, 13], + "h": [None] * 6 + cat_values, + } + ) + tm.assert_frame_equal(res, exp) + + def test_categorical_concat_dtypes(self): + + # GH8143 + index = ["cat", "obj", "num"] + cat = Categorical(["a", "b", "c"]) + obj = Series(["a", "b", "c"]) + num = Series([1, 2, 3]) + df = pd.concat([Series(cat), obj, num], axis=1, keys=index) + + result = df.dtypes == "object" + expected = Series([False, True, False], index=index) + tm.assert_series_equal(result, expected) + + result = df.dtypes == "int64" + expected = Series([False, False, True], index=index) + tm.assert_series_equal(result, expected) + + result = df.dtypes == "category" + expected = Series([True, False, False], index=index) + tm.assert_series_equal(result, expected) + + def test_concat_categoricalindex(self): + # GH 16111, categories that aren't lexsorted + categories = [9, 0, 1, 2, 3] + + a = Series(1, index=pd.CategoricalIndex([9, 0], categories=categories)) + b = Series(2, index=pd.CategoricalIndex([0, 1], categories=categories)) + c = Series(3, index=pd.CategoricalIndex([1, 2], categories=categories)) + + result = pd.concat([a, b, c], axis=1) + + exp_idx = pd.CategoricalIndex([9, 0, 1, 2], categories=categories) + exp = DataFrame( + { + 0: [1, 1, np.nan, np.nan], + 1: [np.nan, 2, 2, np.nan], + 2: [np.nan, np.nan, 3, 3], + }, + columns=[0, 1, 2], + index=exp_idx, + ) + tm.assert_frame_equal(result, exp) + + def test_categorical_concat_preserve(self): + + # GH 8641 series concat not preserving category dtype + # GH 13524 can concat different categories + s = Series(list("abc"), dtype="category") + s2 = Series(list("abd"), dtype="category") + + exp = Series(list("abcabd")) + res = pd.concat([s, s2], ignore_index=True) + tm.assert_series_equal(res, exp) + + exp = Series(list("abcabc"), dtype="category") + res = pd.concat([s, s], ignore_index=True) + tm.assert_series_equal(res, exp) + + exp = Series(list("abcabc"), index=[0, 1, 2, 0, 1, 2], dtype="category") + res = pd.concat([s, s]) + tm.assert_series_equal(res, exp) + + a = Series(np.arange(6, dtype="int64")) + b = Series(list("aabbca")) + + df2 = DataFrame({"A": a, "B": b.astype(CategoricalDtype(list("cab")))}) + res = pd.concat([df2, df2]) + exp = DataFrame( + { + "A": pd.concat([a, a]), + "B": pd.concat([b, b]).astype(CategoricalDtype(list("cab"))), + } + ) + tm.assert_frame_equal(res, exp) + + def test_categorical_index_preserver(self): + + a = Series(np.arange(6, dtype="int64")) + b = Series(list("aabbca")) + + df2 = DataFrame( + {"A": a, "B": b.astype(CategoricalDtype(list("cab")))} + ).set_index("B") + result = pd.concat([df2, df2]) + expected = DataFrame( + { + "A": pd.concat([a, a]), + "B": pd.concat([b, b]).astype(CategoricalDtype(list("cab"))), + } + ).set_index("B") + tm.assert_frame_equal(result, expected) + + # wrong categories + df3 = DataFrame( + {"A": a, "B": Categorical(b, categories=list("abe"))} + ).set_index("B") + msg = "categories must match existing categories when appending" + with pytest.raises(TypeError, match=msg): + pd.concat([df2, df3]) + + def test_concat_categorical_tz(self): + # GH-23816 + a = Series(pd.date_range("2017-01-01", periods=2, tz="US/Pacific")) + b = Series(["a", "b"], dtype="category") + result = pd.concat([a, b], ignore_index=True) + expected = Series( + [ + pd.Timestamp("2017-01-01", tz="US/Pacific"), + pd.Timestamp("2017-01-02", tz="US/Pacific"), + "a", + "b", + ] + ) + tm.assert_series_equal(result, expected) + + def test_concat_categorical_unchanged(self): + # GH-12007 + # test fix for when concat on categorical and float + # coerces dtype categorical -> float + df = DataFrame(Series(["a", "b", "c"], dtype="category", name="A")) + ser = Series([0, 1, 2], index=[0, 1, 3], name="B") + result = pd.concat([df, ser], axis=1) + expected = DataFrame( + { + "A": Series(["a", "b", "c", np.nan], dtype="category"), + "B": Series([0, 1, np.nan, 2], dtype="float"), + } + ) + tm.assert_equal(result, expected) + + def test_categorical_concat_gh7864(self): + # GH 7864 + # make sure ordering is preserved + df = DataFrame({"id": [1, 2, 3, 4, 5, 6], "raw_grade": list("abbaae")}) + df["grade"] = Categorical(df["raw_grade"]) + df["grade"].cat.set_categories(["e", "a", "b"]) + + df1 = df[0:3] + df2 = df[3:] + + tm.assert_index_equal(df["grade"].cat.categories, df1["grade"].cat.categories) + tm.assert_index_equal(df["grade"].cat.categories, df2["grade"].cat.categories) + + dfx = pd.concat([df1, df2]) + tm.assert_index_equal(df["grade"].cat.categories, dfx["grade"].cat.categories) + + dfa = df1.append(df2) + tm.assert_index_equal(df["grade"].cat.categories, dfa["grade"].cat.categories) diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py index c3e1f3177b3d3..90172abefb8c4 100644 --- a/pandas/tests/reshape/concat/test_concat.py +++ b/pandas/tests/reshape/concat/test_concat.py @@ -1,38 +1,18 @@ from collections import abc, deque from decimal import Decimal -from io import StringIO from warnings import catch_warnings import numpy as np -from numpy.random import randn import pytest -from pandas.core.dtypes.dtypes import CategoricalDtype - import pandas as pd -from pandas import ( - Categorical, - DataFrame, - DatetimeIndex, - Index, - MultiIndex, - Series, - concat, - date_range, - read_csv, -) +from pandas import DataFrame, Index, MultiIndex, Series, concat, date_range import pandas._testing as tm from pandas.core.arrays import SparseArray from pandas.core.construction import create_series_with_explicit_dtype from pandas.tests.extension.decimal import to_decimal -@pytest.fixture(params=[True, False]) -def sort(request): - """Boolean sort keyword for concat and DataFrame.append.""" - return request.param - - class TestConcatenate: def test_concat_copy(self): df = DataFrame(np.random.randn(4, 3)) @@ -116,39 +96,6 @@ def test_concat_keys_specific_levels(self): assert result.columns.names == ["group_key", None] - def test_concat_dataframe_keys_bug(self, sort): - t1 = DataFrame( - {"value": Series([1, 2, 3], index=Index(["a", "b", "c"], name="id"))} - ) - t2 = DataFrame({"value": Series([7, 8], index=Index(["a", "b"], name="id"))}) - - # it works - result = concat([t1, t2], axis=1, keys=["t1", "t2"], sort=sort) - assert list(result.columns) == [("t1", "value"), ("t2", "value")] - - def test_concat_series_partial_columns_names(self): - # GH10698 - foo = Series([1, 2], name="foo") - bar = Series([1, 2]) - baz = Series([4, 5]) - - result = concat([foo, bar, baz], axis=1) - expected = DataFrame( - {"foo": [1, 2], 0: [1, 2], 1: [4, 5]}, columns=["foo", 0, 1] - ) - tm.assert_frame_equal(result, expected) - - result = concat([foo, bar, baz], axis=1, keys=["red", "blue", "yellow"]) - expected = DataFrame( - {"red": [1, 2], "blue": [1, 2], "yellow": [4, 5]}, - columns=["red", "blue", "yellow"], - ) - tm.assert_frame_equal(result, expected) - - result = concat([foo, bar, baz], axis=1, ignore_index=True) - expected = DataFrame({0: [1, 2], 1: [1, 2], 2: [4, 5]}) - tm.assert_frame_equal(result, expected) - @pytest.mark.parametrize("mapping", ["mapping", "dict"]) def test_concat_mapping(self, mapping, non_dict_mapping_subclass): constructor = dict if mapping == "dict" else non_dict_mapping_subclass @@ -176,106 +123,6 @@ def test_concat_mapping(self, mapping, non_dict_mapping_subclass): expected = concat([frames[k] for k in keys], keys=keys) tm.assert_frame_equal(result, expected) - def test_concat_ignore_index(self, sort): - frame1 = DataFrame( - {"test1": ["a", "b", "c"], "test2": [1, 2, 3], "test3": [4.5, 3.2, 1.2]} - ) - frame2 = DataFrame({"test3": [5.2, 2.2, 4.3]}) - frame1.index = Index(["x", "y", "z"]) - frame2.index = Index(["x", "y", "q"]) - - v1 = concat([frame1, frame2], axis=1, ignore_index=True, sort=sort) - - nan = np.nan - expected = DataFrame( - [ - [nan, nan, nan, 4.3], - ["a", 1, 4.5, 5.2], - ["b", 2, 3.2, 2.2], - ["c", 3, 1.2, nan], - ], - index=Index(["q", "x", "y", "z"]), - ) - if not sort: - expected = expected.loc[["x", "y", "z", "q"]] - - tm.assert_frame_equal(v1, expected) - - @pytest.mark.parametrize( - "name_in1,name_in2,name_in3,name_out", - [ - ("idx", "idx", "idx", "idx"), - ("idx", "idx", None, None), - ("idx", None, None, None), - ("idx1", "idx2", None, None), - ("idx1", "idx1", "idx2", None), - ("idx1", "idx2", "idx3", None), - (None, None, None, None), - ], - ) - def test_concat_same_index_names(self, name_in1, name_in2, name_in3, name_out): - # GH13475 - indices = [ - Index(["a", "b", "c"], name=name_in1), - Index(["b", "c", "d"], name=name_in2), - Index(["c", "d", "e"], name=name_in3), - ] - frames = [ - DataFrame({c: [0, 1, 2]}, index=i) for i, c in zip(indices, ["x", "y", "z"]) - ] - result = pd.concat(frames, axis=1) - - exp_ind = Index(["a", "b", "c", "d", "e"], name=name_out) - expected = DataFrame( - { - "x": [0, 1, 2, np.nan, np.nan], - "y": [np.nan, 0, 1, 2, np.nan], - "z": [np.nan, np.nan, 0, 1, 2], - }, - index=exp_ind, - ) - - tm.assert_frame_equal(result, expected) - - def test_concat_multiindex_with_keys(self): - index = MultiIndex( - levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], - codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], - names=["first", "second"], - ) - frame = DataFrame( - np.random.randn(10, 3), - index=index, - columns=Index(["A", "B", "C"], name="exp"), - ) - result = concat([frame, frame], keys=[0, 1], names=["iteration"]) - - assert result.index.names == ("iteration",) + index.names - tm.assert_frame_equal(result.loc[0], frame) - tm.assert_frame_equal(result.loc[1], frame) - assert result.index.nlevels == 3 - - def test_concat_multiindex_with_none_in_index_names(self): - # GH 15787 - index = pd.MultiIndex.from_product([[1], range(5)], names=["level1", None]) - df = DataFrame({"col": range(5)}, index=index, dtype=np.int32) - - result = concat([df, df], keys=[1, 2], names=["level2"]) - index = pd.MultiIndex.from_product( - [[1, 2], [1], range(5)], names=["level2", "level1", None] - ) - expected = DataFrame({"col": list(range(5)) * 2}, index=index, dtype=np.int32) - tm.assert_frame_equal(result, expected) - - result = concat([df, df[:2]], keys=[1, 2], names=["level2"]) - level2 = [1] * 5 + [2] * 2 - level1 = [1] * 7 - no_name = list(range(5)) + list(range(2)) - tuples = list(zip(level2, level1, no_name)) - index = pd.MultiIndex.from_tuples(tuples, names=["level2", "level1", None]) - expected = DataFrame({"col": no_name}, index=index, dtype=np.int32) - tm.assert_frame_equal(result, expected) - def test_concat_keys_and_levels(self): df = DataFrame(np.random.randn(1, 3)) df2 = DataFrame(np.random.randn(1, 4)) @@ -330,28 +177,6 @@ def test_concat_keys_levels_no_overlap(self): with pytest.raises(ValueError, match=msg): concat([df, df2], keys=["one", "two"], levels=[["foo", "bar", "baz"]]) - def test_concat_rename_index(self): - a = DataFrame( - np.random.rand(3, 3), - columns=list("ABC"), - index=Index(list("abc"), name="index_a"), - ) - b = DataFrame( - np.random.rand(3, 3), - columns=list("ABC"), - index=Index(list("abc"), name="index_b"), - ) - - result = concat([a, b], keys=["key0", "key1"], names=["lvl0", "lvl1"]) - - exp = concat([a, b], keys=["key0", "key1"], names=["lvl0"]) - names = list(exp.index.names) - names[1] = "lvl1" - exp.index.set_names(names, inplace=True) - - tm.assert_frame_equal(result, exp) - assert result.index.names == exp.index.names - def test_crossed_dtypes_weird_corner(self): columns = ["A", "B", "C", "D"] df1 = DataFrame( @@ -385,53 +210,6 @@ def test_crossed_dtypes_weird_corner(self): result = concat([df, df2], keys=["one", "two"], names=["first", "second"]) assert result.index.names == ("first", "second") - def test_dups_index(self): - # GH 4771 - - # single dtypes - df = DataFrame( - np.random.randint(0, 10, size=40).reshape(10, 4), - columns=["A", "A", "C", "C"], - ) - - result = concat([df, df], axis=1) - tm.assert_frame_equal(result.iloc[:, :4], df) - tm.assert_frame_equal(result.iloc[:, 4:], df) - - result = concat([df, df], axis=0) - tm.assert_frame_equal(result.iloc[:10], df) - tm.assert_frame_equal(result.iloc[10:], df) - - # multi dtypes - df = concat( - [ - DataFrame(np.random.randn(10, 4), columns=["A", "A", "B", "B"]), - DataFrame( - np.random.randint(0, 10, size=20).reshape(10, 2), columns=["A", "C"] - ), - ], - axis=1, - ) - - result = concat([df, df], axis=1) - tm.assert_frame_equal(result.iloc[:, :6], df) - tm.assert_frame_equal(result.iloc[:, 6:], df) - - result = concat([df, df], axis=0) - tm.assert_frame_equal(result.iloc[:10], df) - tm.assert_frame_equal(result.iloc[10:], df) - - # append - result = df.iloc[0:8, :].append(df.iloc[8:]) - tm.assert_frame_equal(result, df) - - result = df.iloc[0:8, :].append(df.iloc[8:9]).append(df.iloc[9:10]) - tm.assert_frame_equal(result, df) - - expected = concat([df, df], axis=0) - result = df.append(df) - tm.assert_frame_equal(result, expected) - def test_with_mixed_tuples(self, sort): # 10697 # columns have mixed tuples, so handle properly @@ -441,38 +219,6 @@ def test_with_mixed_tuples(self, sort): # it works concat([df1, df2], sort=sort) - def test_handle_empty_objects(self, sort): - df = DataFrame(np.random.randn(10, 4), columns=list("abcd")) - - baz = df[:5].copy() - baz["foo"] = "bar" - empty = df[5:5] - - frames = [baz, empty, empty, df[5:]] - concatted = concat(frames, axis=0, sort=sort) - - expected = df.reindex(columns=["a", "b", "c", "d", "foo"]) - expected["foo"] = expected["foo"].astype("O") - expected.loc[0:4, "foo"] = "bar" - - tm.assert_frame_equal(concatted, expected) - - # empty as first element with time series - # GH3259 - df = DataFrame( - dict(A=range(10000)), index=date_range("20130101", periods=10000, freq="s") - ) - empty = DataFrame() - result = concat([df, empty], axis=1) - tm.assert_frame_equal(result, df) - result = concat([empty, df], axis=1) - tm.assert_frame_equal(result, df) - - result = concat([df, empty]) - tm.assert_frame_equal(result, df) - result = concat([empty, df]) - tm.assert_frame_equal(result, df) - def test_concat_mixed_objs(self): # concat mixed series/frames @@ -542,20 +288,6 @@ def test_concat_mixed_objs(self): result = concat([s1, df, s2], ignore_index=True) tm.assert_frame_equal(result, expected) - def test_empty_dtype_coerce(self): - - # xref to #12411 - # xref to #12045 - # xref to #11594 - # see below - - # 10571 - df1 = DataFrame(data=[[1, None], [2, None]], columns=["a", "b"]) - df2 = DataFrame(data=[[3, None], [4, None]], columns=["a", "b"]) - result = concat([df1, df2]) - expected = df1.dtypes - tm.assert_series_equal(result.dtypes, expected) - def test_dtype_coerceion(self): # 12411 @@ -578,76 +310,6 @@ def test_dtype_coerceion(self): result = concat([df.iloc[[0]], df.iloc[[1]]]) tm.assert_series_equal(result.dtypes, df.dtypes) - def test_concat_series(self): - - ts = tm.makeTimeSeries() - ts.name = "foo" - - pieces = [ts[:5], ts[5:15], ts[15:]] - - result = concat(pieces) - tm.assert_series_equal(result, ts) - assert result.name == ts.name - - result = concat(pieces, keys=[0, 1, 2]) - expected = ts.copy() - - ts.index = DatetimeIndex(np.array(ts.index.values, dtype="M8[ns]")) - - exp_codes = [np.repeat([0, 1, 2], [len(x) for x in pieces]), np.arange(len(ts))] - exp_index = MultiIndex(levels=[[0, 1, 2], ts.index], codes=exp_codes) - expected.index = exp_index - tm.assert_series_equal(result, expected) - - def test_concat_series_axis1(self, sort=sort): - ts = tm.makeTimeSeries() - - pieces = [ts[:-2], ts[2:], ts[2:-2]] - - result = concat(pieces, axis=1) - expected = DataFrame(pieces).T - tm.assert_frame_equal(result, expected) - - result = concat(pieces, keys=["A", "B", "C"], axis=1) - expected = DataFrame(pieces, index=["A", "B", "C"]).T - tm.assert_frame_equal(result, expected) - - # preserve series names, #2489 - s = Series(randn(5), name="A") - s2 = Series(randn(5), name="B") - - result = concat([s, s2], axis=1) - expected = DataFrame({"A": s, "B": s2}) - tm.assert_frame_equal(result, expected) - - s2.name = None - result = concat([s, s2], axis=1) - tm.assert_index_equal(result.columns, Index(["A", 0], dtype="object")) - - # must reindex, #2603 - s = Series(randn(3), index=["c", "a", "b"], name="A") - s2 = Series(randn(4), index=["d", "a", "b", "c"], name="B") - result = concat([s, s2], axis=1, sort=sort) - expected = DataFrame({"A": s, "B": s2}) - tm.assert_frame_equal(result, expected) - - def test_concat_series_axis1_names_applied(self): - # ensure names argument is not ignored on axis=1, #23490 - s = Series([1, 2, 3]) - s2 = Series([4, 5, 6]) - result = concat([s, s2], axis=1, keys=["a", "b"], names=["A"]) - expected = DataFrame( - [[1, 4], [2, 5], [3, 6]], columns=Index(["a", "b"], name="A") - ) - tm.assert_frame_equal(result, expected) - - result = concat([s, s2], axis=1, keys=[("a", 1), ("b", 2)], names=["A", "B"]) - expected = DataFrame( - [[1, 4], [2, 5], [3, 6]], - columns=MultiIndex.from_tuples([("a", 1), ("b", 2)], names=["A", "B"]), - ) - tm.assert_frame_equal(result, expected) - def test_concat_single_with_key(self): df = DataFrame(np.random.randn(10, 4)) @@ -664,17 +326,6 @@ def test_concat_exclude_none(self): with pytest.raises(ValueError, match="All objects passed were None"): concat([None, None]) - def test_concat_timedelta64_block(self): - from pandas import to_timedelta - - rng = to_timedelta(np.arange(10), unit="s") - - df = DataFrame({"time": rng}) - - result = concat([df, df]) - assert (result.iloc[:10]["time"] == rng).all() - assert (result.iloc[10:]["time"] == rng).all() - def test_concat_keys_with_none(self): # #1649 df0 = DataFrame([[10, 20, 30], [10, 20, 30], [10, 20, 30]]) @@ -736,26 +387,6 @@ def test_concat_bug_3602(self): result = concat([df1, df2], axis=1) tm.assert_frame_equal(result, expected) - def test_concat_inner_join_empty(self): - # GH 15328 - df_empty = DataFrame() - df_a = DataFrame({"a": [1, 2]}, index=[0, 1], dtype="int64") - df_expected = DataFrame({"a": []}, index=[], dtype="int64") - - for how, expected in [("inner", df_expected), ("outer", df_a)]: - result = pd.concat([df_a, df_empty], axis=1, join=how) - tm.assert_frame_equal(result, expected) - - def test_concat_series_axis1_same_names_ignore_index(self): - dates = date_range("01-Jan-2013", "01-Jan-2014", freq="MS")[0:-1] - s1 = Series(randn(len(dates)), index=dates, name="value") - s2 = Series(randn(len(dates)), index=dates, name="value") - - result = concat([s1, s2], axis=1, ignore_index=True) - expected = Index([0, 1]) - - tm.assert_index_equal(result.columns, expected) - def test_concat_iterables(self): # GH8645 check concat works with tuples, list, generators, and weird # stuff like deque and custom iterables @@ -788,342 +419,6 @@ def __iter__(self): tm.assert_frame_equal(pd.concat(CustomIterator2(), ignore_index=True), expected) - def test_concat_invalid(self): - - # trying to concat a ndframe with a non-ndframe - df1 = tm.makeCustomDataframe(10, 2) - for obj in [1, dict(), [1, 2], (1, 2)]: - - msg = ( - f"cannot concatenate object of type '{type(obj)}'; " - "only Series and DataFrame objs are valid" - ) - with pytest.raises(TypeError, match=msg): - concat([df1, obj]) - - def test_concat_invalid_first_argument(self): - df1 = tm.makeCustomDataframe(10, 2) - df2 = tm.makeCustomDataframe(10, 2) - msg = ( - "first argument must be an iterable of pandas " - 'objects, you passed an object of type "DataFrame"' - ) - with pytest.raises(TypeError, match=msg): - concat(df1, df2) - - # generator ok though - concat(DataFrame(np.random.rand(5, 5)) for _ in range(3)) - - # text reader ok - # GH6583 - data = """index,A,B,C,D -foo,2,3,4,5 -bar,7,8,9,10 -baz,12,13,14,15 -qux,12,13,14,15 -foo2,12,13,14,15 -bar2,12,13,14,15 -""" - - reader = read_csv(StringIO(data), chunksize=1) - result = concat(reader, ignore_index=True) - expected = read_csv(StringIO(data)) - tm.assert_frame_equal(result, expected) - - def test_concat_empty_series(self): - # GH 11082 - s1 = Series([1, 2, 3], name="x") - s2 = Series(name="y", dtype="float64") - res = pd.concat([s1, s2], axis=1) - exp = DataFrame( - {"x": [1, 2, 3], "y": [np.nan, np.nan, np.nan]}, - index=Index([0, 1, 2], dtype="O"), - ) - tm.assert_frame_equal(res, exp) - - s1 = Series([1, 2, 3], name="x") - s2 = Series(name="y", dtype="float64") - res = pd.concat([s1, s2], axis=0) - # name will be reset - exp = Series([1, 2, 3]) - tm.assert_series_equal(res, exp) - - # empty Series with no name - s1 = Series([1, 2, 3], name="x") - s2 = Series(name=None, dtype="float64") - res = pd.concat([s1, s2], axis=1) - exp = DataFrame( - {"x": [1, 2, 3], 0: [np.nan, np.nan, np.nan]}, - columns=["x", 0], - index=Index([0, 1, 2], dtype="O"), - ) - tm.assert_frame_equal(res, exp) - - @pytest.mark.parametrize("tz", [None, "UTC"]) - @pytest.mark.parametrize("values", [[], [1, 2, 3]]) - def test_concat_empty_series_timelike(self, tz, values): - # GH 18447 - - first = Series([], dtype="M8[ns]").dt.tz_localize(tz) - dtype = None if values else np.float64 - second = Series(values, dtype=dtype) - - expected = DataFrame( - { - 0: Series([pd.NaT] * len(values), dtype="M8[ns]").dt.tz_localize(tz), - 1: values, - } - ) - result = concat([first, second], axis=1) - tm.assert_frame_equal(result, expected) - - def test_default_index(self): - # is_series and ignore_index - s1 = Series([1, 2, 3], name="x") - s2 = Series([4, 5, 6], name="y") - res = pd.concat([s1, s2], axis=1, ignore_index=True) - assert isinstance(res.columns, pd.RangeIndex) - exp = DataFrame([[1, 4], [2, 5], [3, 6]]) - # use check_index_type=True to check the result have - # RangeIndex (default index) - tm.assert_frame_equal(res, exp, check_index_type=True, check_column_type=True) - - # is_series and all inputs have no names - s1 = Series([1, 2, 3]) - s2 = Series([4, 5, 6]) - res = pd.concat([s1, s2], axis=1, ignore_index=False) - assert isinstance(res.columns, pd.RangeIndex) - exp = DataFrame([[1, 4], [2, 5], [3, 6]]) - exp.columns = pd.RangeIndex(2) - tm.assert_frame_equal(res, exp, check_index_type=True, check_column_type=True) - - # is_dataframe and ignore_index - df1 = DataFrame({"A": [1, 2], "B": [5, 6]}) - df2 = DataFrame({"A": [3, 4], "B": [7, 8]}) - - res = pd.concat([df1, df2], axis=0, ignore_index=True) - exp = DataFrame([[1, 5], [2, 6], [3, 7], [4, 8]], columns=["A", "B"]) - tm.assert_frame_equal(res, exp, check_index_type=True, check_column_type=True) - - res = pd.concat([df1, df2], axis=1, ignore_index=True) - exp = DataFrame([[1, 5, 3, 7], [2, 6, 4, 8]]) - tm.assert_frame_equal(res, exp, check_index_type=True, check_column_type=True) - - def test_concat_multiindex_rangeindex(self): - # GH13542 - # when multi-index levels are RangeIndex objects - # there is a bug in concat with objects of len 1 - - df = DataFrame(np.random.randn(9, 2)) - df.index = MultiIndex( - levels=[pd.RangeIndex(3), pd.RangeIndex(3)], - codes=[np.repeat(np.arange(3), 3), np.tile(np.arange(3), 3)], - ) - - res = concat([df.iloc[[2, 3, 4], :], df.iloc[[5], :]]) - exp = df.iloc[[2, 3, 4, 5], :] - tm.assert_frame_equal(res, exp) - - def test_concat_multiindex_dfs_with_deepcopy(self): - # GH 9967 - from copy import deepcopy - - example_multiindex1 = pd.MultiIndex.from_product([["a"], ["b"]]) - example_dataframe1 = DataFrame([0], index=example_multiindex1) - - example_multiindex2 = pd.MultiIndex.from_product([["a"], ["c"]]) - example_dataframe2 = DataFrame([1], index=example_multiindex2) - - example_dict = {"s1": example_dataframe1, "s2": example_dataframe2} - expected_index = pd.MultiIndex( - levels=[["s1", "s2"], ["a"], ["b", "c"]], - codes=[[0, 1], [0, 0], [0, 1]], - names=["testname", None, None], - ) - expected = DataFrame([[0], [1]], index=expected_index) - result_copy = pd.concat(deepcopy(example_dict), names=["testname"]) - tm.assert_frame_equal(result_copy, expected) - result_no_copy = pd.concat(example_dict, names=["testname"]) - tm.assert_frame_equal(result_no_copy, expected) - - def test_categorical_concat_append(self): - cat = Categorical(["a", "b"], categories=["a", "b"]) - vals = [1, 2] - df = DataFrame({"cats": cat, "vals": vals}) - cat2 = Categorical(["a", "b", "a", "b"], categories=["a", "b"]) - vals2 = [1, 2, 1, 2] - exp = DataFrame({"cats": cat2, "vals": vals2}, index=Index([0, 1, 0, 1])) - - tm.assert_frame_equal(pd.concat([df, df]), exp) - tm.assert_frame_equal(df.append(df), exp) - - # GH 13524 can concat different categories - cat3 = Categorical(["a", "b"], categories=["a", "b", "c"]) - vals3 = [1, 2] - df_different_categories = DataFrame({"cats": cat3, "vals": vals3}) - - res = pd.concat([df, df_different_categories], ignore_index=True) - exp = DataFrame({"cats": list("abab"), "vals": [1, 2, 1, 2]}) - tm.assert_frame_equal(res, exp) - - res = df.append(df_different_categories, ignore_index=True) - tm.assert_frame_equal(res, exp) - - def test_categorical_concat_dtypes(self): - - # GH8143 - index = ["cat", "obj", "num"] - cat = Categorical(["a", "b", "c"]) - obj = Series(["a", "b", "c"]) - num = Series([1, 2, 3]) - df = pd.concat([Series(cat), obj, num], axis=1, keys=index) - - result = df.dtypes == "object" - expected = Series([False, True, False], index=index) - tm.assert_series_equal(result, expected) - - result = df.dtypes == "int64" - expected = Series([False, False, True], index=index) - tm.assert_series_equal(result, expected) - - result = df.dtypes == "category" - expected = Series([True, False, False], index=index) - tm.assert_series_equal(result, expected) - - def test_categorical_concat(self, sort): - # See GH 10177 - df1 = DataFrame( - np.arange(18, dtype="int64").reshape(6, 3), columns=["a", "b", "c"] - ) - - df2 = DataFrame(np.arange(14, dtype="int64").reshape(7, 2), columns=["a", "c"]) - - cat_values = ["one", "one", "two", "one", "two", "two", "one"] - df2["h"] = Series(Categorical(cat_values)) - - res = pd.concat((df1, df2), axis=0, ignore_index=True, sort=sort) - exp = DataFrame( - { - "a": [0, 3, 6, 9, 12, 15, 0, 2, 4, 6, 8, 10, 12], - "b": [ - 1, - 4, - 7, - 10, - 13, - 16, - np.nan, - np.nan, - np.nan, - np.nan, - np.nan, - np.nan, - np.nan, - ], - "c": [2, 5, 8, 11, 14, 17, 1, 3, 5, 7, 9, 11, 13], - "h": [None] * 6 + cat_values, - } - ) - tm.assert_frame_equal(res, exp) - - def test_categorical_concat_gh7864(self): - # GH 7864 - # make sure ordering is preserved - df = DataFrame({"id": [1, 2, 3, 4, 5, 6], "raw_grade": list("abbaae")}) - df["grade"] = Categorical(df["raw_grade"]) - df["grade"].cat.set_categories(["e", "a", "b"]) - - df1 = df[0:3] - df2 = df[3:] - - tm.assert_index_equal(df["grade"].cat.categories, df1["grade"].cat.categories) - tm.assert_index_equal(df["grade"].cat.categories, df2["grade"].cat.categories) - - dfx = pd.concat([df1, df2]) - tm.assert_index_equal(df["grade"].cat.categories, dfx["grade"].cat.categories) - - dfa = df1.append(df2) - tm.assert_index_equal(df["grade"].cat.categories, dfa["grade"].cat.categories) - - def test_categorical_concat_preserve(self): - - # GH 8641 series concat not preserving category dtype - # GH 13524 can concat different categories - s = Series(list("abc"), dtype="category") - s2 = Series(list("abd"), dtype="category") - - exp = Series(list("abcabd")) - res = pd.concat([s, s2], ignore_index=True) - tm.assert_series_equal(res, exp) - - exp = Series(list("abcabc"), dtype="category") - res = pd.concat([s, s], ignore_index=True) - tm.assert_series_equal(res, exp) - - exp = Series(list("abcabc"), index=[0, 1, 2, 0, 1, 2], dtype="category") - res = pd.concat([s, s]) - tm.assert_series_equal(res, exp) - - a = Series(np.arange(6, dtype="int64")) - b = Series(list("aabbca")) - - df2 = DataFrame({"A": a, "B": b.astype(CategoricalDtype(list("cab")))}) - res = pd.concat([df2, df2]) - exp = DataFrame( - { - "A": pd.concat([a, a]), - "B": pd.concat([b, b]).astype(CategoricalDtype(list("cab"))), - } - ) - tm.assert_frame_equal(res, exp) - - def test_categorical_index_preserver(self): - - a = Series(np.arange(6, dtype="int64")) - b = Series(list("aabbca")) - - df2 = DataFrame( - {"A": a, "B": b.astype(CategoricalDtype(list("cab")))} - ).set_index("B") - result = pd.concat([df2, df2]) - expected = DataFrame( - { - "A": pd.concat([a, a]), - "B": pd.concat([b, b]).astype(CategoricalDtype(list("cab"))), - } - ).set_index("B") - tm.assert_frame_equal(result, expected) - - # wrong categories - df3 = DataFrame( - {"A": a, "B": Categorical(b, categories=list("abe"))} - ).set_index("B") - msg = "categories must match existing categories when appending" - with pytest.raises(TypeError, match=msg): - pd.concat([df2, df3]) - - def test_concat_categoricalindex(self): - # GH 16111, categories that aren't lexsorted - categories = [9, 0, 1, 2, 3] - - a = Series(1, index=pd.CategoricalIndex([9, 0], categories=categories)) - b = Series(2, index=pd.CategoricalIndex([0, 1], categories=categories)) - c = Series(3, index=pd.CategoricalIndex([1, 2], categories=categories)) - - result = pd.concat([a, b, c], axis=1) - - exp_idx = pd.CategoricalIndex([9, 0, 1, 2], categories=categories) - exp = DataFrame( - { - 0: [1, 1, np.nan, np.nan], - 1: [np.nan, 2, 2, np.nan], - 2: [np.nan, np.nan, 3, 3], - }, - columns=[0, 1, 2], - index=exp_idx, - ) - tm.assert_frame_equal(result, exp) - def test_concat_order(self): # GH 17344 dfs = [DataFrame(index=range(3), columns=["a", 1, None])] @@ -1141,7 +436,7 @@ def test_concat_different_extension_dtypes_upcasts(self): expected = Series([1, 2, Decimal(1), Decimal(2)], dtype=object) tm.assert_series_equal(result, expected) - def test_concat_odered_dict(self): + def test_concat_ordered_dict(self): # GH 21510 expected = pd.concat( [Series(range(3)), Series(range(4))], keys=["First", "Another"] @@ -1151,22 +446,6 @@ def test_concat_odered_dict(self): ) tm.assert_series_equal(result, expected) - def test_concat_empty_dataframe_dtypes(self): - df = DataFrame(columns=list("abc")) - df["a"] = df["a"].astype(np.bool_) - df["b"] = df["b"].astype(np.int32) - df["c"] = df["c"].astype(np.float64) - - result = pd.concat([df, df]) - assert result["a"].dtype == np.bool_ - assert result["b"].dtype == np.int32 - assert result["c"].dtype == np.float64 - - result = pd.concat([df, df.astype(np.float64)]) - assert result["a"].dtype == np.object_ - assert result["b"].dtype == np.float64 - assert result["c"].dtype == np.float64 - @pytest.mark.parametrize("pdt", [Series, pd.DataFrame]) @pytest.mark.parametrize("dt", np.sctypes["float"]) @@ -1206,144 +485,6 @@ def test_concat_empty_and_non_empty_frame_regression(): tm.assert_frame_equal(result, expected) -def test_concat_empty_and_non_empty_series_regression(): - # GH 18187 regression test - s1 = Series([1]) - s2 = Series([], dtype=object) - - expected = s1 - result = pd.concat([s1, s2]) - tm.assert_series_equal(result, expected) - - -def test_concat_sorts_columns(sort): - # GH-4588 - df1 = DataFrame({"a": [1, 2], "b": [1, 2]}, columns=["b", "a"]) - df2 = DataFrame({"a": [3, 4], "c": [5, 6]}) - - # for sort=True/None - expected = DataFrame( - {"a": [1, 2, 3, 4], "b": [1, 2, None, None], "c": [None, None, 5, 6]}, - columns=["a", "b", "c"], - ) - - if sort is False: - expected = expected[["b", "a", "c"]] - - # default - with tm.assert_produces_warning(None): - result = pd.concat([df1, df2], ignore_index=True, sort=sort) - tm.assert_frame_equal(result, expected) - - -def test_concat_sorts_index(sort): - df1 = DataFrame({"a": [1, 2, 3]}, index=["c", "a", "b"]) - df2 = DataFrame({"b": [1, 2]}, index=["a", "b"]) - - # For True/None - expected = DataFrame( - {"a": [2, 3, 1], "b": [1, 2, None]}, index=["a", "b", "c"], columns=["a", "b"] - ) - if sort is False: - expected = expected.loc[["c", "a", "b"]] - - # Warn and sort by default - with tm.assert_produces_warning(None): - result = pd.concat([df1, df2], axis=1, sort=sort) - tm.assert_frame_equal(result, expected) - - -def test_concat_inner_sort(sort): - # https://github.com/pandas-dev/pandas/pull/20613 - df1 = DataFrame({"a": [1, 2], "b": [1, 2], "c": [1, 2]}, columns=["b", "a", "c"]) - df2 = DataFrame({"a": [1, 2], "b": [3, 4]}, index=[3, 4]) - - with tm.assert_produces_warning(None): - # unset sort should *not* warn for inner join - # since that never sorted - result = pd.concat([df1, df2], sort=sort, join="inner", ignore_index=True) - - expected = DataFrame({"b": [1, 2, 3, 4], "a": [1, 2, 1, 2]}, columns=["b", "a"]) - if sort is True: - expected = expected[["a", "b"]] - tm.assert_frame_equal(result, expected) - - -def test_concat_aligned_sort(): - # GH-4588 - df = DataFrame({"c": [1, 2], "b": [3, 4], "a": [5, 6]}, columns=["c", "b", "a"]) - result = pd.concat([df, df], sort=True, ignore_index=True) - expected = DataFrame( - {"a": [5, 6, 5, 6], "b": [3, 4, 3, 4], "c": [1, 2, 1, 2]}, - columns=["a", "b", "c"], - ) - tm.assert_frame_equal(result, expected) - - result = pd.concat([df, df[["c", "b"]]], join="inner", sort=True, ignore_index=True) - expected = expected[["b", "c"]] - tm.assert_frame_equal(result, expected) - - -def test_concat_aligned_sort_does_not_raise(): - # GH-4588 - # We catch TypeErrors from sorting internally and do not re-raise. - df = DataFrame({1: [1, 2], "a": [3, 4]}, columns=[1, "a"]) - expected = DataFrame({1: [1, 2, 1, 2], "a": [3, 4, 3, 4]}, columns=[1, "a"]) - result = pd.concat([df, df], ignore_index=True, sort=True) - tm.assert_frame_equal(result, expected) - - -@pytest.mark.parametrize("s1name,s2name", [(np.int64(190), (43, 0)), (190, (43, 0))]) -def test_concat_series_name_npscalar_tuple(s1name, s2name): - # GH21015 - s1 = Series({"a": 1, "b": 2}, name=s1name) - s2 = Series({"c": 5, "d": 6}, name=s2name) - result = pd.concat([s1, s2]) - expected = Series({"a": 1, "b": 2, "c": 5, "d": 6}) - tm.assert_series_equal(result, expected) - - -def test_concat_categorical_tz(): - # GH-23816 - a = Series(pd.date_range("2017-01-01", periods=2, tz="US/Pacific")) - b = Series(["a", "b"], dtype="category") - result = pd.concat([a, b], ignore_index=True) - expected = Series( - [ - pd.Timestamp("2017-01-01", tz="US/Pacific"), - pd.Timestamp("2017-01-02", tz="US/Pacific"), - "a", - "b", - ] - ) - tm.assert_series_equal(result, expected) - - -def test_concat_categorical_unchanged(): - # GH-12007 - # test fix for when concat on categorical and float - # coerces dtype categorical -> float - df = DataFrame(Series(["a", "b", "c"], dtype="category", name="A")) - ser = Series([0, 1, 2], index=[0, 1, 3], name="B") - result = pd.concat([df, ser], axis=1) - expected = DataFrame( - { - "A": Series(["a", "b", "c", np.nan], dtype="category"), - "B": Series([0, 1, np.nan, 2], dtype="float"), - } - ) - tm.assert_equal(result, expected) - - -def test_concat_empty_df_object_dtype(): - # GH 9149 - df_1 = DataFrame({"Row": [0, 1, 1], "EmptyCol": np.nan, "NumberCol": [1, 2, 3]}) - df_2 = DataFrame(columns=df_1.columns) - result = pd.concat([df_1, df_2], axis=0) - expected = df_1.astype(object) - tm.assert_frame_equal(result, expected) - - def test_concat_sparse(): # GH 23557 a = Series(SparseArray([0, 1, 2])) @@ -1365,20 +506,6 @@ def test_concat_dense_sparse(): tm.assert_series_equal(result, expected) -@pytest.mark.parametrize("test_series", [True, False]) -def test_concat_copy_index(test_series, axis): - # GH 29879 - if test_series: - ser = Series([1, 2]) - comb = concat([ser, ser], axis=axis, copy=True) - assert comb.index is not ser.index - else: - df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"]) - comb = concat([df, df], axis=axis, copy=True) - assert comb.index is not df.index - assert comb.columns is not df.columns - - @pytest.mark.parametrize("keys", [["e", "f", "f"], ["f", "e", "f"]]) def test_duplicate_keys(keys): # GH 33654 diff --git a/pandas/tests/reshape/concat/test_dataframe.py b/pandas/tests/reshape/concat/test_dataframe.py index 0e302f5e71fb4..295846ee1b264 100644 --- a/pandas/tests/reshape/concat/test_dataframe.py +++ b/pandas/tests/reshape/concat/test_dataframe.py @@ -2,7 +2,7 @@ import pytest import pandas as pd -from pandas import DataFrame, Index, Series +from pandas import DataFrame, Index, Series, concat import pandas._testing as tm @@ -157,3 +157,13 @@ def test_concat_astype_dup_col(self): np.array(["b", "b"]).reshape(1, 2), columns=["a", "a"] ).astype("category") tm.assert_frame_equal(result, expected) + + def test_concat_dataframe_keys_bug(self, sort): + t1 = DataFrame( + {"value": Series([1, 2, 3], index=Index(["a", "b", "c"], name="id"))} + ) + t2 = DataFrame({"value": Series([7, 8], index=Index(["a", "b"], name="id"))}) + + # it works + result = concat([t1, t2], axis=1, keys=["t1", "t2"], sort=sort) + assert list(result.columns) == [("t1", "value"), ("t2", "value")] diff --git a/pandas/tests/reshape/concat/test_datetimes.py b/pandas/tests/reshape/concat/test_datetimes.py index 0becb16beee08..8783f539faa65 100644 --- a/pandas/tests/reshape/concat/test_datetimes.py +++ b/pandas/tests/reshape/concat/test_datetimes.py @@ -15,16 +15,11 @@ Timestamp, concat, date_range, + to_timedelta, ) import pandas._testing as tm -@pytest.fixture(params=[True, False]) -def sort(request): - """Boolean sort keyword for concat and DataFrame.append.""" - return request.param - - class TestDatetimeConcat: def test_concat_datetime64_block(self): from pandas.core.indexes.datetimes import date_range @@ -518,3 +513,13 @@ def test_concat_period_other_series(self): result = concat([x, y], ignore_index=True) tm.assert_series_equal(result, expected) assert result.dtype == "object" + + +def test_concat_timedelta64_block(): + rng = to_timedelta(np.arange(10), unit="s") + + df = DataFrame({"time": rng}) + + result = concat([df, df]) + tm.assert_frame_equal(result.iloc[:10], df) + tm.assert_frame_equal(result.iloc[10:], df) diff --git a/pandas/tests/reshape/concat/test_empty.py b/pandas/tests/reshape/concat/test_empty.py new file mode 100644 index 0000000000000..5c540124de8e6 --- /dev/null +++ b/pandas/tests/reshape/concat/test_empty.py @@ -0,0 +1,251 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import DataFrame, Index, Series, concat, date_range +import pandas._testing as tm + + +class TestEmptyConcat: + def test_handle_empty_objects(self, sort): + df = DataFrame(np.random.randn(10, 4), columns=list("abcd")) + + baz = df[:5].copy() + baz["foo"] = "bar" + empty = df[5:5] + + frames = [baz, empty, empty, df[5:]] + concatted = concat(frames, axis=0, sort=sort) + + expected = df.reindex(columns=["a", "b", "c", "d", "foo"]) + expected["foo"] = expected["foo"].astype("O") + expected.loc[0:4, "foo"] = "bar" + + tm.assert_frame_equal(concatted, expected) + + # empty as first element with time series + # GH3259 + df = DataFrame( + dict(A=range(10000)), index=date_range("20130101", periods=10000, freq="s") + ) + empty = DataFrame() + result = concat([df, empty], axis=1) + tm.assert_frame_equal(result, df) + result = concat([empty, df], axis=1) + tm.assert_frame_equal(result, df) + + result = concat([df, empty]) + tm.assert_frame_equal(result, df) + result = concat([empty, df]) + tm.assert_frame_equal(result, df) + + def test_concat_empty_series(self): + # GH 11082 + s1 = Series([1, 2, 3], name="x") + s2 = Series(name="y", dtype="float64") + res = pd.concat([s1, s2], axis=1) + exp = DataFrame( + {"x": [1, 2, 3], "y": [np.nan, np.nan, np.nan]}, + index=Index([0, 1, 2], dtype="O"), + ) + tm.assert_frame_equal(res, exp) + + s1 = Series([1, 2, 3], name="x") + s2 = Series(name="y", dtype="float64") + res = pd.concat([s1, s2], axis=0) + # name will be reset + exp = Series([1, 2, 3]) + tm.assert_series_equal(res, exp) + + # empty Series with no name + s1 = Series([1, 2, 3], name="x") + s2 = Series(name=None, dtype="float64") + res = pd.concat([s1, s2], axis=1) + exp = DataFrame( + {"x": [1, 2, 3], 0: [np.nan, np.nan, np.nan]}, + columns=["x", 0], + index=Index([0, 1, 2], dtype="O"), + ) + tm.assert_frame_equal(res, exp) + + @pytest.mark.parametrize("tz", [None, "UTC"]) + @pytest.mark.parametrize("values", [[], [1, 2, 3]]) + def test_concat_empty_series_timelike(self, tz, values): + # GH 18447 + + first = Series([], dtype="M8[ns]").dt.tz_localize(tz) + dtype = None if values else np.float64 + second = Series(values, dtype=dtype) + + expected = DataFrame( + { + 0: Series([pd.NaT] * len(values), dtype="M8[ns]").dt.tz_localize(tz), + 1: values, + } + ) + result = concat([first, second], axis=1) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "left,right,expected", + [ + # booleans + (np.bool_, np.int32, np.int32), + (np.bool_, np.float32, np.object_), + # datetime-like + ("m8[ns]", np.bool_, np.object_), + ("m8[ns]", np.int64, np.object_), + ("M8[ns]", np.bool_, np.object_), + ("M8[ns]", np.int64, np.object_), + # categorical + ("category", "category", "category"), + ("category", "object", "object"), + ], + ) + def test_concat_empty_series_dtypes(self, left, right, expected): + result = pd.concat([Series(dtype=left), Series(dtype=right)]) + assert result.dtype == expected + + @pytest.mark.parametrize( + "dtype", ["float64", "int8", "uint8", "bool", "m8[ns]", "M8[ns]"] + ) + def test_concat_empty_series_dtypes_match_roundtrips(self, dtype): + dtype = np.dtype(dtype) + + result = pd.concat([Series(dtype=dtype)]) + assert result.dtype == dtype + + result = pd.concat([Series(dtype=dtype), Series(dtype=dtype)]) + assert result.dtype == dtype + + def test_concat_empty_series_dtypes_roundtrips(self): + + # round-tripping with self & like self + dtypes = map(np.dtype, ["float64", "int8", "uint8", "bool", "m8[ns]", "M8[ns]"]) + + def int_result_type(dtype, dtype2): + typs = {dtype.kind, dtype2.kind} + if not len(typs - {"i", "u", "b"}) and ( + dtype.kind == "i" or dtype2.kind == "i" + ): + return "i" + elif not len(typs - {"u", "b"}) and ( + dtype.kind == "u" or dtype2.kind == "u" + ): + return "u" + return None + + def float_result_type(dtype, dtype2): + typs = {dtype.kind, dtype2.kind} + if not len(typs - {"f", "i", "u"}) and ( + dtype.kind == "f" or dtype2.kind == "f" + ): + return "f" + return None + + def get_result_type(dtype, dtype2): + result = float_result_type(dtype, dtype2) + if result is not None: + return result + result = int_result_type(dtype, dtype2) + if result is not None: + return result + return "O" + + for dtype in dtypes: + for dtype2 in dtypes: + if dtype == dtype2: + continue + + expected = get_result_type(dtype, dtype2) + result = pd.concat([Series(dtype=dtype), Series(dtype=dtype2)]).dtype + assert result.kind == expected + + def test_concat_empty_series_dtypes_triple(self): + + assert ( + pd.concat( + [Series(dtype="M8[ns]"), Series(dtype=np.bool_), Series(dtype=np.int64)] + ).dtype + == np.object_ + ) + + def test_concat_empty_series_dtype_category_with_array(self): + # GH#18515 + assert ( + pd.concat( + [Series(np.array([]), dtype="category"), Series(dtype="float64")] + ).dtype + == "float64" + ) + + def test_concat_empty_series_dtypes_sparse(self): + result = pd.concat( + [ + Series(dtype="float64").astype("Sparse"), + Series(dtype="float64").astype("Sparse"), + ] + ) + assert result.dtype == "Sparse[float64]" + + result = pd.concat( + [Series(dtype="float64").astype("Sparse"), Series(dtype="float64")] + ) + # TODO: release-note: concat sparse dtype + expected = pd.SparseDtype(np.float64) + assert result.dtype == expected + + result = pd.concat( + [Series(dtype="float64").astype("Sparse"), Series(dtype="object")] + ) + # TODO: release-note: concat sparse dtype + expected = pd.SparseDtype("object") + assert result.dtype == expected + + def test_concat_empty_df_object_dtype(self): + # GH 9149 + df_1 = DataFrame({"Row": [0, 1, 1], "EmptyCol": np.nan, "NumberCol": [1, 2, 3]}) + df_2 = DataFrame(columns=df_1.columns) + result = pd.concat([df_1, df_2], axis=0) + expected = df_1.astype(object) + tm.assert_frame_equal(result, expected) + + def test_concat_empty_dataframe_dtypes(self): + df = DataFrame(columns=list("abc")) + df["a"] = df["a"].astype(np.bool_) + df["b"] = df["b"].astype(np.int32) + df["c"] = df["c"].astype(np.float64) + + result = pd.concat([df, df]) + assert result["a"].dtype == np.bool_ + assert result["b"].dtype == np.int32 + assert result["c"].dtype == np.float64 + + result = pd.concat([df, df.astype(np.float64)]) + assert result["a"].dtype == np.object_ + assert result["b"].dtype == np.float64 + assert result["c"].dtype == np.float64 + + def test_concat_inner_join_empty(self): + # GH 15328 + df_empty = DataFrame() + df_a = DataFrame({"a": [1, 2]}, index=[0, 1], dtype="int64") + df_expected = DataFrame({"a": []}, index=[], dtype="int64") + + for how, expected in [("inner", df_expected), ("outer", df_a)]: + result = pd.concat([df_a, df_empty], axis=1, join=how) + tm.assert_frame_equal(result, expected) + + def test_empty_dtype_coerce(self): + + # xref to #12411 + # xref to #12045 + # xref to #11594 + # see below + + # 10571 + df1 = DataFrame(data=[[1, None], [2, None]], columns=["a", "b"]) + df2 = DataFrame(data=[[3, None], [4, None]], columns=["a", "b"]) + result = concat([df1, df2]) + expected = df1.dtypes + tm.assert_series_equal(result.dtypes, expected) diff --git a/pandas/tests/reshape/concat/test_index.py b/pandas/tests/reshape/concat/test_index.py new file mode 100644 index 0000000000000..e283212b4e60c --- /dev/null +++ b/pandas/tests/reshape/concat/test_index.py @@ -0,0 +1,261 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import DataFrame, Index, MultiIndex, Series, concat +import pandas._testing as tm + + +class TestIndexConcat: + def test_concat_ignore_index(self, sort): + frame1 = DataFrame( + {"test1": ["a", "b", "c"], "test2": [1, 2, 3], "test3": [4.5, 3.2, 1.2]} + ) + frame2 = DataFrame({"test3": [5.2, 2.2, 4.3]}) + frame1.index = Index(["x", "y", "z"]) + frame2.index = Index(["x", "y", "q"]) + + v1 = concat([frame1, frame2], axis=1, ignore_index=True, sort=sort) + + nan = np.nan + expected = DataFrame( + [ + [nan, nan, nan, 4.3], + ["a", 1, 4.5, 5.2], + ["b", 2, 3.2, 2.2], + ["c", 3, 1.2, nan], + ], + index=Index(["q", "x", "y", "z"]), + ) + if not sort: + expected = expected.loc[["x", "y", "z", "q"]] + + tm.assert_frame_equal(v1, expected) + + @pytest.mark.parametrize( + "name_in1,name_in2,name_in3,name_out", + [ + ("idx", "idx", "idx", "idx"), + ("idx", "idx", None, None), + ("idx", None, None, None), + ("idx1", "idx2", None, None), + ("idx1", "idx1", "idx2", None), + ("idx1", "idx2", "idx3", None), + (None, None, None, None), + ], + ) + def test_concat_same_index_names(self, name_in1, name_in2, name_in3, name_out): + # GH13475 + indices = [ + Index(["a", "b", "c"], name=name_in1), + Index(["b", "c", "d"], name=name_in2), + Index(["c", "d", "e"], name=name_in3), + ] + frames = [ + DataFrame({c: [0, 1, 2]}, index=i) for i, c in zip(indices, ["x", "y", "z"]) + ] + result = pd.concat(frames, axis=1) + + exp_ind = Index(["a", "b", "c", "d", "e"], name=name_out) + expected = DataFrame( + { + "x": [0, 1, 2, np.nan, np.nan], + "y": [np.nan, 0, 1, 2, np.nan], + "z": [np.nan, np.nan, 0, 1, 2], + }, + index=exp_ind, + ) + + tm.assert_frame_equal(result, expected) + + def test_concat_rename_index(self): + a = DataFrame( + np.random.rand(3, 3), + columns=list("ABC"), + index=Index(list("abc"), name="index_a"), + ) + b = DataFrame( + np.random.rand(3, 3), + columns=list("ABC"), + index=Index(list("abc"), name="index_b"), + ) + + result = concat([a, b], keys=["key0", "key1"], names=["lvl0", "lvl1"]) + + exp = concat([a, b], keys=["key0", "key1"], names=["lvl0"]) + names = list(exp.index.names) + names[1] = "lvl1" + exp.index.set_names(names, inplace=True) + + tm.assert_frame_equal(result, exp) + assert result.index.names == exp.index.names + + @pytest.mark.parametrize("test_series", [True, False]) + def test_concat_copy_index(self, test_series, axis): + # GH 29879 + if test_series: + ser = Series([1, 2]) + comb = concat([ser, ser], axis=axis, copy=True) + assert comb.index is not ser.index + else: + df = DataFrame([[1, 2], [3, 4]], columns=["a", "b"]) + comb = concat([df, df], axis=axis, copy=True) + assert comb.index is not df.index + assert comb.columns is not df.columns + + def test_default_index(self): + # is_series and ignore_index + s1 = Series([1, 2, 3], name="x") + s2 = Series([4, 5, 6], name="y") + res = pd.concat([s1, s2], axis=1, ignore_index=True) + assert isinstance(res.columns, pd.RangeIndex) + exp = DataFrame([[1, 4], [2, 5], [3, 6]]) + # use check_index_type=True to check the result have + # RangeIndex (default index) + tm.assert_frame_equal(res, exp, check_index_type=True, check_column_type=True) + + # is_series and all inputs have no names + s1 = Series([1, 2, 3]) + s2 = Series([4, 5, 6]) + res = pd.concat([s1, s2], axis=1, ignore_index=False) + assert isinstance(res.columns, pd.RangeIndex) + exp = DataFrame([[1, 4], [2, 5], [3, 6]]) + exp.columns = pd.RangeIndex(2) + tm.assert_frame_equal(res, exp, check_index_type=True, check_column_type=True) + + # is_dataframe and ignore_index + df1 = DataFrame({"A": [1, 2], "B": [5, 6]}) + df2 = DataFrame({"A": [3, 4], "B": [7, 8]}) + + res = pd.concat([df1, df2], axis=0, ignore_index=True) + exp = DataFrame([[1, 5], [2, 6], [3, 7], [4, 8]], columns=["A", "B"]) + tm.assert_frame_equal(res, exp, check_index_type=True, check_column_type=True) + + res = pd.concat([df1, df2], axis=1, ignore_index=True) + exp = DataFrame([[1, 5, 3, 7], [2, 6, 4, 8]]) + tm.assert_frame_equal(res, exp, check_index_type=True, check_column_type=True) + + def test_dups_index(self): + # GH 4771 + + # single dtypes + df = DataFrame( + np.random.randint(0, 10, size=40).reshape(10, 4), + columns=["A", "A", "C", "C"], + ) + + result = concat([df, df], axis=1) + tm.assert_frame_equal(result.iloc[:, :4], df) + tm.assert_frame_equal(result.iloc[:, 4:], df) + + result = concat([df, df], axis=0) + tm.assert_frame_equal(result.iloc[:10], df) + tm.assert_frame_equal(result.iloc[10:], df) + + # multi dtypes + df = concat( + [ + DataFrame(np.random.randn(10, 4), columns=["A", "A", "B", "B"]), + DataFrame( + np.random.randint(0, 10, size=20).reshape(10, 2), columns=["A", "C"] + ), + ], + axis=1, + ) + + result = concat([df, df], axis=1) + tm.assert_frame_equal(result.iloc[:, :6], df) + tm.assert_frame_equal(result.iloc[:, 6:], df) + + result = concat([df, df], axis=0) + tm.assert_frame_equal(result.iloc[:10], df) + tm.assert_frame_equal(result.iloc[10:], df) + + # append + result = df.iloc[0:8, :].append(df.iloc[8:]) + tm.assert_frame_equal(result, df) + + result = df.iloc[0:8, :].append(df.iloc[8:9]).append(df.iloc[9:10]) + tm.assert_frame_equal(result, df) + + expected = concat([df, df], axis=0) + result = df.append(df) + tm.assert_frame_equal(result, expected) + + +class TestMultiIndexConcat: + def test_concat_multiindex_with_keys(self): + index = MultiIndex( + levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], + codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], + names=["first", "second"], + ) + frame = DataFrame( + np.random.randn(10, 3), + index=index, + columns=Index(["A", "B", "C"], name="exp"), + ) + result = concat([frame, frame], keys=[0, 1], names=["iteration"]) + + assert result.index.names == ("iteration",) + index.names + tm.assert_frame_equal(result.loc[0], frame) + tm.assert_frame_equal(result.loc[1], frame) + assert result.index.nlevels == 3 + + def test_concat_multiindex_with_none_in_index_names(self): + # GH 15787 + index = pd.MultiIndex.from_product([[1], range(5)], names=["level1", None]) + df = DataFrame({"col": range(5)}, index=index, dtype=np.int32) + + result = concat([df, df], keys=[1, 2], names=["level2"]) + index = pd.MultiIndex.from_product( + [[1, 2], [1], range(5)], names=["level2", "level1", None] + ) + expected = DataFrame({"col": list(range(5)) * 2}, index=index, dtype=np.int32) + tm.assert_frame_equal(result, expected) + + result = concat([df, df[:2]], keys=[1, 2], names=["level2"]) + level2 = [1] * 5 + [2] * 2 + level1 = [1] * 7 + no_name = list(range(5)) + list(range(2)) + tuples = list(zip(level2, level1, no_name)) + index = pd.MultiIndex.from_tuples(tuples, names=["level2", "level1", None]) + expected = DataFrame({"col": no_name}, index=index, dtype=np.int32) + tm.assert_frame_equal(result, expected) + + def test_concat_multiindex_rangeindex(self): + # GH13542 + # when multi-index levels are RangeIndex objects + # there is a bug in concat with objects of len 1 + + df = DataFrame(np.random.randn(9, 2)) + df.index = MultiIndex( + levels=[pd.RangeIndex(3), pd.RangeIndex(3)], + codes=[np.repeat(np.arange(3), 3), np.tile(np.arange(3), 3)], + ) + + res = concat([df.iloc[[2, 3, 4], :], df.iloc[[5], :]]) + exp = df.iloc[[2, 3, 4, 5], :] + tm.assert_frame_equal(res, exp) + + def test_concat_multiindex_dfs_with_deepcopy(self): + # GH 9967 + from copy import deepcopy + + example_multiindex1 = pd.MultiIndex.from_product([["a"], ["b"]]) + example_dataframe1 = DataFrame([0], index=example_multiindex1) + + example_multiindex2 = pd.MultiIndex.from_product([["a"], ["c"]]) + example_dataframe2 = DataFrame([1], index=example_multiindex2) + + example_dict = {"s1": example_dataframe1, "s2": example_dataframe2} + expected_index = pd.MultiIndex( + levels=[["s1", "s2"], ["a"], ["b", "c"]], + codes=[[0, 1], [0, 0], [0, 1]], + names=["testname", None, None], + ) + expected = DataFrame([[0], [1]], index=expected_index) + result_copy = pd.concat(deepcopy(example_dict), names=["testname"]) + tm.assert_frame_equal(result_copy, expected) + result_no_copy = pd.concat(example_dict, names=["testname"]) + tm.assert_frame_equal(result_no_copy, expected) diff --git a/pandas/tests/reshape/concat/test_invalid.py b/pandas/tests/reshape/concat/test_invalid.py new file mode 100644 index 0000000000000..3a886e0d612c6 --- /dev/null +++ b/pandas/tests/reshape/concat/test_invalid.py @@ -0,0 +1,51 @@ +from io import StringIO + +import numpy as np +import pytest + +from pandas import DataFrame, concat, read_csv +import pandas._testing as tm + + +class TestInvalidConcat: + def test_concat_invalid(self): + + # trying to concat a ndframe with a non-ndframe + df1 = tm.makeCustomDataframe(10, 2) + for obj in [1, dict(), [1, 2], (1, 2)]: + + msg = ( + f"cannot concatenate object of type '{type(obj)}'; " + "only Series and DataFrame objs are valid" + ) + with pytest.raises(TypeError, match=msg): + concat([df1, obj]) + + def test_concat_invalid_first_argument(self): + df1 = tm.makeCustomDataframe(10, 2) + df2 = tm.makeCustomDataframe(10, 2) + msg = ( + "first argument must be an iterable of pandas " + 'objects, you passed an object of type "DataFrame"' + ) + with pytest.raises(TypeError, match=msg): + concat(df1, df2) + + # generator ok though + concat(DataFrame(np.random.rand(5, 5)) for _ in range(3)) + + # text reader ok + # GH6583 + data = """index,A,B,C,D + foo,2,3,4,5 + bar,7,8,9,10 + baz,12,13,14,15 + qux,12,13,14,15 + foo2,12,13,14,15 + bar2,12,13,14,15 + """ + + reader = read_csv(StringIO(data), chunksize=1) + result = concat(reader, ignore_index=True) + expected = read_csv(StringIO(data)) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/reshape/concat/test_series.py b/pandas/tests/reshape/concat/test_series.py index 7f84e937736ac..aea2840bb897f 100644 --- a/pandas/tests/reshape/concat/test_series.py +++ b/pandas/tests/reshape/concat/test_series.py @@ -1,123 +1,146 @@ import numpy as np +from numpy.random import randn import pytest import pandas as pd -from pandas import Series +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + MultiIndex, + Series, + concat, + date_range, +) +import pandas._testing as tm + + +@pytest.fixture(params=[True, False]) +def sort(request): + """Boolean sort keyword for concat and DataFrame.append.""" + return request.param class TestSeriesConcat: - @pytest.mark.parametrize( - "dtype", ["float64", "int8", "uint8", "bool", "m8[ns]", "M8[ns]"] - ) - def test_concat_empty_series_dtypes_match_roundtrips(self, dtype): - dtype = np.dtype(dtype) - - result = pd.concat([Series(dtype=dtype)]) - assert result.dtype == dtype - - result = pd.concat([Series(dtype=dtype), Series(dtype=dtype)]) - assert result.dtype == dtype - - def test_concat_empty_series_dtypes_roundtrips(self): - - # round-tripping with self & like self - dtypes = map(np.dtype, ["float64", "int8", "uint8", "bool", "m8[ns]", "M8[ns]"]) - - def int_result_type(dtype, dtype2): - typs = {dtype.kind, dtype2.kind} - if not len(typs - {"i", "u", "b"}) and ( - dtype.kind == "i" or dtype2.kind == "i" - ): - return "i" - elif not len(typs - {"u", "b"}) and ( - dtype.kind == "u" or dtype2.kind == "u" - ): - return "u" - return None - - def float_result_type(dtype, dtype2): - typs = {dtype.kind, dtype2.kind} - if not len(typs - {"f", "i", "u"}) and ( - dtype.kind == "f" or dtype2.kind == "f" - ): - return "f" - return None - - def get_result_type(dtype, dtype2): - result = float_result_type(dtype, dtype2) - if result is not None: - return result - result = int_result_type(dtype, dtype2) - if result is not None: - return result - return "O" - - for dtype in dtypes: - for dtype2 in dtypes: - if dtype == dtype2: - continue - - expected = get_result_type(dtype, dtype2) - result = pd.concat([Series(dtype=dtype), Series(dtype=dtype2)]).dtype - assert result.kind == expected + def test_concat_series(self): - @pytest.mark.parametrize( - "left,right,expected", - [ - # booleans - (np.bool_, np.int32, np.int32), - (np.bool_, np.float32, np.object_), - # datetime-like - ("m8[ns]", np.bool_, np.object_), - ("m8[ns]", np.int64, np.object_), - ("M8[ns]", np.bool_, np.object_), - ("M8[ns]", np.int64, np.object_), - # categorical - ("category", "category", "category"), - ("category", "object", "object"), - ], - ) - def test_concat_empty_series_dtypes(self, left, right, expected): - result = pd.concat([Series(dtype=left), Series(dtype=right)]) - assert result.dtype == expected + ts = tm.makeTimeSeries() + ts.name = "foo" - def test_concat_empty_series_dtypes_triple(self): + pieces = [ts[:5], ts[5:15], ts[15:]] - assert ( - pd.concat( - [Series(dtype="M8[ns]"), Series(dtype=np.bool_), Series(dtype=np.int64)] - ).dtype - == np.object_ - ) + result = concat(pieces) + tm.assert_series_equal(result, ts) + assert result.name == ts.name + + result = concat(pieces, keys=[0, 1, 2]) + expected = ts.copy() + + ts.index = DatetimeIndex(np.array(ts.index.values, dtype="M8[ns]")) + + exp_codes = [np.repeat([0, 1, 2], [len(x) for x in pieces]), np.arange(len(ts))] + exp_index = MultiIndex(levels=[[0, 1, 2], ts.index], codes=exp_codes) + expected.index = exp_index + tm.assert_series_equal(result, expected) + + def test_concat_empty_and_non_empty_series_regression(self): + # GH 18187 regression test + s1 = Series([1]) + s2 = Series([], dtype=object) + + expected = s1 + result = pd.concat([s1, s2]) + tm.assert_series_equal(result, expected) + + def test_concat_series_axis1(self, sort=sort): + ts = tm.makeTimeSeries() - def test_concat_empty_series_dtype_category_with_array(self): - # GH#18515 - assert ( - pd.concat( - [Series(np.array([]), dtype="category"), Series(dtype="float64")] - ).dtype - == "float64" + pieces = [ts[:-2], ts[2:], ts[2:-2]] + + result = concat(pieces, axis=1) + expected = DataFrame(pieces).T + tm.assert_frame_equal(result, expected) + + result = concat(pieces, keys=["A", "B", "C"], axis=1) + expected = DataFrame(pieces, index=["A", "B", "C"]).T + tm.assert_frame_equal(result, expected) + + # preserve series names, #2489 + s = Series(randn(5), name="A") + s2 = Series(randn(5), name="B") + + result = concat([s, s2], axis=1) + expected = DataFrame({"A": s, "B": s2}) + tm.assert_frame_equal(result, expected) + + s2.name = None + result = concat([s, s2], axis=1) + tm.assert_index_equal(result.columns, Index(["A", 0], dtype="object")) + + # must reindex, #2603 + s = Series(randn(3), index=["c", "a", "b"], name="A") + s2 = Series(randn(4), index=["d", "a", "b", "c"], name="B") + result = concat([s, s2], axis=1, sort=sort) + expected = DataFrame({"A": s, "B": s2}) + tm.assert_frame_equal(result, expected) + + def test_concat_series_axis1_names_applied(self): + # ensure names argument is not ignored on axis=1, #23490 + s = Series([1, 2, 3]) + s2 = Series([4, 5, 6]) + result = concat([s, s2], axis=1, keys=["a", "b"], names=["A"]) + expected = DataFrame( + [[1, 4], [2, 5], [3, 6]], columns=Index(["a", "b"], name="A") ) + tm.assert_frame_equal(result, expected) - def test_concat_empty_series_dtypes_sparse(self): - result = pd.concat( - [ - Series(dtype="float64").astype("Sparse"), - Series(dtype="float64").astype("Sparse"), - ] + result = concat([s, s2], axis=1, keys=[("a", 1), ("b", 2)], names=["A", "B"]) + expected = DataFrame( + [[1, 4], [2, 5], [3, 6]], + columns=MultiIndex.from_tuples([("a", 1), ("b", 2)], names=["A", "B"]), ) - assert result.dtype == "Sparse[float64]" + tm.assert_frame_equal(result, expected) - result = pd.concat( - [Series(dtype="float64").astype("Sparse"), Series(dtype="float64")] + def test_concat_series_axis1_same_names_ignore_index(self): + dates = date_range("01-Jan-2013", "01-Jan-2014", freq="MS")[0:-1] + s1 = Series(randn(len(dates)), index=dates, name="value") + s2 = Series(randn(len(dates)), index=dates, name="value") + + result = concat([s1, s2], axis=1, ignore_index=True) + expected = Index([0, 1]) + + tm.assert_index_equal(result.columns, expected) + + @pytest.mark.parametrize( + "s1name,s2name", [(np.int64(190), (43, 0)), (190, (43, 0))] + ) + def test_concat_series_name_npscalar_tuple(self, s1name, s2name): + # GH21015 + s1 = Series({"a": 1, "b": 2}, name=s1name) + s2 = Series({"c": 5, "d": 6}, name=s2name) + result = pd.concat([s1, s2]) + expected = Series({"a": 1, "b": 2, "c": 5, "d": 6}) + tm.assert_series_equal(result, expected) + + def test_concat_series_partial_columns_names(self): + # GH10698 + foo = Series([1, 2], name="foo") + bar = Series([1, 2]) + baz = Series([4, 5]) + + result = concat([foo, bar, baz], axis=1) + expected = DataFrame( + {"foo": [1, 2], 0: [1, 2], 1: [4, 5]}, columns=["foo", 0, 1] ) - # TODO: release-note: concat sparse dtype - expected = pd.SparseDtype(np.float64) - assert result.dtype == expected + tm.assert_frame_equal(result, expected) - result = pd.concat( - [Series(dtype="float64").astype("Sparse"), Series(dtype="object")] + result = concat([foo, bar, baz], axis=1, keys=["red", "blue", "yellow"]) + expected = DataFrame( + {"red": [1, 2], "blue": [1, 2], "yellow": [4, 5]}, + columns=["red", "blue", "yellow"], ) - # TODO: release-note: concat sparse dtype - expected = pd.SparseDtype("object") - assert result.dtype == expected + tm.assert_frame_equal(result, expected) + + result = concat([foo, bar, baz], axis=1, ignore_index=True) + expected = DataFrame({0: [1, 2], 1: [1, 2], 2: [4, 5]}) + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/reshape/concat/test_sort.py b/pandas/tests/reshape/concat/test_sort.py new file mode 100644 index 0000000000000..865f696b7a73a --- /dev/null +++ b/pandas/tests/reshape/concat/test_sort.py @@ -0,0 +1,83 @@ +import pandas as pd +from pandas import DataFrame +import pandas._testing as tm + + +class TestConcatSort: + def test_concat_sorts_columns(self, sort): + # GH-4588 + df1 = DataFrame({"a": [1, 2], "b": [1, 2]}, columns=["b", "a"]) + df2 = DataFrame({"a": [3, 4], "c": [5, 6]}) + + # for sort=True/None + expected = DataFrame( + {"a": [1, 2, 3, 4], "b": [1, 2, None, None], "c": [None, None, 5, 6]}, + columns=["a", "b", "c"], + ) + + if sort is False: + expected = expected[["b", "a", "c"]] + + # default + with tm.assert_produces_warning(None): + result = pd.concat([df1, df2], ignore_index=True, sort=sort) + tm.assert_frame_equal(result, expected) + + def test_concat_sorts_index(self, sort): + df1 = DataFrame({"a": [1, 2, 3]}, index=["c", "a", "b"]) + df2 = DataFrame({"b": [1, 2]}, index=["a", "b"]) + + # For True/None + expected = DataFrame( + {"a": [2, 3, 1], "b": [1, 2, None]}, + index=["a", "b", "c"], + columns=["a", "b"], + ) + if sort is False: + expected = expected.loc[["c", "a", "b"]] + + # Warn and sort by default + with tm.assert_produces_warning(None): + result = pd.concat([df1, df2], axis=1, sort=sort) + tm.assert_frame_equal(result, expected) + + def test_concat_inner_sort(self, sort): + # https://github.com/pandas-dev/pandas/pull/20613 + df1 = DataFrame( + {"a": [1, 2], "b": [1, 2], "c": [1, 2]}, columns=["b", "a", "c"] + ) + df2 = DataFrame({"a": [1, 2], "b": [3, 4]}, index=[3, 4]) + + with tm.assert_produces_warning(None): + # unset sort should *not* warn for inner join + # since that never sorted + result = pd.concat([df1, df2], sort=sort, join="inner", ignore_index=True) + + expected = DataFrame({"b": [1, 2, 3, 4], "a": [1, 2, 1, 2]}, columns=["b", "a"]) + if sort is True: + expected = expected[["a", "b"]] + tm.assert_frame_equal(result, expected) + + def test_concat_aligned_sort(self): + # GH-4588 + df = DataFrame({"c": [1, 2], "b": [3, 4], "a": [5, 6]}, columns=["c", "b", "a"]) + result = pd.concat([df, df], sort=True, ignore_index=True) + expected = DataFrame( + {"a": [5, 6, 5, 6], "b": [3, 4, 3, 4], "c": [1, 2, 1, 2]}, + columns=["a", "b", "c"], + ) + tm.assert_frame_equal(result, expected) + + result = pd.concat( + [df, df[["c", "b"]]], join="inner", sort=True, ignore_index=True + ) + expected = expected[["b", "c"]] + tm.assert_frame_equal(result, expected) + + def test_concat_aligned_sort_does_not_raise(self): + # GH-4588 + # We catch TypeErrors from sorting internally and do not re-raise. + df = DataFrame({1: [1, 2], "a": [3, 4]}, columns=[1, "a"]) + expected = DataFrame({1: [1, 2, 1, 2], "a": [3, 4, 3, 4]}, columns=[1, "a"]) + result = pd.concat([df, df], ignore_index=True, sort=True) + tm.assert_frame_equal(result, expected)
* created test_categorical.py - [x] closes #37243 - [ ] tests added / passed - [x] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37387
2020-10-24T18:27:03Z
2020-10-28T12:04:17Z
2020-10-28T12:04:16Z
2020-10-28T12:31:53Z
DOC: Improve clarity and fix grammar
diff --git a/doc/source/user_guide/io.rst b/doc/source/user_guide/io.rst index 41c12fe63d047..1c271e74aafba 100644 --- a/doc/source/user_guide/io.rst +++ b/doc/source/user_guide/io.rst @@ -5686,7 +5686,7 @@ ignored. dtypes: float64(1), int64(1) memory usage: 15.3 MB -Given the next test set: +The following test functions will be used below to compare the performance of several IO methods: .. code-block:: python @@ -5791,7 +5791,7 @@ Given the next test set: def test_parquet_read(): pd.read_parquet("test.parquet") -When writing, the top-three functions in terms of speed are ``test_feather_write``, ``test_hdf_fixed_write`` and ``test_hdf_fixed_write_compress``. +When writing, the top three functions in terms of speed are ``test_feather_write``, ``test_hdf_fixed_write`` and ``test_hdf_fixed_write_compress``. .. code-block:: ipython @@ -5825,7 +5825,7 @@ When writing, the top-three functions in terms of speed are ``test_feather_write In [13]: %timeit test_parquet_write(df) 67.6 ms ± 706 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) -When reading, the top three are ``test_feather_read``, ``test_pickle_read`` and +When reading, the top three functions in terms of speed are ``test_feather_read``, ``test_pickle_read`` and ``test_hdf_fixed_read``. @@ -5862,8 +5862,7 @@ When reading, the top three are ``test_feather_read``, ``test_pickle_read`` and 24.4 ms ± 146 µs per loop (mean ± std. dev. of 7 runs, 10 loops each) -For this test case ``test.pkl.compress``, ``test.parquet`` and ``test.feather`` took the least space on disk. -Space on disk (in bytes) +The files ``test.pkl.compress``, ``test.parquet`` and ``test.feather`` took the least space on disk (in bytes). .. code-block:: none
- [ ] closes #xxxx - [ ] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry This PR improves the "Performance considerations" section of the IO tools user guide: https://pandas.pydata.org/pandas-docs/stable/user_guide/io.html#performance-considerations
https://api.github.com/repos/pandas-dev/pandas/pulls/37386
2020-10-24T17:38:39Z
2020-10-25T18:38:23Z
2020-10-25T18:38:23Z
2020-10-26T14:38:14Z
replace Appender decorator with doc
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 049d2c4888a69..e9634bc3aabd6 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -6032,7 +6032,8 @@ def __rdivmod__(self, other) -> Tuple[DataFrame, DataFrame]: # ---------------------------------------------------------------------- # Combination-Related - @Appender( + @doc( + _shared_docs["compare"], """ Returns ------- @@ -6062,11 +6063,11 @@ def __rdivmod__(self, other) -> Tuple[DataFrame, DataFrame]: Examples -------- >>> df = pd.DataFrame( -... { +... {{ ... "col1": ["a", "a", "b", "b", "a"], ... "col2": [1.0, 2.0, 3.0, np.nan, 5.0], ... "col3": [1.0, 2.0, 3.0, 4.0, 5.0] -... }, +... }}, ... columns=["col1", "col2", "col3"], ... ) >>> df @@ -6134,9 +6135,9 @@ def __rdivmod__(self, other) -> Tuple[DataFrame, DataFrame]: 2 b b 3.0 3.0 3.0 4.0 3 b b NaN NaN 4.0 4.0 4 a a 5.0 5.0 5.0 5.0 -""" +""", + klass=_shared_doc_kwargs["klass"], ) - @Appender(_shared_docs["compare"] % _shared_doc_kwargs) def compare( self, other: DataFrame, diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 36ce2c4776bd0..aebdba5ca0b40 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -8516,7 +8516,7 @@ def ranker(data): return ranker(data) - @Appender(_shared_docs["compare"] % _shared_doc_kwargs) + @doc(_shared_docs["compare"], klass=_shared_doc_kwargs["klass"]) def compare( self, other, diff --git a/pandas/core/series.py b/pandas/core/series.py index e4a805a18bcdb..f6928c2179397 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -2813,7 +2813,8 @@ def _construct_result( out.name = name return out - @Appender( + @doc( + generic._shared_docs["compare"], """ Returns ------- @@ -2873,9 +2874,9 @@ def _construct_result( 2 c c 3 d b 4 e e -""" +""", + klass=_shared_doc_kwargs["klass"], ) - @Appender(generic._shared_docs["compare"] % _shared_doc_kwargs) def compare( self, other: "Series", diff --git a/pandas/core/shared_docs.py b/pandas/core/shared_docs.py index c9940c78b8d7d..cc918c27b5c2e 100644 --- a/pandas/core/shared_docs.py +++ b/pandas/core/shared_docs.py @@ -47,16 +47,16 @@ _shared_docs[ "compare" ] = """ -Compare to another %(klass)s and show the differences. +Compare to another {klass} and show the differences. .. versionadded:: 1.1.0 Parameters ---------- -other : %(klass)s +other : {klass} Object to compare with. -align_axis : {0 or 'index', 1 or 'columns'}, default 1 +align_axis : {{0 or 'index', 1 or 'columns'}}, default 1 Determine which axis to align the comparison on. * 0, or 'index' : Resulting differences are stacked vertically
- [x] ref #31942 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] replaces Appender with doc for NDFrame.compare()
https://api.github.com/repos/pandas-dev/pandas/pulls/37384
2020-10-24T17:15:24Z
2020-11-11T01:26:37Z
2020-11-11T01:26:37Z
2020-11-11T01:26:46Z
CI fix failing codecheck
diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 25e6142476d65..ddca67306d804 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -1233,17 +1233,17 @@ def test_sum_timedelta64_skipna_false(): arr = np.arange(8).astype(np.int64).view("m8[s]").reshape(4, 2) arr[-1, -1] = "Nat" - df = pd.DataFrame(arr) + df = DataFrame(arr) result = df.sum(skipna=False) - expected = pd.Series([pd.Timedelta(seconds=12), pd.NaT]) + expected = Series([pd.Timedelta(seconds=12), pd.NaT]) tm.assert_series_equal(result, expected) result = df.sum(axis=0, skipna=False) tm.assert_series_equal(result, expected) result = df.sum(axis=1, skipna=False) - expected = pd.Series( + expected = Series( [ pd.Timedelta(seconds=1), pd.Timedelta(seconds=5),
https://api.github.com/repos/pandas-dev/pandas/pulls/37383
2020-10-24T16:05:58Z
2020-10-24T17:21:59Z
2020-10-24T17:21:59Z
2020-10-24T17:23:12Z
TST: Different tests were collected between gw0 and gw1
diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 4c670e56613ed..3869bf8f7ddcd 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -117,7 +117,7 @@ def _is_py3_complex_incompat(result, expected): return isinstance(expected, (complex, np.complexfloating)) and np.isnan(result) -_good_arith_ops = set(ARITH_OPS_SYMS).difference(SPECIAL_CASE_ARITH_OPS_SYMS) +_good_arith_ops = sorted(set(ARITH_OPS_SYMS).difference(SPECIAL_CASE_ARITH_OPS_SYMS)) # TODO: using range(5) here is a kludge diff --git a/pandas/tests/frame/apply/test_frame_transform.py b/pandas/tests/frame/apply/test_frame_transform.py index 1b259ddbd41dc..d141fa8682c10 100644 --- a/pandas/tests/frame/apply/test_frame_transform.py +++ b/pandas/tests/frame/apply/test_frame_transform.py @@ -20,7 +20,7 @@ def test_transform_ufunc(axis, float_frame): tm.assert_frame_equal(result, expected) -@pytest.mark.parametrize("op", transformation_kernels) +@pytest.mark.parametrize("op", sorted(transformation_kernels)) def test_transform_groupby_kernel(axis, float_frame, op): # GH 35964 if op == "cumcount": @@ -161,7 +161,7 @@ def test_transform_reducer_raises(all_reductions): # mypy doesn't allow adding lists of different types # https://github.com/python/mypy/issues/5492 -@pytest.mark.parametrize("op", [*transformation_kernels, lambda x: x + 1]) +@pytest.mark.parametrize("op", [*sorted(transformation_kernels), lambda x: x + 1]) def test_transform_bad_dtype(op): # GH 35964 df = DataFrame({"A": 3 * [object]}) # DataFrame that will fail on most transforms @@ -182,7 +182,7 @@ def test_transform_bad_dtype(op): df.transform({"A": [op]}) -@pytest.mark.parametrize("op", transformation_kernels) +@pytest.mark.parametrize("op", sorted(transformation_kernels)) def test_transform_partial_failure(op): # GH 35964 wont_fail = ["ffill", "bfill", "fillna", "pad", "backfill", "shift"] diff --git a/pandas/tests/series/apply/test_series_transform.py b/pandas/tests/series/apply/test_series_transform.py index 67b271f757cfb..ada27289e795d 100644 --- a/pandas/tests/series/apply/test_series_transform.py +++ b/pandas/tests/series/apply/test_series_transform.py @@ -18,7 +18,7 @@ def test_transform_ufunc(string_series): tm.assert_series_equal(result, expected) -@pytest.mark.parametrize("op", transformation_kernels) +@pytest.mark.parametrize("op", sorted(transformation_kernels)) def test_transform_groupby_kernel(string_series, op): # GH 35964 if op == "cumcount": @@ -144,7 +144,7 @@ def test_transform_reducer_raises(all_reductions): # mypy doesn't allow adding lists of different types # https://github.com/python/mypy/issues/5492 -@pytest.mark.parametrize("op", [*transformation_kernels, lambda x: x + 1]) +@pytest.mark.parametrize("op", [*sorted(transformation_kernels), lambda x: x + 1]) def test_transform_bad_dtype(op): # GH 35964 s = Series(3 * [object]) # Series that will fail on most transforms
not sure if anyone else if having issue running tests locally. have created a clean pandas-dev env on a different machine so maybe a transient thing. https://github.com/pytest-dev/pytest-xdist/issues/432 <details> ``` INSTALLED VERSIONS ------------------ commit : dce547ea2fe7f8c5c51c04d0a87704a2b4abf476 python : 3.8.6.final.0 python-bits : 64 OS : Windows OS-release : 10 Version : 10.0.18362 machine : AMD64 processor : Intel64 Family 6 Model 142 Stepping 12, GenuineIntel byteorder : little LC_ALL : None LANG : en_GB.UTF-8 LOCALE : English_United Kingdom.1252 pandas : 1.2.0.dev0+908.gdce547ea2f numpy : 1.19.2 pytz : 2020.1 dateutil : 2.8.1 pip : 20.2.4 setuptools : 49.6.0.post20201009 Cython : 0.29.21 pytest : 6.1.1 hypothesis : 5.37.4 sphinx : 3.2.1 blosc : None feather : None xlsxwriter : 1.3.7 lxml.etree : 4.6.1 html5lib : 1.1 pymysql : None psycopg2 : None jinja2 : 2.11.2 IPython : 7.18.1 pandas_datareader: None bs4 : 4.9.3 bottleneck : 1.3.2 fsspec : 0.8.4 fastparquet : 0.4.1 gcsfs : 0.7.1 matplotlib : 3.3.2 numexpr : 2.7.1 odfpy : None openpyxl : 3.0.5 pandas_gbq : None pyarrow : 2.0.0 pyxlsb : None s3fs : 0.4.2 scipy : 1.5.0 sqlalchemy : 1.3.20 tables : 3.6.1 tabulate : 0.8.7 xarray : 0.16.1 xlrd : 1.2.0 xlwt : 1.3.0 numba : 0.51.2 ``` </details>
https://api.github.com/repos/pandas-dev/pandas/pulls/37382
2020-10-24T15:58:59Z
2020-10-25T21:56:55Z
2020-10-25T21:56:55Z
2020-10-26T09:40:48Z
Fixed Metadata Propogation in DataFrame
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 7111d54d65815..669265dddd4ff 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -558,7 +558,7 @@ Other - Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` incorrectly raising ``AssertionError`` instead of ``ValueError`` when invalid parameter combinations are passed (:issue:`36045`) - Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` with numeric values and string ``to_replace`` (:issue:`34789`) - Fixed bug in metadata propagation incorrectly copying DataFrame columns as metadata when the column name overlaps with the metadata name (:issue:`37037`) -- Fixed metadata propagation in the :class:`Series.dt` and :class:`Series.str` accessors and :class:`DataFrame.duplicated` and :class:`DataFrame.stack` and :class:`DataFrame.unstack` and :class:`DataFrame.pivot` methods (:issue:`28283`) +- Fixed metadata propagation in the :class:`Series.dt`, :class:`Series.str` accessors, :class:`DataFrame.duplicated`, :class:`DataFrame.stack`, :class:`DataFrame.unstack`, :class:`DataFrame.pivot`, :class:`DataFrame.append`, :class:`DataFrame.diff`, :class:`DataFrame.applymap` and :class:`DataFrame.update` methods (:issue:`28283`) (:issue:`37381`) - Bug in :meth:`Index.union` behaving differently depending on whether operand is a :class:`Index` or other list-like (:issue:`36384`) - Passing an array with 2 or more dimensions to the :class:`Series` constructor now raises the more specific ``ValueError``, from a bare ``Exception`` previously (:issue:`35744`) - Bug in ``accessor.DirNamesMixin``, where ``dir(obj)`` wouldn't show attributes defined on the instance (:issue:`37173`). diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 24b89085ac121..09a014af60861 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -7401,7 +7401,7 @@ def diff(self, periods: int = 1, axis: Axis = 0) -> DataFrame: return self - self.shift(periods, axis=axis) new_data = self._mgr.diff(n=periods, axis=bm_axis) - return self._constructor(new_data) + return self._constructor(new_data).__finalize__(self, "diff") # ---------------------------------------------------------------------- # Function application @@ -7780,7 +7780,7 @@ def infer(x): return lib.map_infer(x, func, ignore_na=ignore_na) return lib.map_infer(x.astype(object)._values, func, ignore_na=ignore_na) - return self.apply(infer) + return self.apply(infer).__finalize__(self, "applymap") # ---------------------------------------------------------------------- # Merging / joining methods @@ -7917,12 +7917,14 @@ def append( to_concat = [self, *other] else: to_concat = [self, other] - return concat( - to_concat, - ignore_index=ignore_index, - verify_integrity=verify_integrity, - sort=sort, - ) + return ( + concat( + to_concat, + ignore_index=ignore_index, + verify_integrity=verify_integrity, + sort=sort, + ) + ).__finalize__(self, method="append") def join( self, other, on=None, how="left", lsuffix="", rsuffix="", sort=False diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 1219fefd7ea92..978597e3c7686 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -689,7 +689,7 @@ def get_result(self): self._maybe_restore_index_levels(result) - return result + return result.__finalize__(self, method="merge") def _indicator_pre_merge( self, left: "DataFrame", right: "DataFrame" @@ -1505,7 +1505,7 @@ def get_result(self): ) typ = self.left._constructor - result = typ(result_data).__finalize__(self, method=self._merge_type) + result = typ(result_data) self._maybe_add_join_keys(result, left_indexer, right_indexer) diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py index d7aadda990f53..46548a32cfeb7 100644 --- a/pandas/tests/generic/test_finalize.py +++ b/pandas/tests/generic/test_finalize.py @@ -178,20 +178,14 @@ marks=not_implemented_mark, ), pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("diff")), - marks=not_implemented_mark, - ), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("applymap", lambda x: x)), - marks=not_implemented_mark, + (pd.DataFrame, frame_data, operator.methodcaller("applymap", lambda x: x)) ), pytest.param( ( pd.DataFrame, frame_data, operator.methodcaller("append", pd.DataFrame({"A": [1]})), - ), - marks=not_implemented_mark, + ) ), pytest.param( ( @@ -199,7 +193,6 @@ frame_data, operator.methodcaller("append", pd.DataFrame({"B": [1]})), ), - marks=not_implemented_mark, ), pytest.param( (
In reference to #28283 Added finalize reference to append, merge, eval, diff, applymap, and update. Removed the ignore marks from the associated tests.
https://api.github.com/repos/pandas-dev/pandas/pulls/37381
2020-10-24T15:25:35Z
2020-11-04T16:52:45Z
2020-11-04T16:52:45Z
2021-06-06T19:22:15Z
TST: Update unreliable num precision component of test_binary_arith_ops (GH37328)
diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index a4f1b1828bbc6..728ffc6f85ba4 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -316,10 +316,13 @@ def check_alignment(self, result, nlhs, ghs, op): # TypeError, AttributeError: series or frame with scalar align pass else: - # direct numpy comparison expected = self.ne.evaluate(f"nlhs {op} ghs") - tm.assert_numpy_array_equal(result.values, expected) + # Update assert statement due to unreliable numerical + # precision component (GH37328) + # TODO: update testing code so that assert_almost_equal statement + # can be replaced again by the assert_numpy_array_equal statement + tm.assert_almost_equal(result.values, expected) # modulus, pow, and floor division require special casing
- [x] closes #37328 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37380
2020-10-24T14:11:12Z
2020-10-28T12:04:57Z
2020-10-28T12:04:56Z
2020-10-28T12:05:00Z
CI move validate unwanted patterns over to pre-commit
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index e7738fb9a2979..7e9a1ec890fba 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -99,6 +99,28 @@ repos: language: pygrep entry: (\.\. code-block ::|\.\. ipython ::) files: \.(py|pyx|rst)$ + - id: unwanted-patterns-strings-to-concatenate + name: Check for use of not concatenated strings + language: python + entry: ./scripts/validate_unwanted_patterns.py --validation-type="strings_to_concatenate" + files: \.(py|pyx|pxd|pxi)$ + - id: unwanted-patterns-strings-with-wrong-placed-whitespace + name: Check for strings with wrong placed spaces + language: python + entry: ./scripts/validate_unwanted_patterns.py --validation-type="strings_with_wrong_placed_whitespace" + files: \.(py|pyx|pxd|pxi)$ + - id: unwanted-patterns-private-import-across-module + name: Check for import of private attributes across modules + language: python + entry: ./scripts/validate_unwanted_patterns.py --validation-type="private_import_across_module" + types: [python] + exclude: ^(asv_bench|pandas/_vendored|pandas/tests|doc)/ + - id: unwanted-patterns-private-function-across-module + name: Check for use of private functions across modules + language: python + entry: ./scripts/validate_unwanted_patterns.py --validation-type="private_function_across_module" + types: [python] + exclude: ^(asv_bench|pandas/_vendored|pandas/tests|doc)/ - repo: https://github.com/asottile/yesqa rev: v1.2.2 hooks: diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 877e136492518..a9cce9357b531 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -73,38 +73,6 @@ if [[ -z "$CHECK" || "$CHECK" == "lint" ]]; then cpplint --quiet --extensions=c,h --headers=h --recursive --filter=-readability/casting,-runtime/int,-build/include_subdir pandas/_libs/src/*.h pandas/_libs/src/parser pandas/_libs/ujson pandas/_libs/tslibs/src/datetime pandas/_libs/*.cpp RET=$(($RET + $?)) ; echo $MSG "DONE" - MSG='Check for use of not concatenated strings' ; echo $MSG - if [[ "$GITHUB_ACTIONS" == "true" ]]; then - $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="strings_to_concatenate" --format="##[error]{source_path}:{line_number}:{msg}" . - else - $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="strings_to_concatenate" . - fi - RET=$(($RET + $?)) ; echo $MSG "DONE" - - MSG='Check for strings with wrong placed spaces' ; echo $MSG - if [[ "$GITHUB_ACTIONS" == "true" ]]; then - $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="strings_with_wrong_placed_whitespace" --format="##[error]{source_path}:{line_number}:{msg}" . - else - $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="strings_with_wrong_placed_whitespace" . - fi - RET=$(($RET + $?)) ; echo $MSG "DONE" - - MSG='Check for import of private attributes across modules' ; echo $MSG - if [[ "$GITHUB_ACTIONS" == "true" ]]; then - $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="private_import_across_module" --included-file-extensions="py" --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored --format="##[error]{source_path}:{line_number}:{msg}" pandas/ - else - $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="private_import_across_module" --included-file-extensions="py" --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored pandas/ - fi - RET=$(($RET + $?)) ; echo $MSG "DONE" - - MSG='Check for use of private functions across modules' ; echo $MSG - if [[ "$GITHUB_ACTIONS" == "true" ]]; then - $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="private_function_across_module" --included-file-extensions="py" --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored,doc/ --format="##[error]{source_path}:{line_number}:{msg}" pandas/ - else - $BASE_DIR/scripts/validate_unwanted_patterns.py --validation-type="private_function_across_module" --included-file-extensions="py" --excluded-file-paths=pandas/tests,asv_bench/,pandas/_vendored,doc/ pandas/ - fi - RET=$(($RET + $?)) ; echo $MSG "DONE" - fi ### PATTERNS ### diff --git a/scripts/validate_unwanted_patterns.py b/scripts/validate_unwanted_patterns.py index 119ae1cce2ff0..f824980a6d7e1 100755 --- a/scripts/validate_unwanted_patterns.py +++ b/scripts/validate_unwanted_patterns.py @@ -12,11 +12,10 @@ import argparse import ast -import os import sys import token import tokenize -from typing import IO, Callable, FrozenSet, Iterable, List, Set, Tuple +from typing import IO, Callable, Iterable, List, Set, Tuple PRIVATE_IMPORTS_TO_IGNORE: Set[str] = { "_extension_array_shared_docs", @@ -403,8 +402,6 @@ def main( function: Callable[[IO[str]], Iterable[Tuple[int, str]]], source_path: str, output_format: str, - file_extensions_to_check: str, - excluded_file_paths: str, ) -> bool: """ Main entry point of the script. @@ -432,19 +429,9 @@ def main( ValueError If the `source_path` is not pointing to existing file/directory. """ - if not os.path.exists(source_path): - raise ValueError("Please enter a valid path, pointing to a file/directory.") - is_failed: bool = False - file_path: str = "" - - FILE_EXTENSIONS_TO_CHECK: FrozenSet[str] = frozenset( - file_extensions_to_check.split(",") - ) - PATHS_TO_IGNORE = frozenset(excluded_file_paths.split(",")) - if os.path.isfile(source_path): - file_path = source_path + for file_path in source_path: with open(file_path) as file_obj: for line_number, msg in function(file_obj): is_failed = True @@ -454,25 +441,6 @@ def main( ) ) - for subdir, _, files in os.walk(source_path): - if any(path in subdir for path in PATHS_TO_IGNORE): - continue - for file_name in files: - if not any( - file_name.endswith(extension) for extension in FILE_EXTENSIONS_TO_CHECK - ): - continue - - file_path = os.path.join(subdir, file_name) - with open(file_path) as file_obj: - for line_number, msg in function(file_obj): - is_failed = True - print( - output_format.format( - source_path=file_path, line_number=line_number, msg=msg - ) - ) - return is_failed @@ -487,9 +455,7 @@ def main( parser = argparse.ArgumentParser(description="Unwanted patterns checker.") - parser.add_argument( - "path", nargs="?", default=".", help="Source path of file/directory to check." - ) + parser.add_argument("paths", nargs="*", help="Source paths of files to check.") parser.add_argument( "--format", "-f", @@ -503,25 +469,13 @@ def main( required=True, help="Validation test case to check.", ) - parser.add_argument( - "--included-file-extensions", - default="py,pyx,pxd,pxi", - help="Comma separated file extensions to check.", - ) - parser.add_argument( - "--excluded-file-paths", - default="asv_bench/env", - help="Comma separated file paths to exclude.", - ) args = parser.parse_args() sys.exit( main( function=globals().get(args.validation_type), # type: ignore - source_path=args.path, + source_path=args.paths, output_format=args.format, - file_extensions_to_check=args.included_file_extensions, - excluded_file_paths=args.excluded_file_paths, ) )
This becomes much simpler with pre-commit :smile: As with other PRs of this kind, the motivation for moving checks like these over to pre-commit is that they become cross-platform and that they provide faster feedback to devs ---- example: if I apply ```diff diff --git a/pandas/io/formats/info.py b/pandas/io/formats/info.py index 891b3ea7a..6c1075910 100644 --- a/pandas/io/formats/info.py +++ b/pandas/io/formats/info.py @@ -479,7 +479,7 @@ class DataFrameTableBuilder(TableBuilderAbstract): collected_dtypes = [ f"{key}({val:d})" for key, val in sorted(self.dtype_counts.items()) ] - self._lines.append(f"dtypes: {', '.join(collected_dtypes)}") + self._lines.append(" " f"dtypes: {', '.join(collected_dtypes)}") def add_memory_usage_line(self) -> None: """Add line containing memory usage.""" ``` then I get ```console $ pre-commit run unwanted-patterns-strings-to-concatenate --all Check for use of not concatenated strings................................Failed - hook id: unwanted-patterns-strings-to-concatenate - exit code: 1 pandas/io/formats/info.py:482:String unnecessarily split in two by black. Please merge them manually. ```
https://api.github.com/repos/pandas-dev/pandas/pulls/37379
2020-10-24T11:29:40Z
2020-10-26T12:07:18Z
2020-10-26T12:07:18Z
2020-10-26T12:51:10Z
TST: on_offset_implementations closes #34751
diff --git a/pandas/tests/tseries/offsets/test_offsets_properties.py b/pandas/tests/tseries/offsets/test_offsets_properties.py index 0fa9081d606b0..8d9b54cf3f0df 100644 --- a/pandas/tests/tseries/offsets/test_offsets_properties.py +++ b/pandas/tests/tseries/offsets/test_offsets_properties.py @@ -13,6 +13,7 @@ from hypothesis.extra.dateutil import timezones as dateutil_timezones from hypothesis.extra.pytz import timezones as pytz_timezones import pytest +import pytz import pandas as pd from pandas import Timestamp @@ -92,7 +93,13 @@ def test_on_offset_implementations(dt, offset): # check that the class-specific implementations of is_on_offset match # the general case definition: # (dt + offset) - offset == dt - compare = (dt + offset) - offset + try: + compare = (dt + offset) - offset + except pytz.NonExistentTimeError: + # dt + offset does not exist, assume(False) to indicate + # to hypothesis that this is not a valid test case + assume(False) + assert offset.is_on_offset(dt) == (compare == dt)
- [x] closes #34751 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37376
2020-10-24T01:11:58Z
2020-10-24T02:55:20Z
2020-10-24T02:55:20Z
2020-10-24T02:59:55Z
DEPR: Index.__and__, __or__, __xor__ behaving as set ops
diff --git a/doc/source/user_guide/indexing.rst b/doc/source/user_guide/indexing.rst index 2bc7e13e39ec4..4493ddd0b2822 100644 --- a/doc/source/user_guide/indexing.rst +++ b/doc/source/user_guide/indexing.rst @@ -1594,19 +1594,16 @@ See :ref:`Advanced Indexing <advanced>` for usage of MultiIndexes. Set operations on Index objects ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -The two main operations are ``union (|)`` and ``intersection (&)``. -These can be directly called as instance methods or used via overloaded -operators. Difference is provided via the ``.difference()`` method. +The two main operations are ``union`` and ``intersection``. +Difference is provided via the ``.difference()`` method. .. ipython:: python a = pd.Index(['c', 'b', 'a']) b = pd.Index(['c', 'e', 'd']) - a | b - a & b a.difference(b) -Also available is the ``symmetric_difference (^)`` operation, which returns elements +Also available is the ``symmetric_difference`` operation, which returns elements that appear in either ``idx1`` or ``idx2``, but not in both. This is equivalent to the Index created by ``idx1.difference(idx2).union(idx2.difference(idx1))``, with duplicates dropped. @@ -1616,7 +1613,6 @@ with duplicates dropped. idx1 = pd.Index([1, 2, 3, 4]) idx2 = pd.Index([2, 3, 4, 5]) idx1.symmetric_difference(idx2) - idx1 ^ idx2 .. note:: @@ -1631,7 +1627,7 @@ integer values are converted to float idx1 = pd.Index([0, 1, 2]) idx2 = pd.Index([0.5, 1.5]) - idx1 | idx2 + idx1.union(idx2) .. _indexing.missing: diff --git a/doc/source/user_guide/missing_data.rst b/doc/source/user_guide/missing_data.rst index e6d06aa6bd1a0..1621b37f31b23 100644 --- a/doc/source/user_guide/missing_data.rst +++ b/doc/source/user_guide/missing_data.rst @@ -466,7 +466,7 @@ at the new values. ser = pd.Series(np.sort(np.random.uniform(size=100))) # interpolate at new_index - new_index = ser.index | pd.Index([49.25, 49.5, 49.75, 50.25, 50.5, 50.75]) + new_index = ser.index.union(pd.Index([49.25, 49.5, 49.75, 50.25, 50.5, 50.75])) interp_s = ser.reindex(new_index).interpolate(method="pchip") interp_s[49:51] diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 84f594acf5e4c..aaa39e26f4359 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -338,6 +338,7 @@ Deprecations - Deprecated slice-indexing on timezone-aware :class:`DatetimeIndex` with naive ``datetime`` objects, to match scalar indexing behavior (:issue:`36148`) - :meth:`Index.ravel` returning a ``np.ndarray`` is deprecated, in the future this will return a view on the same index (:issue:`19956`) - Deprecate use of strings denoting units with 'M', 'Y' or 'y' in :func:`~pandas.to_timedelta` (:issue:`36666`) +- :class:`Index` methods ``&``, ``|``, and ``^`` behaving as the set operations :meth:`Index.intersection`, :meth:`Index.union`, and :meth:`Index.symmetric_difference`, respectively, are deprecated and in the future will behave as pointwise boolean operations matching :class:`Series` behavior. Use the named set methods instead (:issue:`36758`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 1938722225b98..e4b2bcb3e7a48 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2512,14 +2512,35 @@ def __iadd__(self, other): @final def __and__(self, other): + warnings.warn( + "Index.__and__ operating as a set operation is deprecated, " + "in the future this will be a logical operation matching " + "Series.__and__. Use index.intersection(other) instead", + FutureWarning, + stacklevel=2, + ) return self.intersection(other) @final def __or__(self, other): + warnings.warn( + "Index.__or__ operating as a set operation is deprecated, " + "in the future this will be a logical operation matching " + "Series.__or__. Use index.union(other) instead", + FutureWarning, + stacklevel=2, + ) return self.union(other) @final def __xor__(self, other): + warnings.warn( + "Index.__xor__ operating as a set operation is deprecated, " + "in the future this will be a logical operation matching " + "Series.__xor__. Use index.symmetric_difference(other) instead", + FutureWarning, + stacklevel=2, + ) return self.symmetric_difference(other) @final diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index bdd3afe747d1d..29a489866d111 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -3139,12 +3139,12 @@ def _convert_to_indexer(r) -> Int64Index: r = r.nonzero()[0] return Int64Index(r) - def _update_indexer(idxr, indexer=indexer): + def _update_indexer(idxr: Optional[Index], indexer: Optional[Index]) -> Index: if indexer is None: indexer = Index(np.arange(n)) if idxr is None: return indexer - return indexer & idxr + return indexer.intersection(idxr) for i, k in enumerate(seq): @@ -3162,7 +3162,9 @@ def _update_indexer(idxr, indexer=indexer): idxrs = _convert_to_indexer( self._get_level_indexer(x, level=i, indexer=indexer) ) - indexers = idxrs if indexers is None else indexers | idxrs + indexers = (idxrs if indexers is None else indexers).union( + idxrs + ) except KeyError: # ignore not founds diff --git a/pandas/core/series.py b/pandas/core/series.py index 19d07a8c5e6bf..e4a805a18bcdb 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -725,7 +725,7 @@ def __array_ufunc__( # it to handle *args. index = alignable[0].index for s in alignable[1:]: - index |= s.index + index = index.union(s.index) inputs = tuple( x.reindex(index) if issubclass(t, Series) else x for x, t in zip(inputs, types) diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 4cd19800d4e26..5013365896fb2 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -475,10 +475,10 @@ def __init__( if cols is not None: # all missing, raise - if not len(Index(cols) & df.columns): + if not len(Index(cols).intersection(df.columns)): raise KeyError("passes columns are not ALL present dataframe") - if len(Index(cols) & df.columns) != len(cols): + if len(Index(cols).intersection(df.columns)) != len(cols): # Deprecated in GH#17295, enforced in 1.0.0 raise KeyError("Not all names specified in 'columns' are found") diff --git a/pandas/io/json/_json.py b/pandas/io/json/_json.py index 288bc0adc5162..98b9a585d890e 100644 --- a/pandas/io/json/_json.py +++ b/pandas/io/json/_json.py @@ -268,7 +268,7 @@ def __init__( if ( (obj.ndim == 1) and (obj.name in set(obj.index.names)) - or len(obj.columns & obj.index.names) + or len(obj.columns.intersection(obj.index.names)) ): msg = "Overlapping names between the index and columns" raise ValueError(msg) diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py index 93c92c0b8f1ab..3dbfd8b64cbba 100644 --- a/pandas/tests/indexes/datetimes/test_setops.py +++ b/pandas/tests/indexes/datetimes/test_setops.py @@ -300,7 +300,8 @@ def test_intersection_bug_1708(self): index_1 = date_range("1/1/2012", periods=4, freq="12H") index_2 = index_1 + DateOffset(hours=1) - result = index_1 & index_2 + with tm.assert_produces_warning(FutureWarning): + result = index_1 & index_2 assert len(result) == 0 @pytest.mark.parametrize("tz", tz) diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py index 0b17c1c4c9679..4ac9a27069a3f 100644 --- a/pandas/tests/indexes/multi/test_setops.py +++ b/pandas/tests/indexes/multi/test_setops.py @@ -105,11 +105,13 @@ def test_symmetric_difference(idx, sort): def test_multiindex_symmetric_difference(): # GH 13490 idx = MultiIndex.from_product([["a", "b"], ["A", "B"]], names=["a", "b"]) - result = idx ^ idx + with tm.assert_produces_warning(FutureWarning): + result = idx ^ idx assert result.names == idx.names idx2 = idx.copy().rename(["A", "B"]) - result = idx ^ idx2 + with tm.assert_produces_warning(FutureWarning): + result = idx ^ idx2 assert result.names == [None, None] diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index f37c3dff1e338..3750df4b65066 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -1008,7 +1008,8 @@ def test_symmetric_difference(self, sort): tm.assert_index_equal(result, expected) # __xor__ syntax - expected = index1 ^ index2 + with tm.assert_produces_warning(FutureWarning): + expected = index1 ^ index2 assert tm.equalContents(result, expected) assert result.name is None diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py index 1a40fe550be61..7b886a9353322 100644 --- a/pandas/tests/indexes/test_setops.py +++ b/pandas/tests/indexes/test_setops.py @@ -93,5 +93,18 @@ def test_union_dtypes(left, right, expected): right = pandas_dtype(right) a = pd.Index([], dtype=left) b = pd.Index([], dtype=right) - result = (a | b).dtype + result = a.union(b).dtype assert result == expected + + +def test_dunder_inplace_setops_deprecated(index): + # GH#37374 these will become logical ops, not setops + + with tm.assert_produces_warning(FutureWarning): + index |= index + + with tm.assert_produces_warning(FutureWarning): + index &= index + + with tm.assert_produces_warning(FutureWarning): + index ^= index diff --git a/pandas/tests/indexes/timedeltas/test_setops.py b/pandas/tests/indexes/timedeltas/test_setops.py index 16ac70d9f23f2..94fdfefa497a3 100644 --- a/pandas/tests/indexes/timedeltas/test_setops.py +++ b/pandas/tests/indexes/timedeltas/test_setops.py @@ -97,13 +97,15 @@ def test_intersection_bug_1708(self): index_1 = timedelta_range("1 day", periods=4, freq="h") index_2 = index_1 + pd.offsets.Hour(5) - result = index_1 & index_2 + with tm.assert_produces_warning(FutureWarning): + result = index_1 & index_2 assert len(result) == 0 index_1 = timedelta_range("1 day", periods=4, freq="h") index_2 = index_1 + pd.offsets.Hour(1) - result = index_1 & index_2 + with tm.assert_produces_warning(FutureWarning): + result = index_1 & index_2 expected = timedelta_range("1 day 01:00:00", periods=3, freq="h") tm.assert_index_equal(result, expected) assert result.freq == expected.freq diff --git a/pandas/tests/resample/test_datetime_index.py b/pandas/tests/resample/test_datetime_index.py index 7681807b60989..d3d33d6fe847e 100644 --- a/pandas/tests/resample/test_datetime_index.py +++ b/pandas/tests/resample/test_datetime_index.py @@ -1112,9 +1112,9 @@ def test_resample_anchored_multiday(): # # See: https://github.com/pandas-dev/pandas/issues/8683 - index = pd.date_range( - "2014-10-14 23:06:23.206", periods=3, freq="400L" - ) | pd.date_range("2014-10-15 23:00:00", periods=2, freq="2200L") + index1 = pd.date_range("2014-10-14 23:06:23.206", periods=3, freq="400L") + index2 = pd.date_range("2014-10-15 23:00:00", periods=2, freq="2200L") + index = index1.union(index2) s = Series(np.random.randn(5), index=index) diff --git a/pandas/tests/series/test_logical_ops.py b/pandas/tests/series/test_logical_ops.py index 3d53e7ac26338..7cfda2464f21a 100644 --- a/pandas/tests/series/test_logical_ops.py +++ b/pandas/tests/series/test_logical_ops.py @@ -269,11 +269,13 @@ def test_reversed_xor_with_index_returns_index(self): idx2 = Index([1, 0, 1, 0]) expected = Index.symmetric_difference(idx1, ser) - result = idx1 ^ ser + with tm.assert_produces_warning(FutureWarning): + result = idx1 ^ ser tm.assert_index_equal(result, expected) expected = Index.symmetric_difference(idx2, ser) - result = idx2 ^ ser + with tm.assert_produces_warning(FutureWarning): + result = idx2 ^ ser tm.assert_index_equal(result, expected) @pytest.mark.parametrize( @@ -304,11 +306,13 @@ def test_reversed_logical_op_with_index_returns_series(self, op): idx2 = Index([1, 0, 1, 0]) expected = Series(op(idx1.values, ser.values)) - result = op(ser, idx1) + with tm.assert_produces_warning(FutureWarning): + result = op(ser, idx1) tm.assert_series_equal(result, expected) expected = Series(op(idx2.values, ser.values)) - result = op(ser, idx2) + with tm.assert_produces_warning(FutureWarning): + result = op(ser, idx2) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( @@ -324,7 +328,9 @@ def test_reverse_ops_with_index(self, op, expected): # multi-set Index ops are buggy, so let's avoid duplicates... ser = Series([True, False]) idx = Index([False, True]) - result = op(ser, idx) + with tm.assert_produces_warning(FutureWarning, check_stacklevel=False): + # behaving as set ops is deprecated, will become logical ops + result = op(ser, idx) tm.assert_index_equal(result, expected) def test_logical_ops_label_based(self): diff --git a/pandas/tests/test_strings.py b/pandas/tests/test_strings.py index f52d0d0fccab8..538a52d84b73a 100644 --- a/pandas/tests/test_strings.py +++ b/pandas/tests/test_strings.py @@ -645,7 +645,9 @@ def test_str_cat_align_mixed_inputs(self, join): u = np.array(["A", "B", "C", "D"]) expected_outer = Series(["aaA", "bbB", "c-C", "ddD", "-e-"]) # joint index of rhs [t, u]; u will be forced have index of s - rhs_idx = t.index & s.index if join == "inner" else t.index | s.index + rhs_idx = ( + t.index.intersection(s.index) if join == "inner" else t.index.union(s.index) + ) expected = expected_outer.loc[s.index.join(rhs_idx, how=join)] result = s.str.cat([t, u], join=join, na_rep="-")
- [x] closes #36758 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry xref #30228
https://api.github.com/repos/pandas-dev/pandas/pulls/37374
2020-10-23T23:25:38Z
2020-11-02T01:02:40Z
2020-11-02T01:02:40Z
2020-11-02T15:00:08Z
CLN: de-duplicate _isnan
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index ff014ac249fc3..ebe1ddb07cad0 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -377,11 +377,6 @@ def astype(self, dtype, copy=True): return Index.astype(self, dtype=dtype, copy=copy) - @cache_readonly - def _isnan(self): - """ return if each value is nan""" - return self._data.codes == -1 - @doc(Index.fillna) def fillna(self, value, downcast=None): value = self._validate_scalar(value) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 76d001d2f3ce6..863880e222b5d 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -78,7 +78,7 @@ def wrapper(left, right): @inherit_names( - ["inferred_freq", "_isnan", "_resolution_obj", "resolution"], + ["inferred_freq", "_resolution_obj", "resolution"], DatetimeLikeArrayMixin, cache=True, ) diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index c9367b7e2ee1d..4da1a43468b57 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -277,3 +277,7 @@ def astype(self, dtype, copy=True): # pass copy=False because any copying will be done in the # _data.astype call above return Index(new_values, dtype=new_values.dtype, name=self.name, copy=False) + + @cache_readonly + def _isnan(self) -> np.ndarray: + return self._data.isna() diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index cb25ef1241ce0..3ffb1160c14ce 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -37,7 +37,6 @@ is_object_dtype, is_scalar, ) -from pandas.core.dtypes.missing import isna from pandas.core.algorithms import take_1d from pandas.core.arrays.interval import IntervalArray, _interval_shared_docs @@ -192,9 +191,6 @@ class IntervalIndex(IntervalMixin, ExtensionIndex): # we would like our indexing holder to defer to us _defer_to_indexing = True - # Immutable, so we are able to cache computations like isna in '_mask' - _mask = None - _data: IntervalArray _values: IntervalArray @@ -342,15 +338,6 @@ def _shallow_copy( result._cache = self._cache return result - @cache_readonly - def _isnan(self): - """ - Return a mask indicating if each value is NA. - """ - if self._mask is None: - self._mask = isna(self.left) - return self._mask - @cache_readonly def _engine(self): left = self._maybe_convert_i8(self.left)
https://api.github.com/repos/pandas-dev/pandas/pulls/37373
2020-10-23T23:03:30Z
2020-10-24T02:50:42Z
2020-10-24T02:50:42Z
2020-10-24T03:00:20Z
TST/REF: collect tests by method
diff --git a/pandas/tests/frame/indexing/test_getitem.py b/pandas/tests/frame/indexing/test_getitem.py new file mode 100644 index 0000000000000..47d53ef6f3619 --- /dev/null +++ b/pandas/tests/frame/indexing/test_getitem.py @@ -0,0 +1,16 @@ +import pytest + +from pandas import DataFrame, MultiIndex + + +class TestGetitem: + def test_getitem_unused_level_raises(self): + # GH#20410 + mi = MultiIndex( + levels=[["a_lot", "onlyone", "notevenone"], [1970, ""]], + codes=[[1, 0], [1, 0]], + ) + df = DataFrame(-1, index=range(3), columns=mi) + + with pytest.raises(KeyError, match="notevenone"): + df["notevenone"] diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index 25e6142476d65..ddca67306d804 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -1233,17 +1233,17 @@ def test_sum_timedelta64_skipna_false(): arr = np.arange(8).astype(np.int64).view("m8[s]").reshape(4, 2) arr[-1, -1] = "Nat" - df = pd.DataFrame(arr) + df = DataFrame(arr) result = df.sum(skipna=False) - expected = pd.Series([pd.Timedelta(seconds=12), pd.NaT]) + expected = Series([pd.Timedelta(seconds=12), pd.NaT]) tm.assert_series_equal(result, expected) result = df.sum(axis=0, skipna=False) tm.assert_series_equal(result, expected) result = df.sum(axis=1, skipna=False) - expected = pd.Series( + expected = Series( [ pd.Timedelta(seconds=1), pd.Timedelta(seconds=5), diff --git a/pandas/tests/frame/test_join.py b/pandas/tests/frame/test_join.py index 2438c743f3b8a..a2e1f2398e711 100644 --- a/pandas/tests/frame/test_join.py +++ b/pandas/tests/frame/test_join.py @@ -222,6 +222,31 @@ def test_suppress_future_warning_with_sort_kw(sort_kw): class TestDataFrameJoin: + def test_join(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + + a = frame.loc[frame.index[:5], ["A"]] + b = frame.loc[frame.index[2:], ["B", "C"]] + + joined = a.join(b, how="outer").reindex(frame.index) + expected = frame.copy() + expected.values[np.isnan(joined.values)] = np.nan + + assert not np.isnan(joined.values).all() + + # TODO what should join do with names ? + tm.assert_frame_equal(joined, expected, check_names=False) + + def test_join_segfault(self): + # GH#1532 + df1 = DataFrame({"a": [1, 1], "b": [1, 2], "x": [1, 2]}) + df2 = DataFrame({"a": [2, 2], "b": [1, 2], "y": [1, 2]}) + df1 = df1.set_index(["a", "b"]) + df2 = df2.set_index(["a", "b"]) + # it works! + for how in ["left", "right", "outer"]: + df1.join(df2, how=how) + def test_join_str_datetime(self): str_dates = ["20120209", "20120222"] dt_dates = [datetime(2012, 2, 9), datetime(2012, 2, 22)] diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 70898367f6a40..9820b39e20651 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -14,8 +14,6 @@ from pandas.compat.numpy import np_datetime64_compat from pandas.util._test_decorators import async_mark -from pandas.core.dtypes.generic import ABCIndex - import pandas as pd from pandas import ( CategoricalIndex, @@ -2518,10 +2516,6 @@ def test_ensure_index_mixed_closed_intervals(self): ], ) def test_generated_op_names(opname, index): - if isinstance(index, ABCIndex) and opname == "rsub": - # Index.__rsub__ does not exist; though the method does exist - # for subclasses. see GH#19723 - return opname = f"__{opname}__" method = getattr(index, opname) assert method.__name__ == opname diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index 5c5692b777360..3b915f13c7568 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -8,7 +8,7 @@ from pandas.compat.numpy import is_numpy_dev import pandas as pd -from pandas import DataFrame, Series, Timestamp, date_range +from pandas import DataFrame, MultiIndex, Series, Timestamp, date_range import pandas._testing as tm from pandas.api.types import is_scalar from pandas.tests.indexing.common import Base @@ -979,6 +979,47 @@ def test_loc_reverse_assignment(self): tm.assert_series_equal(result, expected) +class TestLocWithMultiIndex: + @pytest.mark.parametrize( + "keys, expected", + [ + (["b", "a"], [["b", "b", "a", "a"], [1, 2, 1, 2]]), + (["a", "b"], [["a", "a", "b", "b"], [1, 2, 1, 2]]), + ((["a", "b"], [1, 2]), [["a", "a", "b", "b"], [1, 2, 1, 2]]), + ((["a", "b"], [2, 1]), [["a", "a", "b", "b"], [2, 1, 2, 1]]), + ((["b", "a"], [2, 1]), [["b", "b", "a", "a"], [2, 1, 2, 1]]), + ((["b", "a"], [1, 2]), [["b", "b", "a", "a"], [1, 2, 1, 2]]), + ((["c", "a"], [2, 1]), [["c", "a", "a"], [1, 2, 1]]), + ], + ) + @pytest.mark.parametrize("dim", ["index", "columns"]) + def test_loc_getitem_multilevel_index_order(self, dim, keys, expected): + # GH#22797 + # Try to respect order of keys given for MultiIndex.loc + kwargs = {dim: [["c", "a", "a", "b", "b"], [1, 1, 2, 1, 2]]} + df = DataFrame(np.arange(25).reshape(5, 5), **kwargs) + exp_index = MultiIndex.from_arrays(expected) + if dim == "index": + res = df.loc[keys, :] + tm.assert_index_equal(res.index, exp_index) + elif dim == "columns": + res = df.loc[:, keys] + tm.assert_index_equal(res.columns, exp_index) + + def test_loc_preserve_names(self, multiindex_year_month_day_dataframe_random_data): + ymd = multiindex_year_month_day_dataframe_random_data + + result = ymd.loc[2000] + result2 = ymd["A"].loc[2000] + assert result.index.names == ymd.index.names[1:] + assert result2.index.names == ymd.index.names[1:] + + result = ymd.loc[2000, 2] + result2 = ymd["A"].loc[2000, 2] + assert result.index.name == ymd.index.names[2] + assert result2.index.name == ymd.index.names[2] + + def test_series_loc_getitem_label_list_missing_values(): # gh-11428 key = np.array( diff --git a/pandas/tests/io/formats/test_to_html.py b/pandas/tests/io/formats/test_to_html.py index f5781fff15932..f4f963d268aeb 100644 --- a/pandas/tests/io/formats/test_to_html.py +++ b/pandas/tests/io/formats/test_to_html.py @@ -822,6 +822,14 @@ def test_html_repr_min_rows(datapath, max_rows, min_rows, expected): assert result == expected +def test_to_html_multilevel(multiindex_year_month_day_dataframe_random_data): + ymd = multiindex_year_month_day_dataframe_random_data + + ymd.columns.name = "foo" + ymd.to_html() + ymd.T.to_html() + + @pytest.mark.parametrize("na_rep", ["NaN", "Ted"]) def test_to_html_na_rep_and_float_format(na_rep): # https://github.com/pandas-dev/pandas/issues/13828 diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index a37349654b120..afc271264edbf 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -531,3 +531,20 @@ def test_pickle_binary_object_compression(compression): read_df = pd.read_pickle(buffer, compression=compression) buffer.seek(0) tm.assert_frame_equal(df, read_df) + + +def test_pickle_dataframe_with_multilevel_index( + multiindex_year_month_day_dataframe_random_data, + multiindex_dataframe_random_data, +): + ymd = multiindex_year_month_day_dataframe_random_data + frame = multiindex_dataframe_random_data + + def _test_roundtrip(frame): + unpickled = tm.round_trip_pickle(frame) + tm.assert_frame_equal(frame, unpickled) + + _test_roundtrip(frame) + _test_roundtrip(frame.T) + _test_roundtrip(ymd) + _test_roundtrip(ymd.T) diff --git a/pandas/tests/series/methods/test_count.py b/pandas/tests/series/methods/test_count.py index df1babbee8e18..7fff87c7b55f4 100644 --- a/pandas/tests/series/methods/test_count.py +++ b/pandas/tests/series/methods/test_count.py @@ -7,6 +7,26 @@ class TestSeriesCount: + def test_count_level_series(self): + index = MultiIndex( + levels=[["foo", "bar", "baz"], ["one", "two", "three", "four"]], + codes=[[0, 0, 0, 2, 2], [2, 0, 1, 1, 2]], + ) + + ser = Series(np.random.randn(len(index)), index=index) + + result = ser.count(level=0) + expected = ser.groupby(level=0).count() + tm.assert_series_equal( + result.astype("f8"), expected.reindex(result.index).fillna(0) + ) + + result = ser.count(level=1) + expected = ser.groupby(level=1).count() + tm.assert_series_equal( + result.astype("f8"), expected.reindex(result.index).fillna(0) + ) + def test_count_multiindex(self, series_with_multilevel_index): ser = series_with_multilevel_index diff --git a/pandas/tests/series/test_reductions.py b/pandas/tests/series/test_reductions.py index 28d29c69f6526..0c946b2cbccc9 100644 --- a/pandas/tests/series/test_reductions.py +++ b/pandas/tests/series/test_reductions.py @@ -2,7 +2,8 @@ import pytest import pandas as pd -from pandas import Series +from pandas import MultiIndex, Series +import pandas._testing as tm def test_reductions_td64_with_nat(): @@ -46,6 +47,14 @@ def test_prod_numpy16_bug(): assert not isinstance(result, Series) +def test_sum_with_level(): + obj = Series([10.0], index=MultiIndex.from_tuples([(2, 3)])) + + result = obj.sum(level=0) + expected = Series([10.0], index=[2]) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("func", [np.any, np.all]) @pytest.mark.parametrize("kwargs", [dict(keepdims=True), dict(out=object())]) def test_validate_any_all_out_keepdims_raises(kwargs, func): diff --git a/pandas/tests/test_expressions.py b/pandas/tests/test_expressions.py index 6db1078fcde4f..6d4c1594146de 100644 --- a/pandas/tests/test_expressions.py +++ b/pandas/tests/test_expressions.py @@ -48,30 +48,37 @@ def setup_method(self, method): def teardown_method(self, method): expr._MIN_ELEMENTS = self._MIN_ELEMENTS - def run_arithmetic(self, df, other): + @staticmethod + def call_op(df, other, flex: bool, opname: str): + if flex: + op = lambda x, y: getattr(x, opname)(y) + op.__name__ = opname + else: + op = getattr(operator, opname) + + expr.set_use_numexpr(False) + expected = op(df, other) + expr.set_use_numexpr(True) + + expr.get_test_result() + + result = op(df, other) + return result, expected + + def run_arithmetic(self, df, other, flex: bool): expr._MIN_ELEMENTS = 0 operations = ["add", "sub", "mul", "mod", "truediv", "floordiv"] - for test_flex in [True, False]: - for arith in operations: - # TODO: share with run_binary - if test_flex: - op = lambda x, y: getattr(x, arith)(y) - op.__name__ = arith + for arith in operations: + result, expected = self.call_op(df, other, flex, arith) + + if arith == "truediv": + if expected.ndim == 1: + assert expected.dtype.kind == "f" else: - op = getattr(operator, arith) - expr.set_use_numexpr(False) - expected = op(df, other) - expr.set_use_numexpr(True) - - result = op(df, other) - if arith == "truediv": - if expected.ndim == 1: - assert expected.dtype.kind == "f" - else: - assert all(x.kind == "f" for x in expected.dtypes.values) - tm.assert_equal(expected, result) - - def run_binary(self, df, other): + assert all(x.kind == "f" for x in expected.dtypes.values) + tm.assert_equal(expected, result) + + def run_binary(self, df, other, flex: bool): """ tests solely that the result is the same whether or not numexpr is enabled. Need to test whether the function does the correct thing @@ -81,37 +88,27 @@ def run_binary(self, df, other): expr.set_test_mode(True) operations = ["gt", "lt", "ge", "le", "eq", "ne"] - for test_flex in [True, False]: - for arith in operations: - if test_flex: - op = lambda x, y: getattr(x, arith)(y) - op.__name__ = arith - else: - op = getattr(operator, arith) - expr.set_use_numexpr(False) - expected = op(df, other) - expr.set_use_numexpr(True) - - expr.get_test_result() - result = op(df, other) - used_numexpr = expr.get_test_result() - assert used_numexpr, "Did not use numexpr as expected." - tm.assert_equal(expected, result) - - def run_frame(self, df, other, run_binary=True): - self.run_arithmetic(df, other) - if run_binary: - expr.set_use_numexpr(False) - binary_comp = other + 1 - expr.set_use_numexpr(True) - self.run_binary(df, binary_comp) + for arith in operations: + result, expected = self.call_op(df, other, flex, arith) + + used_numexpr = expr.get_test_result() + assert used_numexpr, "Did not use numexpr as expected." + tm.assert_equal(expected, result) + + def run_frame(self, df, other, flex: bool): + self.run_arithmetic(df, other, flex) + + expr.set_use_numexpr(False) + binary_comp = other + 1 + expr.set_use_numexpr(True) + self.run_binary(df, binary_comp, flex) for i in range(len(df.columns)): - self.run_arithmetic(df.iloc[:, i], other.iloc[:, i]) + self.run_arithmetic(df.iloc[:, i], other.iloc[:, i], flex) # FIXME: dont leave commented-out # series doesn't uses vec_compare instead of numexpr... # binary_comp = other.iloc[:, i] + 1 - # self.run_binary(df.iloc[:, i], binary_comp) + # self.run_binary(df.iloc[:, i], binary_comp, flex) @pytest.mark.parametrize( "df", @@ -126,14 +123,9 @@ def run_frame(self, df, other, run_binary=True): _mixed2, ], ) - def test_arithmetic(self, df): - # TODO: FIGURE OUT HOW TO GET RUN_BINARY TO WORK WITH MIXED=... - # can't do arithmetic because comparison methods try to do *entire* - # frame instead of by-column - kinds = {x.kind for x in df.dtypes.values} - should = len(kinds) == 1 - - self.run_frame(df, df, run_binary=should) + @pytest.mark.parametrize("flex", [True, False]) + def test_arithmetic(self, df, flex): + self.run_frame(df, df, flex) def test_invalid(self): diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index 8b8e49d914905..901049209bf64 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -32,7 +32,7 @@ def test_append(self, multiindex_dataframe_random_data): result = a["A"].append(b["A"]) tm.assert_series_equal(result, frame["A"]) - def test_dataframe_constructor(self): + def test_dataframe_constructor_infer_multiindex(self): multi = DataFrame( np.random.randn(4, 4), index=[np.array(["a", "a", "b", "b"]), np.array(["x", "y", "x", "y"])], @@ -45,7 +45,7 @@ def test_dataframe_constructor(self): ) assert isinstance(multi.columns, MultiIndex) - def test_series_constructor(self): + def test_series_constructor_infer_multiindex(self): multi = Series( 1.0, index=[np.array(["a", "a", "b", "b"]), np.array(["x", "y", "x", "y"])] ) @@ -103,23 +103,6 @@ def _check_op(opname): _check_op("mul") _check_op("div") - def test_pickle( - self, - multiindex_year_month_day_dataframe_random_data, - multiindex_dataframe_random_data, - ): - ymd = multiindex_year_month_day_dataframe_random_data - frame = multiindex_dataframe_random_data - - def _test_roundtrip(frame): - unpickled = tm.round_trip_pickle(frame) - tm.assert_frame_equal(frame, unpickled) - - _test_roundtrip(frame) - _test_roundtrip(frame.T) - _test_roundtrip(ymd) - _test_roundtrip(ymd.T) - def test_reindex(self, multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data @@ -146,37 +129,6 @@ def test_reindex_preserve_levels( chunk = ymdT.loc[:, new_index] assert chunk.columns is new_index - def test_count_level_series(self): - index = MultiIndex( - levels=[["foo", "bar", "baz"], ["one", "two", "three", "four"]], - codes=[[0, 0, 0, 2, 2], [2, 0, 1, 1, 2]], - ) - - s = Series(np.random.randn(len(index)), index=index) - - result = s.count(level=0) - expected = s.groupby(level=0).count() - tm.assert_series_equal( - result.astype("f8"), expected.reindex(result.index).fillna(0) - ) - - result = s.count(level=1) - expected = s.groupby(level=1).count() - tm.assert_series_equal( - result.astype("f8"), expected.reindex(result.index).fillna(0) - ) - - def test_unused_level_raises(self): - # GH 20410 - mi = MultiIndex( - levels=[["a_lot", "onlyone", "notevenone"], [1970, ""]], - codes=[[1, 0], [1, 0]], - ) - df = DataFrame(-1, index=range(3), columns=mi) - - with pytest.raises(KeyError, match="notevenone"): - df["notevenone"] - def test_groupby_transform(self, multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data @@ -219,21 +171,6 @@ def test_groupby_level_no_obs(self): result = grouped.sum() assert (result.columns == ["f2", "f3"]).all() - def test_join(self, multiindex_dataframe_random_data): - frame = multiindex_dataframe_random_data - - a = frame.loc[frame.index[:5], ["A"]] - b = frame.loc[frame.index[2:], ["B", "C"]] - - joined = a.join(b, how="outer").reindex(frame.index) - expected = frame.copy() - expected.values[np.isnan(joined.values)] = np.nan - - assert not np.isnan(joined.values).all() - - # TODO what should join do with names ? - tm.assert_frame_equal(joined, expected, check_names=False) - def test_insert_index(self, multiindex_year_month_day_dataframe_random_data): ymd = multiindex_year_month_day_dataframe_random_data @@ -323,13 +260,6 @@ def aggf(x): tm.assert_frame_equal(leftside, rightside) - def test_stat_op_corner(self): - obj = Series([10.0], index=MultiIndex.from_tuples([(2, 3)])) - - result = obj.sum(level=0) - expected = Series([10.0], index=[2]) - tm.assert_series_equal(result, expected) - def test_std_var_pass_ddof(self): index = MultiIndex.from_arrays( [np.arange(5).repeat(10), np.tile(np.arange(10), 5)] @@ -389,26 +319,6 @@ def test_multilevel_consolidate(self): df["Totals", ""] = df.sum(1) df = df._consolidate() - def test_loc_preserve_names(self, multiindex_year_month_day_dataframe_random_data): - ymd = multiindex_year_month_day_dataframe_random_data - - result = ymd.loc[2000] - result2 = ymd["A"].loc[2000] - assert result.index.names == ymd.index.names[1:] - assert result2.index.names == ymd.index.names[1:] - - result = ymd.loc[2000, 2] - result2 = ymd["A"].loc[2000, 2] - assert result.index.name == ymd.index.names[2] - assert result2.index.name == ymd.index.names[2] - - def test_to_html(self, multiindex_year_month_day_dataframe_random_data): - ymd = multiindex_year_month_day_dataframe_random_data - - ymd.columns.name = "foo" - ymd.to_html() - ymd.T.to_html() - def test_level_with_tuples(self): index = MultiIndex( levels=[[("foo", "bar", 0), ("foo", "baz", 0), ("foo", "qux", 0)], [0, 1]], @@ -484,16 +394,6 @@ def test_unicode_repr_level_names(self): repr(s) repr(df) - def test_join_segfault(self): - # 1532 - df1 = DataFrame({"a": [1, 1], "b": [1, 2], "x": [1, 2]}) - df2 = DataFrame({"a": [2, 2], "b": [1, 2], "y": [1, 2]}) - df1 = df1.set_index(["a", "b"]) - df2 = df2.set_index(["a", "b"]) - # it works! - for how in ["left", "right", "outer"]: - df1.join(df2, how=how) - @pytest.mark.parametrize("d", [4, "d"]) def test_empty_frame_groupby_dtypes_consistency(self, d): # GH 20888 @@ -583,29 +483,3 @@ def test_sort_non_lexsorted(self): ) result = sorted.loc[pd.IndexSlice["B":"C", "a":"c"], :] tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( - "keys, expected", - [ - (["b", "a"], [["b", "b", "a", "a"], [1, 2, 1, 2]]), - (["a", "b"], [["a", "a", "b", "b"], [1, 2, 1, 2]]), - ((["a", "b"], [1, 2]), [["a", "a", "b", "b"], [1, 2, 1, 2]]), - ((["a", "b"], [2, 1]), [["a", "a", "b", "b"], [2, 1, 2, 1]]), - ((["b", "a"], [2, 1]), [["b", "b", "a", "a"], [2, 1, 2, 1]]), - ((["b", "a"], [1, 2]), [["b", "b", "a", "a"], [1, 2, 1, 2]]), - ((["c", "a"], [2, 1]), [["c", "a", "a"], [1, 2, 1]]), - ], - ) - @pytest.mark.parametrize("dim", ["index", "columns"]) - def test_multilevel_index_loc_order(self, dim, keys, expected): - # GH 22797 - # Try to respect order of keys given for MultiIndex.loc - kwargs = {dim: [["c", "a", "a", "b", "b"], [1, 1, 2, 1, 2]]} - df = DataFrame(np.arange(25).reshape(5, 5), **kwargs) - exp_index = MultiIndex.from_arrays(expected) - if dim == "index": - res = df.loc[keys, :] - tm.assert_index_equal(res.index, exp_index) - elif dim == "columns": - res = df.loc[:, keys] - tm.assert_index_equal(res.columns, exp_index)
https://api.github.com/repos/pandas-dev/pandas/pulls/37372
2020-10-23T22:34:40Z
2020-10-24T17:53:39Z
2020-10-24T17:53:39Z
2020-10-24T18:00:19Z
PERF: ensure_string_array with non-numpy input array
diff --git a/asv_bench/benchmarks/strings.py b/asv_bench/benchmarks/strings.py index d8b35abb94b9d..7c75ad031e7cd 100644 --- a/asv_bench/benchmarks/strings.py +++ b/asv_bench/benchmarks/strings.py @@ -2,7 +2,7 @@ import numpy as np -from pandas import DataFrame, Series +from pandas import Categorical, DataFrame, Series from .pandas_vb_common import tm @@ -16,6 +16,10 @@ def setup(self, dtype): self.series_arr = tm.rands_array(nchars=10, size=10 ** 5) self.frame_arr = self.series_arr.reshape((50_000, 2)).copy() + # GH37371. Testing construction of string series/frames from ExtensionArrays + self.series_cat_arr = Categorical(self.series_arr) + self.frame_cat_arr = Categorical(self.frame_arr) + def time_series_construction(self, dtype): Series(self.series_arr, dtype=dtype) @@ -28,6 +32,18 @@ def time_frame_construction(self, dtype): def peakmem_frame_construction(self, dtype): DataFrame(self.frame_arr, dtype=dtype) + def time_cat_series_construction(self, dtype): + Series(self.series_cat_arr, dtype=dtype) + + def peakmem_cat_series_construction(self, dtype): + Series(self.series_cat_arr, dtype=dtype) + + def time_cat_frame_construction(self, dtype): + DataFrame(self.frame_cat_arr, dtype=dtype) + + def peakmem_cat_frame_construction(self, dtype): + DataFrame(self.frame_cat_arr, dtype=dtype) + class Methods: def setup(self): diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 05996efb6d332..9b320182d7968 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -334,7 +334,7 @@ Deprecations Performance improvements ~~~~~~~~~~~~~~~~~~~~~~~~ -- Performance improvements when creating DataFrame or Series with dtype ``str`` or :class:`StringDtype` from array with many string elements (:issue:`36304`, :issue:`36317`, :issue:`36325`, :issue:`36432`) +- Performance improvements when creating DataFrame or Series with dtype ``str`` or :class:`StringDtype` from array with many string elements (:issue:`36304`, :issue:`36317`, :issue:`36325`, :issue:`36432`, :issue:`37371`) - Performance improvement in :meth:`GroupBy.agg` with the ``numba`` engine (:issue:`35759`) - Performance improvements when creating :meth:`pd.Series.map` from a huge dictionary (:issue:`34717`) - Performance improvement in :meth:`GroupBy.transform` with the ``numba`` engine (:issue:`36240`) diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 001fbae120ae8..2cb4df7e054fe 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -651,6 +651,11 @@ cpdef ndarray[object] ensure_string_array( cdef: Py_ssize_t i = 0, n = len(arr) + if hasattr(arr, "to_numpy"): + arr = arr.to_numpy() + elif not isinstance(arr, np.ndarray): + arr = np.array(arr, dtype="object") + result = np.asarray(arr, dtype="object") if copy and result is arr:
Currently, if the input array to `ensure_string_array` is a python object (e.g. an `ExtensionArray`), the function will constantly switch between python and cython level code, which is slow. This PR fixes that by ensuring we always have a numpy array, avoiding the trips to python level code. ``` python >>> n = 50_000 >>> cat = pd.Categorical([*['a', pd.NA] * n]) >>> %timeit cat.astype("string") 447 ms ± 11.9 ms per loop # master 5.43 ms ± 80.5 µs per loop # this PR ``` xref #35519, #36464.
https://api.github.com/repos/pandas-dev/pandas/pulls/37371
2020-10-23T21:11:34Z
2020-10-26T17:37:54Z
2020-10-26T17:37:54Z
2020-10-26T22:45:48Z
DOC: add searchsorted examples #36411
diff --git a/pandas/core/base.py b/pandas/core/base.py index 10b83116dee58..67d5d4a24ae49 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -1182,6 +1182,16 @@ def factorize(self, sort: bool = False, na_sentinel: Optional[int] = -1): >>> ser.searchsorted([1, 3], side='right') array([1, 3]) + >>> ser = pd.Series(pd.to_datetime(['3/11/2000', '3/12/2000', '3/13/2000'])) + >>> ser + 0 2000-03-11 + 1 2000-03-12 + 2 2000-03-13 + dtype: datetime64[ns] + + >>> ser.searchsorted('3/14/2000') + 3 + >>> ser = pd.Categorical( ... ['apple', 'bread', 'bread', 'cheese', 'milk'], ordered=True ... )
DOC: add searchsorted examples #36411
https://api.github.com/repos/pandas-dev/pandas/pulls/37370
2020-10-23T20:59:52Z
2020-10-25T18:43:01Z
2020-10-25T18:43:01Z
2020-11-05T20:55:07Z
BUG: Call finalize in DataFrame.unstack
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index f17be825e1295..3e2267a69ed0d 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -529,7 +529,7 @@ Other - Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` incorrectly raising ``AssertionError`` instead of ``ValueError`` when invalid parameter combinations are passed (:issue:`36045`) - Bug in :meth:`DataFrame.replace` and :meth:`Series.replace` with numeric values and string ``to_replace`` (:issue:`34789`) - Fixed bug in metadata propagation incorrectly copying DataFrame columns as metadata when the column name overlaps with the metadata name (:issue:`37037`) -- Fixed metadata propagation in the :class:`Series.dt` and :class:`Series.str` accessors and :class:`DataFrame.duplicated` and ::class:`DataFrame.stack` methods (:issue:`28283`) +- Fixed metadata propagation in the :class:`Series.dt` and :class:`Series.str` accessors and :class:`DataFrame.duplicated` and :class:`DataFrame.stack` and :class:`DataFrame.unstack` and :class:`DataFrame.pivot` methods (:issue:`28283`) - Bug in :meth:`Index.union` behaving differently depending on whether operand is a :class:`Index` or other list-like (:issue:`36384`) - Passing an array with 2 or more dimensions to the :class:`Series` constructor now raises the more specific ``ValueError``, from a bare ``Exception`` previously (:issue:`35744`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index eb150dd87347f..b1d2a7fb0bf7d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -7256,7 +7256,9 @@ def unstack(self, level=-1, fill_value=None): """ from pandas.core.reshape.reshape import unstack - return unstack(self, level, fill_value) + result = unstack(self, level, fill_value) + + return result.__finalize__(self, method="unstack") @Appender(_shared_docs["melt"] % dict(caller="df.melt(", other="melt")) def melt( diff --git a/pandas/tests/generic/test_finalize.py b/pandas/tests/generic/test_finalize.py index 9d2e5cbcc7b58..211d86c89cde7 100644 --- a/pandas/tests/generic/test_finalize.py +++ b/pandas/tests/generic/test_finalize.py @@ -154,10 +154,7 @@ ), marks=not_implemented_mark, ), - pytest.param( - (pd.DataFrame, frame_data, operator.methodcaller("pivot", columns="A")), - marks=not_implemented_mark, - ), + (pd.DataFrame, frame_data, operator.methodcaller("pivot", columns="A")), pytest.param( ( pd.DataFrame, @@ -171,10 +168,7 @@ (pd.DataFrame, frame_data, operator.methodcaller("explode", "A")), marks=not_implemented_mark, ), - pytest.param( - (pd.DataFrame, frame_mi_data, operator.methodcaller("unstack")), - marks=not_implemented_mark, - ), + (pd.DataFrame, frame_mi_data, operator.methodcaller("unstack")), pytest.param( ( pd.DataFrame,
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This commit adds a step to call `__finalize__` in `DataFrame.unstack`, as motivated by #28283. Adding this step also prevents needing a step to call `__finalize__` in `DataFrame.pivot` since `DataFrame.unstack` is called before returning, so the xfail for that test was removed as well.
https://api.github.com/repos/pandas-dev/pandas/pulls/37369
2020-10-23T20:44:05Z
2020-10-24T03:09:22Z
2020-10-24T03:09:22Z
2020-10-24T03:54:08Z
TST: split up test_concat.py #37243 - follows up
diff --git a/pandas/tests/reshape/concat/test_concat.py b/pandas/tests/reshape/concat/test_concat.py index 6fa4419f90138..c3e1f3177b3d3 100644 --- a/pandas/tests/reshape/concat/test_concat.py +++ b/pandas/tests/reshape/concat/test_concat.py @@ -1,11 +1,8 @@ from collections import abc, deque -import datetime as dt -from datetime import datetime from decimal import Decimal from io import StringIO from warnings import catch_warnings -import dateutil import numpy as np from numpy.random import randn import pytest @@ -20,7 +17,6 @@ Index, MultiIndex, Series, - Timestamp, concat, date_range, read_csv, @@ -259,35 +255,6 @@ def test_concat_multiindex_with_keys(self): tm.assert_frame_equal(result.loc[1], frame) assert result.index.nlevels == 3 - def test_concat_multiindex_with_tz(self): - # GH 6606 - df = DataFrame( - { - "dt": [ - datetime(2014, 1, 1), - datetime(2014, 1, 2), - datetime(2014, 1, 3), - ], - "b": ["A", "B", "C"], - "c": [1, 2, 3], - "d": [4, 5, 6], - } - ) - df["dt"] = df["dt"].apply(lambda d: Timestamp(d, tz="US/Pacific")) - df = df.set_index(["dt", "b"]) - - exp_idx1 = DatetimeIndex( - ["2014-01-01", "2014-01-02", "2014-01-03"] * 2, tz="US/Pacific", name="dt" - ) - exp_idx2 = Index(["A", "B", "C"] * 2, name="b") - exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2]) - expected = DataFrame( - {"c": [1, 2, 3] * 2, "d": [4, 5, 6] * 2}, index=exp_idx, columns=["c", "d"] - ) - - result = concat([df, df]) - tm.assert_frame_equal(result, expected) - def test_concat_multiindex_with_none_in_index_names(self): # GH 15787 index = pd.MultiIndex.from_product([[1], range(5)], names=["level1", None]) @@ -697,17 +664,6 @@ def test_concat_exclude_none(self): with pytest.raises(ValueError, match="All objects passed were None"): concat([None, None]) - def test_concat_datetime64_block(self): - from pandas.core.indexes.datetimes import date_range - - rng = date_range("1/1/2000", periods=10) - - df = DataFrame({"time": rng}) - - result = concat([df, df]) - assert (result.iloc[:10]["time"] == rng).all() - assert (result.iloc[10:]["time"] == rng).all() - def test_concat_timedelta64_block(self): from pandas import to_timedelta @@ -874,259 +830,6 @@ def test_concat_invalid_first_argument(self): expected = read_csv(StringIO(data)) tm.assert_frame_equal(result, expected) - def test_concat_NaT_series(self): - # GH 11693 - # test for merging NaT series with datetime series. - x = Series( - date_range("20151124 08:00", "20151124 09:00", freq="1h", tz="US/Eastern") - ) - y = Series(pd.NaT, index=[0, 1], dtype="datetime64[ns, US/Eastern]") - expected = Series([x[0], x[1], pd.NaT, pd.NaT]) - - result = concat([x, y], ignore_index=True) - tm.assert_series_equal(result, expected) - - # all NaT with tz - expected = Series(pd.NaT, index=range(4), dtype="datetime64[ns, US/Eastern]") - result = pd.concat([y, y], ignore_index=True) - tm.assert_series_equal(result, expected) - - # without tz - x = Series(pd.date_range("20151124 08:00", "20151124 09:00", freq="1h")) - y = Series(pd.date_range("20151124 10:00", "20151124 11:00", freq="1h")) - y[:] = pd.NaT - expected = Series([x[0], x[1], pd.NaT, pd.NaT]) - result = pd.concat([x, y], ignore_index=True) - tm.assert_series_equal(result, expected) - - # all NaT without tz - x[:] = pd.NaT - expected = Series(pd.NaT, index=range(4), dtype="datetime64[ns]") - result = pd.concat([x, y], ignore_index=True) - tm.assert_series_equal(result, expected) - - def test_concat_tz_frame(self): - df2 = DataFrame( - dict( - A=pd.Timestamp("20130102", tz="US/Eastern"), - B=pd.Timestamp("20130603", tz="CET"), - ), - index=range(5), - ) - - # concat - df3 = pd.concat([df2.A.to_frame(), df2.B.to_frame()], axis=1) - tm.assert_frame_equal(df2, df3) - - def test_concat_tz_series(self): - # gh-11755: tz and no tz - x = Series(date_range("20151124 08:00", "20151124 09:00", freq="1h", tz="UTC")) - y = Series(date_range("2012-01-01", "2012-01-02")) - expected = Series([x[0], x[1], y[0], y[1]], dtype="object") - result = concat([x, y], ignore_index=True) - tm.assert_series_equal(result, expected) - - # gh-11887: concat tz and object - x = Series(date_range("20151124 08:00", "20151124 09:00", freq="1h", tz="UTC")) - y = Series(["a", "b"]) - expected = Series([x[0], x[1], y[0], y[1]], dtype="object") - result = concat([x, y], ignore_index=True) - tm.assert_series_equal(result, expected) - - # see gh-12217 and gh-12306 - # Concatenating two UTC times - first = DataFrame([[datetime(2016, 1, 1)]]) - first[0] = first[0].dt.tz_localize("UTC") - - second = DataFrame([[datetime(2016, 1, 2)]]) - second[0] = second[0].dt.tz_localize("UTC") - - result = pd.concat([first, second]) - assert result[0].dtype == "datetime64[ns, UTC]" - - # Concatenating two London times - first = DataFrame([[datetime(2016, 1, 1)]]) - first[0] = first[0].dt.tz_localize("Europe/London") - - second = DataFrame([[datetime(2016, 1, 2)]]) - second[0] = second[0].dt.tz_localize("Europe/London") - - result = pd.concat([first, second]) - assert result[0].dtype == "datetime64[ns, Europe/London]" - - # Concatenating 2+1 London times - first = DataFrame([[datetime(2016, 1, 1)], [datetime(2016, 1, 2)]]) - first[0] = first[0].dt.tz_localize("Europe/London") - - second = DataFrame([[datetime(2016, 1, 3)]]) - second[0] = second[0].dt.tz_localize("Europe/London") - - result = pd.concat([first, second]) - assert result[0].dtype == "datetime64[ns, Europe/London]" - - # Concat'ing 1+2 London times - first = DataFrame([[datetime(2016, 1, 1)]]) - first[0] = first[0].dt.tz_localize("Europe/London") - - second = DataFrame([[datetime(2016, 1, 2)], [datetime(2016, 1, 3)]]) - second[0] = second[0].dt.tz_localize("Europe/London") - - result = pd.concat([first, second]) - assert result[0].dtype == "datetime64[ns, Europe/London]" - - def test_concat_tz_series_with_datetimelike(self): - # see gh-12620: tz and timedelta - x = [ - pd.Timestamp("2011-01-01", tz="US/Eastern"), - pd.Timestamp("2011-02-01", tz="US/Eastern"), - ] - y = [pd.Timedelta("1 day"), pd.Timedelta("2 day")] - result = concat([Series(x), Series(y)], ignore_index=True) - tm.assert_series_equal(result, Series(x + y, dtype="object")) - - # tz and period - y = [pd.Period("2011-03", freq="M"), pd.Period("2011-04", freq="M")] - result = concat([Series(x), Series(y)], ignore_index=True) - tm.assert_series_equal(result, Series(x + y, dtype="object")) - - def test_concat_tz_series_tzlocal(self): - # see gh-13583 - x = [ - pd.Timestamp("2011-01-01", tz=dateutil.tz.tzlocal()), - pd.Timestamp("2011-02-01", tz=dateutil.tz.tzlocal()), - ] - y = [ - pd.Timestamp("2012-01-01", tz=dateutil.tz.tzlocal()), - pd.Timestamp("2012-02-01", tz=dateutil.tz.tzlocal()), - ] - - result = concat([Series(x), Series(y)], ignore_index=True) - tm.assert_series_equal(result, Series(x + y)) - assert result.dtype == "datetime64[ns, tzlocal()]" - - @pytest.mark.parametrize("tz1", [None, "UTC"]) - @pytest.mark.parametrize("tz2", [None, "UTC"]) - @pytest.mark.parametrize("s", [pd.NaT, pd.Timestamp("20150101")]) - def test_concat_NaT_dataframes_all_NaT_axis_0(self, tz1, tz2, s): - # GH 12396 - - # tz-naive - first = DataFrame([[pd.NaT], [pd.NaT]]).apply(lambda x: x.dt.tz_localize(tz1)) - second = DataFrame([s]).apply(lambda x: x.dt.tz_localize(tz2)) - - result = pd.concat([first, second], axis=0) - expected = DataFrame(Series([pd.NaT, pd.NaT, s], index=[0, 1, 0])) - expected = expected.apply(lambda x: x.dt.tz_localize(tz2)) - if tz1 != tz2: - expected = expected.astype(object) - - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("tz1", [None, "UTC"]) - @pytest.mark.parametrize("tz2", [None, "UTC"]) - def test_concat_NaT_dataframes_all_NaT_axis_1(self, tz1, tz2): - # GH 12396 - - first = DataFrame(Series([pd.NaT, pd.NaT]).dt.tz_localize(tz1)) - second = DataFrame(Series([pd.NaT]).dt.tz_localize(tz2), columns=[1]) - expected = DataFrame( - { - 0: Series([pd.NaT, pd.NaT]).dt.tz_localize(tz1), - 1: Series([pd.NaT, pd.NaT]).dt.tz_localize(tz2), - } - ) - result = pd.concat([first, second], axis=1) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("tz1", [None, "UTC"]) - @pytest.mark.parametrize("tz2", [None, "UTC"]) - def test_concat_NaT_series_dataframe_all_NaT(self, tz1, tz2): - # GH 12396 - - # tz-naive - first = Series([pd.NaT, pd.NaT]).dt.tz_localize(tz1) - second = DataFrame( - [ - [pd.Timestamp("2015/01/01", tz=tz2)], - [pd.Timestamp("2016/01/01", tz=tz2)], - ], - index=[2, 3], - ) - - expected = DataFrame( - [ - pd.NaT, - pd.NaT, - pd.Timestamp("2015/01/01", tz=tz2), - pd.Timestamp("2016/01/01", tz=tz2), - ] - ) - if tz1 != tz2: - expected = expected.astype(object) - - result = pd.concat([first, second]) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("tz", [None, "UTC"]) - def test_concat_NaT_dataframes(self, tz): - # GH 12396 - - first = DataFrame([[pd.NaT], [pd.NaT]]) - first = first.apply(lambda x: x.dt.tz_localize(tz)) - second = DataFrame( - [[pd.Timestamp("2015/01/01", tz=tz)], [pd.Timestamp("2016/01/01", tz=tz)]], - index=[2, 3], - ) - expected = DataFrame( - [ - pd.NaT, - pd.NaT, - pd.Timestamp("2015/01/01", tz=tz), - pd.Timestamp("2016/01/01", tz=tz), - ] - ) - - result = pd.concat([first, second], axis=0) - tm.assert_frame_equal(result, expected) - - def test_concat_period_series(self): - x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) - y = Series(pd.PeriodIndex(["2015-10-01", "2016-01-01"], freq="D")) - expected = Series([x[0], x[1], y[0], y[1]], dtype="Period[D]") - result = concat([x, y], ignore_index=True) - tm.assert_series_equal(result, expected) - - def test_concat_period_multiple_freq_series(self): - x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) - y = Series(pd.PeriodIndex(["2015-10-01", "2016-01-01"], freq="M")) - expected = Series([x[0], x[1], y[0], y[1]], dtype="object") - result = concat([x, y], ignore_index=True) - tm.assert_series_equal(result, expected) - assert result.dtype == "object" - - def test_concat_period_other_series(self): - x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) - y = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="M")) - expected = Series([x[0], x[1], y[0], y[1]], dtype="object") - result = concat([x, y], ignore_index=True) - tm.assert_series_equal(result, expected) - assert result.dtype == "object" - - # non-period - x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) - y = Series(pd.DatetimeIndex(["2015-11-01", "2015-12-01"])) - expected = Series([x[0], x[1], y[0], y[1]], dtype="object") - result = concat([x, y], ignore_index=True) - tm.assert_series_equal(result, expected) - assert result.dtype == "object" - - x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) - y = Series(["A", "B"]) - expected = Series([x[0], x[1], y[0], y[1]], dtype="object") - result = concat([x, y], ignore_index=True) - tm.assert_series_equal(result, expected) - assert result.dtype == "object" - def test_concat_empty_series(self): # GH 11082 s1 = Series([1, 2, 3], name="x") @@ -1430,73 +1133,6 @@ def test_concat_order(self): expected = dfs[0].columns tm.assert_index_equal(result, expected) - def test_concat_datetime_timezone(self): - # GH 18523 - idx1 = pd.date_range("2011-01-01", periods=3, freq="H", tz="Europe/Paris") - idx2 = pd.date_range(start=idx1[0], end=idx1[-1], freq="H") - df1 = DataFrame({"a": [1, 2, 3]}, index=idx1) - df2 = DataFrame({"b": [1, 2, 3]}, index=idx2) - result = pd.concat([df1, df2], axis=1) - - exp_idx = ( - DatetimeIndex( - [ - "2011-01-01 00:00:00+01:00", - "2011-01-01 01:00:00+01:00", - "2011-01-01 02:00:00+01:00", - ], - freq="H", - ) - .tz_convert("UTC") - .tz_convert("Europe/Paris") - ) - - expected = DataFrame( - [[1, 1], [2, 2], [3, 3]], index=exp_idx, columns=["a", "b"] - ) - - tm.assert_frame_equal(result, expected) - - idx3 = pd.date_range("2011-01-01", periods=3, freq="H", tz="Asia/Tokyo") - df3 = DataFrame({"b": [1, 2, 3]}, index=idx3) - result = pd.concat([df1, df3], axis=1) - - exp_idx = DatetimeIndex( - [ - "2010-12-31 15:00:00+00:00", - "2010-12-31 16:00:00+00:00", - "2010-12-31 17:00:00+00:00", - "2010-12-31 23:00:00+00:00", - "2011-01-01 00:00:00+00:00", - "2011-01-01 01:00:00+00:00", - ] - ) - - expected = DataFrame( - [ - [np.nan, 1], - [np.nan, 2], - [np.nan, 3], - [1, np.nan], - [2, np.nan], - [3, np.nan], - ], - index=exp_idx, - columns=["a", "b"], - ) - - tm.assert_frame_equal(result, expected) - - # GH 13783: Concat after resample - result = pd.concat( - [df1.resample("H").mean(), df2.resample("H").mean()], sort=True - ) - expected = DataFrame( - {"a": [1, 2, 3] + [np.nan] * 3, "b": [np.nan] * 3 + [1, 2, 3]}, - index=idx1.append(idx1), - ) - tm.assert_frame_equal(result, expected) - def test_concat_different_extension_dtypes_upcasts(self): a = Series(pd.core.arrays.integer_array([1, 2])) b = Series(to_decimal([1, 2])) @@ -1699,22 +1335,6 @@ def test_concat_categorical_unchanged(): tm.assert_equal(result, expected) -def test_concat_datetimeindex_freq(): - # GH 3232 - # Monotonic index result - dr = pd.date_range("01-Jan-2013", periods=100, freq="50L", tz="UTC") - data = list(range(100)) - expected = DataFrame(data, index=dr) - result = pd.concat([expected[:50], expected[50:]]) - tm.assert_frame_equal(result, expected) - - # Non-monotonic index result - result = pd.concat([expected[50:], expected[:50]]) - expected = DataFrame(data[50:] + data[:50], index=dr[50:].append(dr[:50])) - expected.index._data.freq = None - tm.assert_frame_equal(result, expected) - - def test_concat_empty_df_object_dtype(): # GH 9149 df_1 = DataFrame({"Row": [0, 1, 1], "EmptyCol": np.nan, "NumberCol": [1, 2, 3]}) @@ -1759,40 +1379,6 @@ def test_concat_copy_index(test_series, axis): assert comb.columns is not df.columns -def test_concat_multiindex_datetime_object_index(): - # https://github.com/pandas-dev/pandas/issues/11058 - s = Series( - ["a", "b"], - index=MultiIndex.from_arrays( - [[1, 2], Index([dt.date(2013, 1, 1), dt.date(2014, 1, 1)], dtype="object")], - names=["first", "second"], - ), - ) - s2 = Series( - ["a", "b"], - index=MultiIndex.from_arrays( - [[1, 2], Index([dt.date(2013, 1, 1), dt.date(2015, 1, 1)], dtype="object")], - names=["first", "second"], - ), - ) - expected = DataFrame( - [["a", "a"], ["b", np.nan], [np.nan, "b"]], - index=MultiIndex.from_arrays( - [ - [1, 2, 2], - DatetimeIndex( - ["2013-01-01", "2014-01-01", "2015-01-01"], - dtype="datetime64[ns]", - freq=None, - ), - ], - names=["first", "second"], - ), - ) - result = concat([s, s2], axis=1) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize("keys", [["e", "f", "f"], ["f", "e", "f"]]) def test_duplicate_keys(keys): # GH 33654 diff --git a/pandas/tests/reshape/concat/test_dataframe.py b/pandas/tests/reshape/concat/test_dataframe.py index 21abd1bed7cbc..0e302f5e71fb4 100644 --- a/pandas/tests/reshape/concat/test_dataframe.py +++ b/pandas/tests/reshape/concat/test_dataframe.py @@ -1,10 +1,8 @@ -from datetime import datetime - import numpy as np import pytest import pandas as pd -from pandas import DataFrame, Index, Series, Timestamp, date_range +from pandas import DataFrame, Index, Series import pandas._testing as tm @@ -21,67 +19,6 @@ def test_concat_multiple_frames_dtypes(self): ) tm.assert_series_equal(results, expected) - def test_concat_multiple_tzs(self): - # GH#12467 - # combining datetime tz-aware and naive DataFrames - ts1 = Timestamp("2015-01-01", tz=None) - ts2 = Timestamp("2015-01-01", tz="UTC") - ts3 = Timestamp("2015-01-01", tz="EST") - - df1 = DataFrame(dict(time=[ts1])) - df2 = DataFrame(dict(time=[ts2])) - df3 = DataFrame(dict(time=[ts3])) - - results = pd.concat([df1, df2]).reset_index(drop=True) - expected = DataFrame(dict(time=[ts1, ts2]), dtype=object) - tm.assert_frame_equal(results, expected) - - results = pd.concat([df1, df3]).reset_index(drop=True) - expected = DataFrame(dict(time=[ts1, ts3]), dtype=object) - tm.assert_frame_equal(results, expected) - - results = pd.concat([df2, df3]).reset_index(drop=True) - expected = DataFrame(dict(time=[ts2, ts3])) - tm.assert_frame_equal(results, expected) - - @pytest.mark.parametrize( - "t1", - [ - "2015-01-01", - pytest.param( - pd.NaT, - marks=pytest.mark.xfail( - reason="GH23037 incorrect dtype when concatenating" - ), - ), - ], - ) - def test_concat_tz_NaT(self, t1): - # GH#22796 - # Concating tz-aware multicolumn DataFrames - ts1 = Timestamp(t1, tz="UTC") - ts2 = Timestamp("2015-01-01", tz="UTC") - ts3 = Timestamp("2015-01-01", tz="UTC") - - df1 = DataFrame([[ts1, ts2]]) - df2 = DataFrame([[ts3]]) - - result = pd.concat([df1, df2]) - expected = DataFrame([[ts1, ts2], [ts3, pd.NaT]], index=[0, 0]) - - tm.assert_frame_equal(result, expected) - - def test_concat_tz_not_aligned(self): - # GH#22796 - ts = pd.to_datetime([1, 2]).tz_localize("UTC") - a = DataFrame({"A": ts}) - b = DataFrame({"A": ts, "B": ts}) - result = pd.concat([a, b], sort=True, ignore_index=True) - expected = DataFrame( - {"A": list(ts) + list(ts), "B": [pd.NaT, pd.NaT] + list(ts)} - ) - tm.assert_frame_equal(result, expected) - def test_concat_tuple_keys(self): # GH#14438 df1 = DataFrame(np.ones((2, 2)), columns=list("AB")) @@ -220,17 +157,3 @@ def test_concat_astype_dup_col(self): np.array(["b", "b"]).reshape(1, 2), columns=["a", "a"] ).astype("category") tm.assert_frame_equal(result, expected) - - def test_concat_datetime_datetime64_frame(self): - # GH#2624 - rows = [] - rows.append([datetime(2010, 1, 1), 1]) - rows.append([datetime(2010, 1, 2), "hi"]) - - df2_obj = DataFrame.from_records(rows, columns=["date", "test"]) - - ind = date_range(start="2000/1/1", freq="D", periods=10) - df1 = DataFrame({"date": ind, "test": range(10)}) - - # it works! - pd.concat([df1, df2_obj]) diff --git a/pandas/tests/reshape/concat/test_datetimes.py b/pandas/tests/reshape/concat/test_datetimes.py new file mode 100644 index 0000000000000..0becb16beee08 --- /dev/null +++ b/pandas/tests/reshape/concat/test_datetimes.py @@ -0,0 +1,520 @@ +import datetime as dt +from datetime import datetime + +import dateutil +import numpy as np +import pytest + +import pandas as pd +from pandas import ( + DataFrame, + DatetimeIndex, + Index, + MultiIndex, + Series, + Timestamp, + concat, + date_range, +) +import pandas._testing as tm + + +@pytest.fixture(params=[True, False]) +def sort(request): + """Boolean sort keyword for concat and DataFrame.append.""" + return request.param + + +class TestDatetimeConcat: + def test_concat_datetime64_block(self): + from pandas.core.indexes.datetimes import date_range + + rng = date_range("1/1/2000", periods=10) + + df = DataFrame({"time": rng}) + + result = concat([df, df]) + assert (result.iloc[:10]["time"] == rng).all() + assert (result.iloc[10:]["time"] == rng).all() + + def test_concat_datetime_datetime64_frame(self): + # GH#2624 + rows = [] + rows.append([datetime(2010, 1, 1), 1]) + rows.append([datetime(2010, 1, 2), "hi"]) + + df2_obj = DataFrame.from_records(rows, columns=["date", "test"]) + + ind = date_range(start="2000/1/1", freq="D", periods=10) + df1 = DataFrame({"date": ind, "test": range(10)}) + + # it works! + pd.concat([df1, df2_obj]) + + def test_concat_datetime_timezone(self): + # GH 18523 + idx1 = pd.date_range("2011-01-01", periods=3, freq="H", tz="Europe/Paris") + idx2 = pd.date_range(start=idx1[0], end=idx1[-1], freq="H") + df1 = DataFrame({"a": [1, 2, 3]}, index=idx1) + df2 = DataFrame({"b": [1, 2, 3]}, index=idx2) + result = pd.concat([df1, df2], axis=1) + + exp_idx = ( + DatetimeIndex( + [ + "2011-01-01 00:00:00+01:00", + "2011-01-01 01:00:00+01:00", + "2011-01-01 02:00:00+01:00", + ], + freq="H", + ) + .tz_convert("UTC") + .tz_convert("Europe/Paris") + ) + + expected = DataFrame( + [[1, 1], [2, 2], [3, 3]], index=exp_idx, columns=["a", "b"] + ) + + tm.assert_frame_equal(result, expected) + + idx3 = pd.date_range("2011-01-01", periods=3, freq="H", tz="Asia/Tokyo") + df3 = DataFrame({"b": [1, 2, 3]}, index=idx3) + result = pd.concat([df1, df3], axis=1) + + exp_idx = DatetimeIndex( + [ + "2010-12-31 15:00:00+00:00", + "2010-12-31 16:00:00+00:00", + "2010-12-31 17:00:00+00:00", + "2010-12-31 23:00:00+00:00", + "2011-01-01 00:00:00+00:00", + "2011-01-01 01:00:00+00:00", + ] + ) + + expected = DataFrame( + [ + [np.nan, 1], + [np.nan, 2], + [np.nan, 3], + [1, np.nan], + [2, np.nan], + [3, np.nan], + ], + index=exp_idx, + columns=["a", "b"], + ) + + tm.assert_frame_equal(result, expected) + + # GH 13783: Concat after resample + result = pd.concat( + [df1.resample("H").mean(), df2.resample("H").mean()], sort=True + ) + expected = DataFrame( + {"a": [1, 2, 3] + [np.nan] * 3, "b": [np.nan] * 3 + [1, 2, 3]}, + index=idx1.append(idx1), + ) + tm.assert_frame_equal(result, expected) + + def test_concat_datetimeindex_freq(self): + # GH 3232 + # Monotonic index result + dr = pd.date_range("01-Jan-2013", periods=100, freq="50L", tz="UTC") + data = list(range(100)) + expected = DataFrame(data, index=dr) + result = pd.concat([expected[:50], expected[50:]]) + tm.assert_frame_equal(result, expected) + + # Non-monotonic index result + result = pd.concat([expected[50:], expected[:50]]) + expected = DataFrame(data[50:] + data[:50], index=dr[50:].append(dr[:50])) + expected.index._data.freq = None + tm.assert_frame_equal(result, expected) + + def test_concat_multiindex_datetime_object_index(self): + # https://github.com/pandas-dev/pandas/issues/11058 + s = Series( + ["a", "b"], + index=MultiIndex.from_arrays( + [ + [1, 2], + Index([dt.date(2013, 1, 1), dt.date(2014, 1, 1)], dtype="object"), + ], + names=["first", "second"], + ), + ) + s2 = Series( + ["a", "b"], + index=MultiIndex.from_arrays( + [ + [1, 2], + Index([dt.date(2013, 1, 1), dt.date(2015, 1, 1)], dtype="object"), + ], + names=["first", "second"], + ), + ) + expected = DataFrame( + [["a", "a"], ["b", np.nan], [np.nan, "b"]], + index=MultiIndex.from_arrays( + [ + [1, 2, 2], + DatetimeIndex( + ["2013-01-01", "2014-01-01", "2015-01-01"], + dtype="datetime64[ns]", + freq=None, + ), + ], + names=["first", "second"], + ), + ) + result = concat([s, s2], axis=1) + tm.assert_frame_equal(result, expected) + + def test_concat_NaT_series(self): + # GH 11693 + # test for merging NaT series with datetime series. + x = Series( + date_range("20151124 08:00", "20151124 09:00", freq="1h", tz="US/Eastern") + ) + y = Series(pd.NaT, index=[0, 1], dtype="datetime64[ns, US/Eastern]") + expected = Series([x[0], x[1], pd.NaT, pd.NaT]) + + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + # all NaT with tz + expected = Series(pd.NaT, index=range(4), dtype="datetime64[ns, US/Eastern]") + result = pd.concat([y, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + # without tz + x = Series(pd.date_range("20151124 08:00", "20151124 09:00", freq="1h")) + y = Series(pd.date_range("20151124 10:00", "20151124 11:00", freq="1h")) + y[:] = pd.NaT + expected = Series([x[0], x[1], pd.NaT, pd.NaT]) + result = pd.concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + # all NaT without tz + x[:] = pd.NaT + expected = Series(pd.NaT, index=range(4), dtype="datetime64[ns]") + result = pd.concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("tz", [None, "UTC"]) + def test_concat_NaT_dataframes(self, tz): + # GH 12396 + + first = DataFrame([[pd.NaT], [pd.NaT]]) + first = first.apply(lambda x: x.dt.tz_localize(tz)) + second = DataFrame( + [[pd.Timestamp("2015/01/01", tz=tz)], [pd.Timestamp("2016/01/01", tz=tz)]], + index=[2, 3], + ) + expected = DataFrame( + [ + pd.NaT, + pd.NaT, + pd.Timestamp("2015/01/01", tz=tz), + pd.Timestamp("2016/01/01", tz=tz), + ] + ) + + result = pd.concat([first, second], axis=0) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("tz1", [None, "UTC"]) + @pytest.mark.parametrize("tz2", [None, "UTC"]) + @pytest.mark.parametrize("s", [pd.NaT, pd.Timestamp("20150101")]) + def test_concat_NaT_dataframes_all_NaT_axis_0(self, tz1, tz2, s): + # GH 12396 + + # tz-naive + first = DataFrame([[pd.NaT], [pd.NaT]]).apply(lambda x: x.dt.tz_localize(tz1)) + second = DataFrame([s]).apply(lambda x: x.dt.tz_localize(tz2)) + + result = pd.concat([first, second], axis=0) + expected = DataFrame(Series([pd.NaT, pd.NaT, s], index=[0, 1, 0])) + expected = expected.apply(lambda x: x.dt.tz_localize(tz2)) + if tz1 != tz2: + expected = expected.astype(object) + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("tz1", [None, "UTC"]) + @pytest.mark.parametrize("tz2", [None, "UTC"]) + def test_concat_NaT_dataframes_all_NaT_axis_1(self, tz1, tz2): + # GH 12396 + + first = DataFrame(Series([pd.NaT, pd.NaT]).dt.tz_localize(tz1)) + second = DataFrame(Series([pd.NaT]).dt.tz_localize(tz2), columns=[1]) + expected = DataFrame( + { + 0: Series([pd.NaT, pd.NaT]).dt.tz_localize(tz1), + 1: Series([pd.NaT, pd.NaT]).dt.tz_localize(tz2), + } + ) + result = pd.concat([first, second], axis=1) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("tz1", [None, "UTC"]) + @pytest.mark.parametrize("tz2", [None, "UTC"]) + def test_concat_NaT_series_dataframe_all_NaT(self, tz1, tz2): + # GH 12396 + + # tz-naive + first = Series([pd.NaT, pd.NaT]).dt.tz_localize(tz1) + second = DataFrame( + [ + [pd.Timestamp("2015/01/01", tz=tz2)], + [pd.Timestamp("2016/01/01", tz=tz2)], + ], + index=[2, 3], + ) + + expected = DataFrame( + [ + pd.NaT, + pd.NaT, + pd.Timestamp("2015/01/01", tz=tz2), + pd.Timestamp("2016/01/01", tz=tz2), + ] + ) + if tz1 != tz2: + expected = expected.astype(object) + + result = pd.concat([first, second]) + tm.assert_frame_equal(result, expected) + + +class TestTimezoneConcat: + def test_concat_tz_series(self): + # gh-11755: tz and no tz + x = Series(date_range("20151124 08:00", "20151124 09:00", freq="1h", tz="UTC")) + y = Series(date_range("2012-01-01", "2012-01-02")) + expected = Series([x[0], x[1], y[0], y[1]], dtype="object") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + # gh-11887: concat tz and object + x = Series(date_range("20151124 08:00", "20151124 09:00", freq="1h", tz="UTC")) + y = Series(["a", "b"]) + expected = Series([x[0], x[1], y[0], y[1]], dtype="object") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + # see gh-12217 and gh-12306 + # Concatenating two UTC times + first = DataFrame([[datetime(2016, 1, 1)]]) + first[0] = first[0].dt.tz_localize("UTC") + + second = DataFrame([[datetime(2016, 1, 2)]]) + second[0] = second[0].dt.tz_localize("UTC") + + result = pd.concat([first, second]) + assert result[0].dtype == "datetime64[ns, UTC]" + + # Concatenating two London times + first = DataFrame([[datetime(2016, 1, 1)]]) + first[0] = first[0].dt.tz_localize("Europe/London") + + second = DataFrame([[datetime(2016, 1, 2)]]) + second[0] = second[0].dt.tz_localize("Europe/London") + + result = pd.concat([first, second]) + assert result[0].dtype == "datetime64[ns, Europe/London]" + + # Concatenating 2+1 London times + first = DataFrame([[datetime(2016, 1, 1)], [datetime(2016, 1, 2)]]) + first[0] = first[0].dt.tz_localize("Europe/London") + + second = DataFrame([[datetime(2016, 1, 3)]]) + second[0] = second[0].dt.tz_localize("Europe/London") + + result = pd.concat([first, second]) + assert result[0].dtype == "datetime64[ns, Europe/London]" + + # Concat'ing 1+2 London times + first = DataFrame([[datetime(2016, 1, 1)]]) + first[0] = first[0].dt.tz_localize("Europe/London") + + second = DataFrame([[datetime(2016, 1, 2)], [datetime(2016, 1, 3)]]) + second[0] = second[0].dt.tz_localize("Europe/London") + + result = pd.concat([first, second]) + assert result[0].dtype == "datetime64[ns, Europe/London]" + + def test_concat_tz_series_tzlocal(self): + # see gh-13583 + x = [ + pd.Timestamp("2011-01-01", tz=dateutil.tz.tzlocal()), + pd.Timestamp("2011-02-01", tz=dateutil.tz.tzlocal()), + ] + y = [ + pd.Timestamp("2012-01-01", tz=dateutil.tz.tzlocal()), + pd.Timestamp("2012-02-01", tz=dateutil.tz.tzlocal()), + ] + + result = concat([Series(x), Series(y)], ignore_index=True) + tm.assert_series_equal(result, Series(x + y)) + assert result.dtype == "datetime64[ns, tzlocal()]" + + def test_concat_tz_series_with_datetimelike(self): + # see gh-12620: tz and timedelta + x = [ + pd.Timestamp("2011-01-01", tz="US/Eastern"), + pd.Timestamp("2011-02-01", tz="US/Eastern"), + ] + y = [pd.Timedelta("1 day"), pd.Timedelta("2 day")] + result = concat([Series(x), Series(y)], ignore_index=True) + tm.assert_series_equal(result, Series(x + y, dtype="object")) + + # tz and period + y = [pd.Period("2011-03", freq="M"), pd.Period("2011-04", freq="M")] + result = concat([Series(x), Series(y)], ignore_index=True) + tm.assert_series_equal(result, Series(x + y, dtype="object")) + + def test_concat_tz_frame(self): + df2 = DataFrame( + dict( + A=pd.Timestamp("20130102", tz="US/Eastern"), + B=pd.Timestamp("20130603", tz="CET"), + ), + index=range(5), + ) + + # concat + df3 = pd.concat([df2.A.to_frame(), df2.B.to_frame()], axis=1) + tm.assert_frame_equal(df2, df3) + + def test_concat_multiple_tzs(self): + # GH#12467 + # combining datetime tz-aware and naive DataFrames + ts1 = Timestamp("2015-01-01", tz=None) + ts2 = Timestamp("2015-01-01", tz="UTC") + ts3 = Timestamp("2015-01-01", tz="EST") + + df1 = DataFrame(dict(time=[ts1])) + df2 = DataFrame(dict(time=[ts2])) + df3 = DataFrame(dict(time=[ts3])) + + results = pd.concat([df1, df2]).reset_index(drop=True) + expected = DataFrame(dict(time=[ts1, ts2]), dtype=object) + tm.assert_frame_equal(results, expected) + + results = pd.concat([df1, df3]).reset_index(drop=True) + expected = DataFrame(dict(time=[ts1, ts3]), dtype=object) + tm.assert_frame_equal(results, expected) + + results = pd.concat([df2, df3]).reset_index(drop=True) + expected = DataFrame(dict(time=[ts2, ts3])) + tm.assert_frame_equal(results, expected) + + def test_concat_multiindex_with_tz(self): + # GH 6606 + df = DataFrame( + { + "dt": [ + datetime(2014, 1, 1), + datetime(2014, 1, 2), + datetime(2014, 1, 3), + ], + "b": ["A", "B", "C"], + "c": [1, 2, 3], + "d": [4, 5, 6], + } + ) + df["dt"] = df["dt"].apply(lambda d: Timestamp(d, tz="US/Pacific")) + df = df.set_index(["dt", "b"]) + + exp_idx1 = DatetimeIndex( + ["2014-01-01", "2014-01-02", "2014-01-03"] * 2, tz="US/Pacific", name="dt" + ) + exp_idx2 = Index(["A", "B", "C"] * 2, name="b") + exp_idx = MultiIndex.from_arrays([exp_idx1, exp_idx2]) + expected = DataFrame( + {"c": [1, 2, 3] * 2, "d": [4, 5, 6] * 2}, index=exp_idx, columns=["c", "d"] + ) + + result = concat([df, df]) + tm.assert_frame_equal(result, expected) + + def test_concat_tz_not_aligned(self): + # GH#22796 + ts = pd.to_datetime([1, 2]).tz_localize("UTC") + a = DataFrame({"A": ts}) + b = DataFrame({"A": ts, "B": ts}) + result = pd.concat([a, b], sort=True, ignore_index=True) + expected = DataFrame( + {"A": list(ts) + list(ts), "B": [pd.NaT, pd.NaT] + list(ts)} + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "t1", + [ + "2015-01-01", + pytest.param( + pd.NaT, + marks=pytest.mark.xfail( + reason="GH23037 incorrect dtype when concatenating" + ), + ), + ], + ) + def test_concat_tz_NaT(self, t1): + # GH#22796 + # Concating tz-aware multicolumn DataFrames + ts1 = Timestamp(t1, tz="UTC") + ts2 = Timestamp("2015-01-01", tz="UTC") + ts3 = Timestamp("2015-01-01", tz="UTC") + + df1 = DataFrame([[ts1, ts2]]) + df2 = DataFrame([[ts3]]) + + result = pd.concat([df1, df2]) + expected = DataFrame([[ts1, ts2], [ts3, pd.NaT]], index=[0, 0]) + + tm.assert_frame_equal(result, expected) + + +class TestPeriodConcat: + def test_concat_period_series(self): + x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) + y = Series(pd.PeriodIndex(["2015-10-01", "2016-01-01"], freq="D")) + expected = Series([x[0], x[1], y[0], y[1]], dtype="Period[D]") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + + def test_concat_period_multiple_freq_series(self): + x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) + y = Series(pd.PeriodIndex(["2015-10-01", "2016-01-01"], freq="M")) + expected = Series([x[0], x[1], y[0], y[1]], dtype="object") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + assert result.dtype == "object" + + def test_concat_period_other_series(self): + x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) + y = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="M")) + expected = Series([x[0], x[1], y[0], y[1]], dtype="object") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + assert result.dtype == "object" + + # non-period + x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) + y = Series(pd.DatetimeIndex(["2015-11-01", "2015-12-01"])) + expected = Series([x[0], x[1], y[0], y[1]], dtype="object") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + assert result.dtype == "object" + + x = Series(pd.PeriodIndex(["2015-11-01", "2015-12-01"], freq="D")) + y = Series(["A", "B"]) + expected = Series([x[0], x[1], y[0], y[1]], dtype="object") + result = concat([x, y], ignore_index=True) + tm.assert_series_equal(result, expected) + assert result.dtype == "object"
* created test_datetime.py and split datetime/timezone/period related tests - [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37368
2020-10-23T19:31:48Z
2020-10-23T20:41:13Z
2020-10-23T20:41:13Z
2020-10-23T20:42:21Z
BUG/TST: Fix infer_dtype for Period array-likes and general ExtensionArrays
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 2824a10de1d47..99ae60859b68c 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -448,6 +448,8 @@ ExtensionArray Other ^^^^^ - Bug in :class:`Index` constructor sometimes silently ignorning a specified ``dtype`` (:issue:`38879`) +- Bug in :func:`pandas.api.types.infer_dtype` not recognizing Series, Index or array with a period dtype (:issue:`23553`) +- Bug in :func:`pandas.api.types.infer_dtype` raising an error for general :class:`.ExtensionArray` objects. It will now return ``"unknown-array"`` instead of raising (:issue:`37367`) - Bug in constructing a :class:`Series` from a list and a :class:`PandasDtype` (:issue:`39357`) - Bug in :class:`Styler` which caused CSS to duplicate on multiple renders. (:issue:`39395`) - ``inspect.getmembers(Series)`` no longer raises an ``AbstractMethodError`` (:issue:`38782`) diff --git a/pandas/_libs/lib.pyx b/pandas/_libs/lib.pyx index 6793ea0ab3bc2..3a11e7fbbdf33 100644 --- a/pandas/_libs/lib.pyx +++ b/pandas/_libs/lib.pyx @@ -69,6 +69,7 @@ from pandas._libs cimport util from pandas._libs.util cimport INT64_MAX, INT64_MIN, UINT64_MAX, is_nan from pandas._libs.tslib import array_to_datetime +from pandas._libs.tslibs.period import Period from pandas._libs.missing cimport ( C_NA, @@ -1082,6 +1083,7 @@ _TYPE_MAP = { "timedelta64[ns]": "timedelta64", "m": "timedelta64", "interval": "interval", + Period: "period", } # types only exist on certain platform @@ -1233,8 +1235,8 @@ cdef object _try_infer_map(object dtype): cdef: object val str attr - for attr in ["name", "kind", "base"]: - val = getattr(dtype, attr) + for attr in ["name", "kind", "base", "type"]: + val = getattr(dtype, attr, None) if val in _TYPE_MAP: return _TYPE_MAP[val] return None @@ -1275,6 +1277,7 @@ def infer_dtype(value: object, skipna: bool = True) -> str: - time - period - mixed + - unknown-array Raises ------ @@ -1287,6 +1290,9 @@ def infer_dtype(value: object, skipna: bool = True) -> str: specialized - 'mixed-integer-float' are floats and integers - 'mixed-integer' are integers mixed with non-integers + - 'unknown-array' is the catchall for something that *is* an array (has + a dtype attribute), but has a dtype unknown to pandas (e.g. external + extension array) Examples -------- @@ -1355,12 +1361,10 @@ def infer_dtype(value: object, skipna: bool = True) -> str: # e.g. categoricals dtype = value.dtype if not isinstance(dtype, np.dtype): - value = _try_infer_map(value.dtype) - if value is not None: - return value - - # its ndarray-like but we can't handle - raise ValueError(f"cannot infer type for {type(value)}") + inferred = _try_infer_map(value.dtype) + if inferred is not None: + return inferred + return "unknown-array" # Unwrap Series/Index values = np.asarray(value) diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 067fff3e0a744..0e6ffa637f1ae 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -202,11 +202,7 @@ def _validate(data): if isinstance(values.dtype, StringDtype): return "string" - try: - inferred_dtype = lib.infer_dtype(values, skipna=True) - except ValueError: - # GH#27571 mostly occurs with ExtensionArray - inferred_dtype = None + inferred_dtype = lib.infer_dtype(values, skipna=True) if inferred_dtype not in allowed_types: raise AttributeError("Can only use .str accessor with string values!") diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index 415fe0309b073..0f4cef772458f 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -891,6 +891,19 @@ def test_infer_dtype_period(self): arr = np.array([Period("2011-01", freq="D"), Period("2011-02", freq="M")]) assert lib.infer_dtype(arr, skipna=True) == "period" + @pytest.mark.parametrize("klass", [pd.array, pd.Series, pd.Index]) + @pytest.mark.parametrize("skipna", [True, False]) + def test_infer_dtype_period_array(self, klass, skipna): + # https://github.com/pandas-dev/pandas/issues/23553 + values = klass( + [ + Period("2011-01-01", freq="D"), + Period("2011-01-02", freq="D"), + pd.NaT, + ] + ) + assert lib.infer_dtype(values, skipna=skipna) == "period" + def test_infer_dtype_period_mixed(self): arr = np.array( [Period("2011-01", freq="M"), np.datetime64("nat")], dtype=object diff --git a/pandas/tests/extension/base/dtype.py b/pandas/tests/extension/base/dtype.py index 5e4d23e91925a..b63af0c22b450 100644 --- a/pandas/tests/extension/base/dtype.py +++ b/pandas/tests/extension/base/dtype.py @@ -4,7 +4,7 @@ import pytest import pandas as pd -from pandas.api.types import is_object_dtype, is_string_dtype +from pandas.api.types import infer_dtype, is_object_dtype, is_string_dtype from pandas.tests.extension.base.base import BaseExtensionTests @@ -123,3 +123,11 @@ def test_get_common_dtype(self, dtype): # still testing as good practice to have this working (and it is the # only case we can test in general) assert dtype._get_common_dtype([dtype]) == dtype + + @pytest.mark.parametrize("skipna", [True, False]) + def test_infer_dtype(self, data, data_missing, skipna): + # only testing that this works without raising an error + res = infer_dtype(data, skipna=skipna) + assert isinstance(res, str) + res = infer_dtype(data_missing, skipna=skipna) + assert isinstance(res, str) diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index 16278ec1ccc53..23b1ce250a5e5 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -7,6 +7,7 @@ import pandas as pd import pandas._testing as tm +from pandas.api.types import infer_dtype from pandas.tests.extension import base from pandas.tests.extension.decimal.array import ( DecimalArray, @@ -120,6 +121,13 @@ class TestDtype(BaseDecimal, base.BaseDtypeTests): def test_hashable(self, dtype): pass + @pytest.mark.parametrize("skipna", [True, False]) + def test_infer_dtype(self, data, data_missing, skipna): + # here overriding base test to ensure we fall back to return + # "unknown-array" for an EA pandas doesn't know + assert infer_dtype(data, skipna=skipna) == "unknown-array" + assert infer_dtype(data_missing, skipna=skipna) == "unknown-array" + class TestInterface(BaseDecimal, base.BaseInterfaceTests): pass diff --git a/pandas/tests/io/test_parquet.py b/pandas/tests/io/test_parquet.py index 5adb3730a8c86..c72363b088a5c 100644 --- a/pandas/tests/io/test_parquet.py +++ b/pandas/tests/io/test_parquet.py @@ -938,7 +938,8 @@ def test_unsupported(self, fp): # period df = pd.DataFrame({"a": pd.period_range("2013", freq="M", periods=3)}) - self.check_error_on_write(df, fp, ValueError, "cannot infer type for") + # error from fastparquet -> don't check exact error message + self.check_error_on_write(df, fp, ValueError, None) # mixed df = pd.DataFrame({"a": ["a", 1, 2.0]})
Closes #23553 In addition, I also changed to let infer_dtype fall back to inferring from the scalar elements if the array-like is not recognized directly (now it raises an error, which doesn't seem very useful?)
https://api.github.com/repos/pandas-dev/pandas/pulls/37367
2020-10-23T19:07:37Z
2021-02-12T17:45:26Z
2021-02-12T17:45:26Z
2021-02-12T17:47:22Z
TYP: DatetimeIndex, TimedeltaIndex
diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 863880e222b5d..2c422b4c551b6 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -1,13 +1,13 @@ """ Base and utility classes for tseries type pandas objects. """ -from datetime import datetime, tzinfo -from typing import TYPE_CHECKING, Any, List, Optional, TypeVar, Union, cast +from datetime import datetime +from typing import TYPE_CHECKING, Any, List, Optional, Tuple, TypeVar, Union, cast import numpy as np from pandas._libs import NaT, Timedelta, iNaT, join as libjoin, lib -from pandas._libs.tslibs import BaseOffset, Resolution, Tick, timezones +from pandas._libs.tslibs import BaseOffset, Resolution, Tick from pandas._typing import Callable, Label from pandas.compat.numpy import function as nv from pandas.errors import AbstractMethodError @@ -672,8 +672,6 @@ class DatetimeTimedeltaMixin(DatetimeIndexOpsMixin, Int64Index): but not PeriodIndex """ - tz: Optional[tzinfo] - # Compat for frequency inference, see GH#23789 _is_monotonic_increasing = Index.is_monotonic_increasing _is_monotonic_decreasing = Index.is_monotonic_decreasing @@ -931,22 +929,9 @@ def join( sort=sort, ) - def _maybe_utc_convert(self, other): - this = self - if not hasattr(self, "tz"): - return this, other - - if isinstance(other, type(self)): - if self.tz is not None: - if other.tz is None: - raise TypeError("Cannot join tz-naive with tz-aware DatetimeIndex") - elif other.tz is not None: - raise TypeError("Cannot join tz-naive with tz-aware DatetimeIndex") - - if not timezones.tz_compare(self.tz, other.tz): - this = self.tz_convert("UTC") - other = other.tz_convert("UTC") - return this, other + def _maybe_utc_convert(self: _T, other: Index) -> Tuple[_T, Index]: + # Overridden by DatetimeIndex + return self, other # -------------------------------------------------------------------- # List-Like Methods diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 11417e0b3317e..ce6f2cbdf5eaa 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -1,12 +1,18 @@ from datetime import date, datetime, time, timedelta, tzinfo import operator -from typing import TYPE_CHECKING, Optional +from typing import TYPE_CHECKING, Optional, Tuple import warnings import numpy as np from pandas._libs import NaT, Period, Timestamp, index as libindex, lib -from pandas._libs.tslibs import Resolution, ints_to_pydatetime, parsing, to_offset +from pandas._libs.tslibs import ( + Resolution, + ints_to_pydatetime, + parsing, + timezones, + to_offset, +) from pandas._libs.tslibs.offsets import prefix_mapping from pandas._typing import DtypeObj, Label from pandas.errors import InvalidIndexError @@ -411,6 +417,21 @@ def union_many(self, others): return this.rename(res_name) return this + def _maybe_utc_convert(self, other: Index) -> Tuple["DatetimeIndex", Index]: + this = self + + if isinstance(other, DatetimeIndex): + if self.tz is not None: + if other.tz is None: + raise TypeError("Cannot join tz-naive with tz-aware DatetimeIndex") + elif other.tz is not None: + raise TypeError("Cannot join tz-naive with tz-aware DatetimeIndex") + + if not timezones.tz_compare(self.tz, other.tz): + this = self.tz_convert("UTC") + other = other.tz_convert("UTC") + return this, other + # -------------------------------------------------------------------- def _get_time_micros(self): diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 20c0297448494..2110a2d400be8 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -2177,7 +2177,7 @@ def TextParser(*args, **kwds): return TextFileReader(*args, **kwds) -def count_empty_vals(vals): +def count_empty_vals(vals) -> int: return sum(1 for v in vals if v == "" or v is None)
Better alternative to parts of #37224
https://api.github.com/repos/pandas-dev/pandas/pulls/37365
2020-10-23T16:08:47Z
2020-10-29T00:57:47Z
2020-10-29T00:57:47Z
2020-10-29T02:00:11Z
Backport PR #37302 on branch 1.1.x (BUG: Allow empty chunksize in stata reader when using iterator)
diff --git a/doc/source/whatsnew/v1.1.4.rst b/doc/source/whatsnew/v1.1.4.rst index f641e7ba4c6f7..18ba5fd46696a 100644 --- a/doc/source/whatsnew/v1.1.4.rst +++ b/doc/source/whatsnew/v1.1.4.rst @@ -22,6 +22,7 @@ Fixed regressions - Fixed regression in :class:`RollingGroupby` causing a segmentation fault with Index of dtype object (:issue:`36727`) - Fixed regression in :class:`PeriodDtype` comparing both equal and unequal to its string representation (:issue:`37265`) - Fixed regression in certain offsets (:meth:`pd.offsets.Day() <pandas.tseries.offsets.Day>` and below) no longer being hashable (:issue:`37267`) +- Fixed regression in :class:`StataReader` which required ``chunksize`` to be manually set when using an iterator to read a dataset (:issue:`37280`) .. --------------------------------------------------------------------------- diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 7677d8a94d521..8e1c72d4aaa7e 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -477,7 +477,7 @@ class PossiblePrecisionLoss(Warning): precision_loss_doc = """ -Column converted from %s to %s, and some data are outside of the lossless +Column converted from {0} to {1}, and some data are outside of the lossless conversion range. This may result in a loss of precision in the saved data. """ @@ -551,7 +551,7 @@ def _cast_to_stata_types(data: DataFrame) -> DataFrame: object in a DataFrame. """ ws = "" - # original, if small, if large + # original, if small, if large conversion_data = ( (np.bool_, np.int8, np.int8), (np.uint8, np.int8, np.int16), @@ -571,7 +571,7 @@ def _cast_to_stata_types(data: DataFrame) -> DataFrame: dtype = c_data[1] else: dtype = c_data[2] - if c_data[2] == np.float64: # Warn if necessary + if c_data[2] == np.int64: # Warn if necessary if data[col].max() >= 2 ** 53: ws = precision_loss_doc.format("uint64", "float64") @@ -635,12 +635,12 @@ def __init__(self, catarray: Series, encoding: str = "latin-1"): self.value_labels = list(zip(np.arange(len(categories)), categories)) self.value_labels.sort(key=lambda x: x[0]) self.text_len = 0 - self.off: List[int] = [] - self.val: List[int] = [] self.txt: List[bytes] = [] self.n = 0 # Compute lengths and setup lists of offsets and labels + offsets: List[int] = [] + values: List[int] = [] for vl in self.value_labels: category = vl[1] if not isinstance(category, str): @@ -650,9 +650,9 @@ def __init__(self, catarray: Series, encoding: str = "latin-1"): ValueLabelTypeMismatch, ) category = category.encode(encoding) - self.off.append(self.text_len) + offsets.append(self.text_len) self.text_len += len(category) + 1 # +1 for the padding - self.val.append(vl[0]) + values.append(vl[0]) self.txt.append(category) self.n += 1 @@ -663,8 +663,8 @@ def __init__(self, catarray: Series, encoding: str = "latin-1"): ) # Ensure int32 - self.off = np.array(self.off, dtype=np.int32) - self.val = np.array(self.val, dtype=np.int32) + self.off = np.array(offsets, dtype=np.int32) + self.val = np.array(values, dtype=np.int32) # Total length self.len = 4 + 4 + 4 * self.n + 4 * self.n + self.text_len @@ -876,23 +876,23 @@ def __init__(self): # with a label, but the underlying variable is -127 to 100 # we're going to drop the label and cast to int self.DTYPE_MAP = dict( - list(zip(range(1, 245), ["a" + str(i) for i in range(1, 245)])) + list(zip(range(1, 245), [np.dtype("a" + str(i)) for i in range(1, 245)])) + [ - (251, np.int8), - (252, np.int16), - (253, np.int32), - (254, np.float32), - (255, np.float64), + (251, np.dtype(np.int8)), + (252, np.dtype(np.int16)), + (253, np.dtype(np.int32)), + (254, np.dtype(np.float32)), + (255, np.dtype(np.float64)), ] ) self.DTYPE_MAP_XML = dict( [ - (32768, np.uint8), # Keys to GSO - (65526, np.float64), - (65527, np.float32), - (65528, np.int32), - (65529, np.int16), - (65530, np.int8), + (32768, np.dtype(np.uint8)), # Keys to GSO + (65526, np.dtype(np.float64)), + (65527, np.dtype(np.float32)), + (65528, np.dtype(np.int32)), + (65529, np.dtype(np.int16)), + (65530, np.dtype(np.int8)), ] ) self.TYPE_MAP = list(range(251)) + list("bhlfd") @@ -1050,9 +1050,10 @@ def __init__( self._order_categoricals = order_categoricals self._encoding = "" self._chunksize = chunksize - if self._chunksize is not None and ( - not isinstance(chunksize, int) or chunksize <= 0 - ): + self._using_iterator = False + if self._chunksize is None: + self._chunksize = 1 + elif not isinstance(chunksize, int) or chunksize <= 0: raise ValueError("chunksize must be a positive integer when set.") # State variables for the file @@ -1062,7 +1063,7 @@ def __init__( self._column_selector_set = False self._value_labels_read = False self._data_read = False - self._dtype = None + self._dtype: Optional[np.dtype] = None self._lines_read = 0 self._native_byteorder = _set_endianness(sys.byteorder) @@ -1195,7 +1196,7 @@ def _read_new_header(self) -> None: # Get data type information, works for versions 117-119. def _get_dtypes( self, seek_vartypes: int - ) -> Tuple[List[Union[int, str]], List[Union[int, np.dtype]]]: + ) -> Tuple[List[Union[int, str]], List[Union[str, np.dtype]]]: self.path_or_buf.seek(seek_vartypes) raw_typlist = [ @@ -1519,11 +1520,8 @@ def _read_strls(self) -> None: self.GSO[str(v_o)] = decoded_va def __next__(self) -> DataFrame: - if self._chunksize is None: - raise ValueError( - "chunksize must be set to a positive integer to use as an iterator." - ) - return self.read(nrows=self._chunksize or 1) + self._using_iterator = True + return self.read(nrows=self._chunksize) def get_chunk(self, size: Optional[int] = None) -> DataFrame: """ @@ -1692,11 +1690,15 @@ def any_startswith(x: str) -> bool: convert = False for col in data: dtype = data[col].dtype - if dtype in (np.float16, np.float32): - dtype = np.float64 + if dtype in (np.dtype(np.float16), np.dtype(np.float32)): + dtype = np.dtype(np.float64) convert = True - elif dtype in (np.int8, np.int16, np.int32): - dtype = np.int64 + elif dtype in ( + np.dtype(np.int8), + np.dtype(np.int16), + np.dtype(np.int32), + ): + dtype = np.dtype(np.int64) convert = True retyped_data.append((col, data[col].astype(dtype))) if convert: @@ -1807,14 +1809,14 @@ def _do_convert_categoricals( keys = np.array(list(vl.keys())) column = data[col] key_matches = column.isin(keys) - if self._chunksize is not None and key_matches.all(): - initial_categories = keys + if self._using_iterator and key_matches.all(): + initial_categories: Optional[np.ndarray] = keys # If all categories are in the keys and we are iterating, # use the same keys for all chunks. If some are missing # value labels, then we will fall back to the categories # varying across chunks. else: - if self._chunksize is not None: + if self._using_iterator: # warn is using an iterator warnings.warn( categorical_conversion_warning, CategoricalConversionWarning @@ -2010,7 +2012,7 @@ def _convert_datetime_to_stata_type(fmt: str) -> np.dtype: "ty", "%ty", ]: - return np.float64 # Stata expects doubles for SIFs + return np.dtype(np.float64) # Stata expects doubles for SIFs else: raise NotImplementedError(f"Format {fmt} not implemented") diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 6d7fec803a8e0..9788602242128 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -1966,9 +1966,6 @@ def test_iterator_errors(dirpath): StataReader(dta_file, chunksize=0) with pytest.raises(ValueError, match="chunksize must be a positive"): StataReader(dta_file, chunksize="apple") - with pytest.raises(ValueError, match="chunksize must be set to a positive"): - with StataReader(dta_file) as reader: - reader.__next__() def test_iterator_value_labels(): @@ -1983,3 +1980,18 @@ def test_iterator_value_labels(): for i in range(2): tm.assert_index_equal(chunk.dtypes[i].categories, expected) tm.assert_frame_equal(chunk, df.iloc[j * 100 : (j + 1) * 100]) + + +def test_precision_loss(): + df = DataFrame( + [[sum(2 ** i for i in range(60)), sum(2 ** i for i in range(52))]], + columns=["big", "little"], + ) + with tm.ensure_clean() as path: + with tm.assert_produces_warning(PossiblePrecisionLoss): + df.to_stata(path, write_index=False) + reread = read_stata(path) + expected_dt = Series([np.float64, np.float64], index=["big", "little"]) + tm.assert_series_equal(reread.dtypes, expected_dt) + assert reread.loc[0, "little"] == df.loc[0, "little"] + assert reread.loc[0, "big"] == float(df.loc[0, "big"])
Backport PR #37302: BUG: Allow empty chunksize in stata reader when using iterator
https://api.github.com/repos/pandas-dev/pandas/pulls/37364
2020-10-23T12:36:24Z
2020-10-24T16:11:09Z
2020-10-24T16:11:09Z
2020-10-24T16:11:09Z
REGR: Notebook (html) repr of DataFrame no longer follows min_rows/max_rows settings
diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index e4bd1eddbc5f8..2fae18bd76657 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -639,20 +639,31 @@ def _calc_max_cols_fitted(self) -> Optional[int]: def _calc_max_rows_fitted(self) -> Optional[int]: """Number of rows with data fitting the screen.""" - if not self._is_in_terminal(): - return self.max_rows + max_rows: Optional[int] - _, height = get_terminal_size() - if self.max_rows == 0: - # rows available to fill with actual data - return height - self._get_number_of_auxillary_rows() + if self._is_in_terminal(): + _, height = get_terminal_size() + if self.max_rows == 0: + # rows available to fill with actual data + return height - self._get_number_of_auxillary_rows() - max_rows: Optional[int] - if self._is_screen_short(height): - max_rows = height + if self._is_screen_short(height): + max_rows = height + else: + max_rows = self.max_rows else: max_rows = self.max_rows + return self._adjust_max_rows(max_rows) + + def _adjust_max_rows(self, max_rows: Optional[int]) -> Optional[int]: + """Adjust max_rows using display logic. + + See description here: + https://pandas.pydata.org/docs/dev/user_guide/options.html#frequently-used-options + + GH #37359 + """ if max_rows: if (len(self.frame) > max_rows) and self.min_rows: # if truncated, set max_rows showed to min_rows diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index b3cf7a6828808..ce9aa16e57f1c 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -2029,6 +2029,35 @@ def test_period(self): ) assert str(df) == exp + @pytest.mark.parametrize( + "length, max_rows, min_rows, expected", + [ + (10, 10, 10, 10), + (10, 10, None, 10), + (10, 8, None, 8), + (20, 30, 10, 30), # max_rows > len(frame), hence max_rows + (50, 30, 10, 10), # max_rows < len(frame), hence min_rows + (100, 60, 10, 10), # same + (60, 60, 10, 60), # edge case + (61, 60, 10, 10), # edge case + ], + ) + def test_max_rows_fitted(self, length, min_rows, max_rows, expected): + """Check that display logic is correct. + + GH #37359 + + See description here: + https://pandas.pydata.org/docs/dev/user_guide/options.html#frequently-used-options + """ + formatter = fmt.DataFrameFormatter( + DataFrame(np.random.rand(length, 3)), + max_rows=max_rows, + min_rows=min_rows, + ) + result = formatter.max_rows_fitted + assert result == expected + def gen_series_formatting(): s1 = Series(["a"] * 100)
- [ ] closes #37359 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Fix display logic in number of rows, explained here https://pandas.pydata.org/docs/dev/user_guide/options.html#frequently-used-options
https://api.github.com/repos/pandas-dev/pandas/pulls/37363
2020-10-23T11:16:39Z
2020-11-13T05:45:48Z
2020-11-13T05:45:48Z
2020-11-13T05:53:19Z
CI autoupdate pre-commit versions
diff --git a/.github/workflows/autoupdate-pre-commit-config.yml b/.github/workflows/autoupdate-pre-commit-config.yml new file mode 100644 index 0000000000000..42d6ae6606442 --- /dev/null +++ b/.github/workflows/autoupdate-pre-commit-config.yml @@ -0,0 +1,33 @@ +name: "Update pre-commit config" + +on: + schedule: + - cron: "0 7 * * 1" # At 07:00 on each Monday. + workflow_dispatch: + +jobs: + update-pre-commit: + if: github.repository_owner == 'pandas-dev' + name: Autoupdate pre-commit config + runs-on: ubuntu-latest + steps: + - name: Set up Python + uses: actions/setup-python@v2 + - name: Cache multiple paths + uses: actions/cache@v2 + with: + path: | + ~/.cache/pre-commit + ~/.cache/pip + key: pre-commit-autoupdate-${{ runner.os }}-build + - name: Update pre-commit config packages + uses: technote-space/create-pr-action@v2 + with: + GITHUB_TOKEN: ${{ secrets.ACTION_TRIGGER_TOKEN }} + EXECUTE_COMMANDS: | + pip install pre-commit + pre-commit autoupdate || (exit 0); + pre-commit run -a || (exit 0); + COMMIT_MESSAGE: "⬆️ UPGRADE: Autoupdate pre-commit config" + PR_BRANCH_NAME: "pre-commit-config-update-${PR_ID}" + PR_TITLE: "⬆️ UPGRADE: Autoupdate pre-commit config" diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 1065ccff32632..b0f35087dc922 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -18,7 +18,7 @@ repos: types: [text] args: [--append-config=flake8/cython-template.cfg] - repo: https://github.com/PyCQA/isort - rev: 5.6.3 + rev: 5.6.4 hooks: - id: isort name: isort (python) @@ -26,7 +26,7 @@ repos: name: isort (cython) types: [cython] - repo: https://github.com/asottile/pyupgrade - rev: v2.7.2 + rev: v2.7.3 hooks: - id: pyupgrade args: [--py37-plus] @@ -124,7 +124,7 @@ repos: hooks: - id: yesqa - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v3.2.0 + rev: v3.3.0 hooks: - id: end-of-file-fixer exclude: ^LICENSES/|\.(html|csv|txt|svg|py)$
Rather than manually updating versions of hooks when new ones come out, we can make a GitHub action to open a PR to do this automatically every Monday. For this to work, we will need whoever owns the repo to [create an access token](https://github.com/technote-space/create-pr-action#github_token) and add it as secret `ACTION_TRIGGER_TOKEN` to the repo - see screenshot below for an example ![image](https://user-images.githubusercontent.com/33491632/96995872-c9972b00-1526-11eb-9c9f-0e38d754590c.png)
https://api.github.com/repos/pandas-dev/pandas/pulls/37362
2020-10-23T10:57:19Z
2020-10-31T23:06:13Z
2020-10-31T23:06:12Z
2020-11-01T10:32:02Z
TST: moved file test_concat.py to folder ./concat/ (#37243)
diff --git a/pandas/tests/reshape/concat/test_append.py b/pandas/tests/reshape/concat/test_append.py new file mode 100644 index 0000000000000..2f9228bc84394 --- /dev/null +++ b/pandas/tests/reshape/concat/test_append.py @@ -0,0 +1,383 @@ +import datetime as dt +from datetime import datetime +from itertools import combinations + +import dateutil +import numpy as np +import pytest + +import pandas as pd +from pandas import DataFrame, Index, Series, Timestamp, concat, isna +import pandas._testing as tm + + +@pytest.fixture(params=[True, False]) +def sort(request): + """Boolean sort keyword for concat and DataFrame.append.""" + return request.param + + +class TestAppend: + def test_append(self, sort, float_frame): + mixed_frame = float_frame.copy() + mixed_frame["foo"] = "bar" + + begin_index = float_frame.index[:5] + end_index = float_frame.index[5:] + + begin_frame = float_frame.reindex(begin_index) + end_frame = float_frame.reindex(end_index) + + appended = begin_frame.append(end_frame) + tm.assert_almost_equal(appended["A"], float_frame["A"]) + + del end_frame["A"] + partial_appended = begin_frame.append(end_frame, sort=sort) + assert "A" in partial_appended + + partial_appended = end_frame.append(begin_frame, sort=sort) + assert "A" in partial_appended + + # mixed type handling + appended = mixed_frame[:5].append(mixed_frame[5:]) + tm.assert_frame_equal(appended, mixed_frame) + + # what to test here + mixed_appended = mixed_frame[:5].append(float_frame[5:], sort=sort) + mixed_appended2 = float_frame[:5].append(mixed_frame[5:], sort=sort) + + # all equal except 'foo' column + tm.assert_frame_equal( + mixed_appended.reindex(columns=["A", "B", "C", "D"]), + mixed_appended2.reindex(columns=["A", "B", "C", "D"]), + ) + + def test_append_empty(self, float_frame): + empty = DataFrame() + + appended = float_frame.append(empty) + tm.assert_frame_equal(float_frame, appended) + assert appended is not float_frame + + appended = empty.append(float_frame) + tm.assert_frame_equal(float_frame, appended) + assert appended is not float_frame + + def test_append_overlap_raises(self, float_frame): + msg = "Indexes have overlapping values" + with pytest.raises(ValueError, match=msg): + float_frame.append(float_frame, verify_integrity=True) + + def test_append_new_columns(self): + # see gh-6129: new columns + df = DataFrame({"a": {"x": 1, "y": 2}, "b": {"x": 3, "y": 4}}) + row = Series([5, 6, 7], index=["a", "b", "c"], name="z") + expected = DataFrame( + { + "a": {"x": 1, "y": 2, "z": 5}, + "b": {"x": 3, "y": 4, "z": 6}, + "c": {"z": 7}, + } + ) + result = df.append(row) + tm.assert_frame_equal(result, expected) + + def test_append_length0_frame(self, sort): + df = DataFrame(columns=["A", "B", "C"]) + df3 = DataFrame(index=[0, 1], columns=["A", "B"]) + df5 = df.append(df3, sort=sort) + + expected = DataFrame(index=[0, 1], columns=["A", "B", "C"]) + tm.assert_frame_equal(df5, expected) + + def test_append_records(self): + arr1 = np.zeros((2,), dtype=("i4,f4,a10")) + arr1[:] = [(1, 2.0, "Hello"), (2, 3.0, "World")] + + arr2 = np.zeros((3,), dtype=("i4,f4,a10")) + arr2[:] = [(3, 4.0, "foo"), (5, 6.0, "bar"), (7.0, 8.0, "baz")] + + df1 = DataFrame(arr1) + df2 = DataFrame(arr2) + + result = df1.append(df2, ignore_index=True) + expected = DataFrame(np.concatenate((arr1, arr2))) + tm.assert_frame_equal(result, expected) + + # rewrite sort fixture, since we also want to test default of None + def test_append_sorts(self, sort): + df1 = DataFrame({"a": [1, 2], "b": [1, 2]}, columns=["b", "a"]) + df2 = DataFrame({"a": [1, 2], "c": [3, 4]}, index=[2, 3]) + + with tm.assert_produces_warning(None): + result = df1.append(df2, sort=sort) + + # for None / True + expected = DataFrame( + {"b": [1, 2, None, None], "a": [1, 2, 1, 2], "c": [None, None, 3, 4]}, + columns=["a", "b", "c"], + ) + if sort is False: + expected = expected[["b", "a", "c"]] + tm.assert_frame_equal(result, expected) + + def test_append_different_columns(self, sort): + df = DataFrame( + { + "bools": np.random.randn(10) > 0, + "ints": np.random.randint(0, 10, 10), + "floats": np.random.randn(10), + "strings": ["foo", "bar"] * 5, + } + ) + + a = df[:5].loc[:, ["bools", "ints", "floats"]] + b = df[5:].loc[:, ["strings", "ints", "floats"]] + + appended = a.append(b, sort=sort) + assert isna(appended["strings"][0:4]).all() + assert isna(appended["bools"][5:]).all() + + def test_append_many(self, sort, float_frame): + chunks = [ + float_frame[:5], + float_frame[5:10], + float_frame[10:15], + float_frame[15:], + ] + + result = chunks[0].append(chunks[1:]) + tm.assert_frame_equal(result, float_frame) + + chunks[-1] = chunks[-1].copy() + chunks[-1]["foo"] = "bar" + result = chunks[0].append(chunks[1:], sort=sort) + tm.assert_frame_equal(result.loc[:, float_frame.columns], float_frame) + assert (result["foo"][15:] == "bar").all() + assert result["foo"][:15].isna().all() + + def test_append_preserve_index_name(self): + # #980 + df1 = DataFrame(columns=["A", "B", "C"]) + df1 = df1.set_index(["A"]) + df2 = DataFrame(data=[[1, 4, 7], [2, 5, 8], [3, 6, 9]], columns=["A", "B", "C"]) + df2 = df2.set_index(["A"]) + + result = df1.append(df2) + assert result.index.name == "A" + + indexes_can_append = [ + pd.RangeIndex(3), + Index([4, 5, 6]), + Index([4.5, 5.5, 6.5]), + Index(list("abc")), + pd.CategoricalIndex("A B C".split()), + pd.CategoricalIndex("D E F".split(), ordered=True), + pd.IntervalIndex.from_breaks([7, 8, 9, 10]), + pd.DatetimeIndex( + [ + dt.datetime(2013, 1, 3, 0, 0), + dt.datetime(2013, 1, 3, 6, 10), + dt.datetime(2013, 1, 3, 7, 12), + ] + ), + ] + + indexes_cannot_append_with_other = [ + pd.MultiIndex.from_arrays(["A B C".split(), "D E F".split()]) + ] + + all_indexes = indexes_can_append + indexes_cannot_append_with_other + + @pytest.mark.parametrize("index", all_indexes, ids=lambda x: type(x).__name__) + def test_append_same_columns_type(self, index): + # GH18359 + + # df wider than ser + df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=index) + ser_index = index[:2] + ser = Series([7, 8], index=ser_index, name=2) + result = df.append(ser) + expected = DataFrame( + [[1.0, 2.0, 3.0], [4, 5, 6], [7, 8, np.nan]], index=[0, 1, 2], columns=index + ) + tm.assert_frame_equal(result, expected) + + # ser wider than df + ser_index = index + index = index[:2] + df = DataFrame([[1, 2], [4, 5]], columns=index) + ser = Series([7, 8, 9], index=ser_index, name=2) + result = df.append(ser) + expected = DataFrame( + [[1, 2, np.nan], [4, 5, np.nan], [7, 8, 9]], + index=[0, 1, 2], + columns=ser_index, + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "df_columns, series_index", + combinations(indexes_can_append, r=2), + ids=lambda x: type(x).__name__, + ) + def test_append_different_columns_types(self, df_columns, series_index): + # GH18359 + # See also test 'test_append_different_columns_types_raises' below + # for errors raised when appending + + df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=df_columns) + ser = Series([7, 8, 9], index=series_index, name=2) + + result = df.append(ser) + idx_diff = ser.index.difference(df_columns) + combined_columns = Index(df_columns.tolist()).append(idx_diff) + expected = DataFrame( + [ + [1.0, 2.0, 3.0, np.nan, np.nan, np.nan], + [4, 5, 6, np.nan, np.nan, np.nan], + [np.nan, np.nan, np.nan, 7, 8, 9], + ], + index=[0, 1, 2], + columns=combined_columns, + ) + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize( + "index_can_append", indexes_can_append, ids=lambda x: type(x).__name__ + ) + @pytest.mark.parametrize( + "index_cannot_append_with_other", + indexes_cannot_append_with_other, + ids=lambda x: type(x).__name__, + ) + def test_append_different_columns_types_raises( + self, index_can_append, index_cannot_append_with_other + ): + # GH18359 + # Dataframe.append will raise if MultiIndex appends + # or is appended to a different index type + # + # See also test 'test_append_different_columns_types' above for + # appending without raising. + + df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=index_can_append) + ser = Series([7, 8, 9], index=index_cannot_append_with_other, name=2) + msg = ( + r"Expected tuple, got (int|long|float|str|" + r"pandas._libs.interval.Interval)|" + r"object of type '(int|float|Timestamp|" + r"pandas._libs.interval.Interval)' has no len\(\)|" + ) + with pytest.raises(TypeError, match=msg): + df.append(ser) + + df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=index_cannot_append_with_other) + ser = Series([7, 8, 9], index=index_can_append, name=2) + + with pytest.raises(TypeError, match=msg): + df.append(ser) + + def test_append_dtype_coerce(self, sort): + + # GH 4993 + # appending with datetime will incorrectly convert datetime64 + + df1 = DataFrame( + index=[1, 2], + data=[dt.datetime(2013, 1, 1, 0, 0), dt.datetime(2013, 1, 2, 0, 0)], + columns=["start_time"], + ) + df2 = DataFrame( + index=[4, 5], + data=[ + [dt.datetime(2013, 1, 3, 0, 0), dt.datetime(2013, 1, 3, 6, 10)], + [dt.datetime(2013, 1, 4, 0, 0), dt.datetime(2013, 1, 4, 7, 10)], + ], + columns=["start_time", "end_time"], + ) + + expected = concat( + [ + Series( + [ + pd.NaT, + pd.NaT, + dt.datetime(2013, 1, 3, 6, 10), + dt.datetime(2013, 1, 4, 7, 10), + ], + name="end_time", + ), + Series( + [ + dt.datetime(2013, 1, 1, 0, 0), + dt.datetime(2013, 1, 2, 0, 0), + dt.datetime(2013, 1, 3, 0, 0), + dt.datetime(2013, 1, 4, 0, 0), + ], + name="start_time", + ), + ], + axis=1, + sort=sort, + ) + result = df1.append(df2, ignore_index=True, sort=sort) + if sort: + expected = expected[["end_time", "start_time"]] + else: + expected = expected[["start_time", "end_time"]] + + tm.assert_frame_equal(result, expected) + + def test_append_missing_column_proper_upcast(self, sort): + df1 = DataFrame({"A": np.array([1, 2, 3, 4], dtype="i8")}) + df2 = DataFrame({"B": np.array([True, False, True, False], dtype=bool)}) + + appended = df1.append(df2, ignore_index=True, sort=sort) + assert appended["A"].dtype == "f8" + assert appended["B"].dtype == "O" + + def test_append_empty_frame_to_series_with_dateutil_tz(self): + # GH 23682 + date = Timestamp("2018-10-24 07:30:00", tz=dateutil.tz.tzutc()) + s = Series({"date": date, "a": 1.0, "b": 2.0}) + df = DataFrame(columns=["c", "d"]) + result_a = df.append(s, ignore_index=True) + expected = DataFrame( + [[np.nan, np.nan, 1.0, 2.0, date]], columns=["c", "d", "a", "b", "date"] + ) + # These columns get cast to object after append + expected["c"] = expected["c"].astype(object) + expected["d"] = expected["d"].astype(object) + tm.assert_frame_equal(result_a, expected) + + expected = DataFrame( + [[np.nan, np.nan, 1.0, 2.0, date]] * 2, columns=["c", "d", "a", "b", "date"] + ) + expected["c"] = expected["c"].astype(object) + expected["d"] = expected["d"].astype(object) + + result_b = result_a.append(s, ignore_index=True) + tm.assert_frame_equal(result_b, expected) + + # column order is different + expected = expected[["c", "d", "date", "a", "b"]] + result = df.append([s, s], ignore_index=True) + tm.assert_frame_equal(result, expected) + + def test_append_empty_tz_frame_with_datetime64ns(self): + # https://github.com/pandas-dev/pandas/issues/35460 + df = DataFrame(columns=["a"]).astype("datetime64[ns, UTC]") + + # pd.NaT gets inferred as tz-naive, so append result is tz-naive + result = df.append({"a": pd.NaT}, ignore_index=True) + expected = DataFrame({"a": [pd.NaT]}).astype("datetime64[ns]") + tm.assert_frame_equal(result, expected) + + # also test with typed value to append + df = DataFrame(columns=["a"]).astype("datetime64[ns, UTC]") + result = df.append( + Series({"a": pd.NaT}, dtype="datetime64[ns]"), ignore_index=True + ) + expected = DataFrame({"a": [pd.NaT]}).astype("datetime64[ns]") + tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/reshape/concat/test_append_common.py b/pandas/tests/reshape/concat/test_append_common.py new file mode 100644 index 0000000000000..7ca3ae65706fe --- /dev/null +++ b/pandas/tests/reshape/concat/test_append_common.py @@ -0,0 +1,727 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import Categorical, DataFrame, Index, Series +import pandas._testing as tm + + +class TestConcatAppendCommon: + """ + Test common dtype coercion rules between concat and append. + """ + + def setup_method(self, method): + + dt_data = [ + pd.Timestamp("2011-01-01"), + pd.Timestamp("2011-01-02"), + pd.Timestamp("2011-01-03"), + ] + tz_data = [ + pd.Timestamp("2011-01-01", tz="US/Eastern"), + pd.Timestamp("2011-01-02", tz="US/Eastern"), + pd.Timestamp("2011-01-03", tz="US/Eastern"), + ] + + td_data = [ + pd.Timedelta("1 days"), + pd.Timedelta("2 days"), + pd.Timedelta("3 days"), + ] + + period_data = [ + pd.Period("2011-01", freq="M"), + pd.Period("2011-02", freq="M"), + pd.Period("2011-03", freq="M"), + ] + + self.data = { + "bool": [True, False, True], + "int64": [1, 2, 3], + "float64": [1.1, np.nan, 3.3], + "category": pd.Categorical(["X", "Y", "Z"]), + "object": ["a", "b", "c"], + "datetime64[ns]": dt_data, + "datetime64[ns, US/Eastern]": tz_data, + "timedelta64[ns]": td_data, + "period[M]": period_data, + } + + def _check_expected_dtype(self, obj, label): + """ + Check whether obj has expected dtype depending on label + considering not-supported dtypes + """ + if isinstance(obj, Index): + if label == "bool": + assert obj.dtype == "object" + else: + assert obj.dtype == label + elif isinstance(obj, Series): + if label.startswith("period"): + assert obj.dtype == "Period[M]" + else: + assert obj.dtype == label + else: + raise ValueError + + def test_dtypes(self): + # to confirm test case covers intended dtypes + for typ, vals in self.data.items(): + self._check_expected_dtype(Index(vals), typ) + self._check_expected_dtype(Series(vals), typ) + + def test_concatlike_same_dtypes(self): + # GH 13660 + for typ1, vals1 in self.data.items(): + + vals2 = vals1 + vals3 = vals1 + + if typ1 == "category": + exp_data = pd.Categorical(list(vals1) + list(vals2)) + exp_data3 = pd.Categorical(list(vals1) + list(vals2) + list(vals3)) + else: + exp_data = vals1 + vals2 + exp_data3 = vals1 + vals2 + vals3 + + # ----- Index ----- # + + # index.append + res = Index(vals1).append(Index(vals2)) + exp = Index(exp_data) + tm.assert_index_equal(res, exp) + + # 3 elements + res = Index(vals1).append([Index(vals2), Index(vals3)]) + exp = Index(exp_data3) + tm.assert_index_equal(res, exp) + + # index.append name mismatch + i1 = Index(vals1, name="x") + i2 = Index(vals2, name="y") + res = i1.append(i2) + exp = Index(exp_data) + tm.assert_index_equal(res, exp) + + # index.append name match + i1 = Index(vals1, name="x") + i2 = Index(vals2, name="x") + res = i1.append(i2) + exp = Index(exp_data, name="x") + tm.assert_index_equal(res, exp) + + # cannot append non-index + with pytest.raises(TypeError, match="all inputs must be Index"): + Index(vals1).append(vals2) + + with pytest.raises(TypeError, match="all inputs must be Index"): + Index(vals1).append([Index(vals2), vals3]) + + # ----- Series ----- # + + # series.append + res = Series(vals1).append(Series(vals2), ignore_index=True) + exp = Series(exp_data) + tm.assert_series_equal(res, exp, check_index_type=True) + + # concat + res = pd.concat([Series(vals1), Series(vals2)], ignore_index=True) + tm.assert_series_equal(res, exp, check_index_type=True) + + # 3 elements + res = Series(vals1).append( + [Series(vals2), Series(vals3)], ignore_index=True + ) + exp = Series(exp_data3) + tm.assert_series_equal(res, exp) + + res = pd.concat( + [Series(vals1), Series(vals2), Series(vals3)], + ignore_index=True, + ) + tm.assert_series_equal(res, exp) + + # name mismatch + s1 = Series(vals1, name="x") + s2 = Series(vals2, name="y") + res = s1.append(s2, ignore_index=True) + exp = Series(exp_data) + tm.assert_series_equal(res, exp, check_index_type=True) + + res = pd.concat([s1, s2], ignore_index=True) + tm.assert_series_equal(res, exp, check_index_type=True) + + # name match + s1 = Series(vals1, name="x") + s2 = Series(vals2, name="x") + res = s1.append(s2, ignore_index=True) + exp = Series(exp_data, name="x") + tm.assert_series_equal(res, exp, check_index_type=True) + + res = pd.concat([s1, s2], ignore_index=True) + tm.assert_series_equal(res, exp, check_index_type=True) + + # cannot append non-index + msg = ( + r"cannot concatenate object of type '.+'; " + "only Series and DataFrame objs are valid" + ) + with pytest.raises(TypeError, match=msg): + Series(vals1).append(vals2) + + with pytest.raises(TypeError, match=msg): + Series(vals1).append([Series(vals2), vals3]) + + with pytest.raises(TypeError, match=msg): + pd.concat([Series(vals1), vals2]) + + with pytest.raises(TypeError, match=msg): + pd.concat([Series(vals1), Series(vals2), vals3]) + + def test_concatlike_dtypes_coercion(self): + # GH 13660 + for typ1, vals1 in self.data.items(): + for typ2, vals2 in self.data.items(): + + vals3 = vals2 + + # basically infer + exp_index_dtype = None + exp_series_dtype = None + + if typ1 == typ2: + # same dtype is tested in test_concatlike_same_dtypes + continue + elif typ1 == "category" or typ2 == "category": + # TODO: suspicious + continue + + # specify expected dtype + if typ1 == "bool" and typ2 in ("int64", "float64"): + # series coerces to numeric based on numpy rule + # index doesn't because bool is object dtype + exp_series_dtype = typ2 + elif typ2 == "bool" and typ1 in ("int64", "float64"): + exp_series_dtype = typ1 + elif ( + typ1 == "datetime64[ns, US/Eastern]" + or typ2 == "datetime64[ns, US/Eastern]" + or typ1 == "timedelta64[ns]" + or typ2 == "timedelta64[ns]" + ): + exp_index_dtype = object + exp_series_dtype = object + + exp_data = vals1 + vals2 + exp_data3 = vals1 + vals2 + vals3 + + # ----- Index ----- # + + # index.append + res = Index(vals1).append(Index(vals2)) + exp = Index(exp_data, dtype=exp_index_dtype) + tm.assert_index_equal(res, exp) + + # 3 elements + res = Index(vals1).append([Index(vals2), Index(vals3)]) + exp = Index(exp_data3, dtype=exp_index_dtype) + tm.assert_index_equal(res, exp) + + # ----- Series ----- # + + # series.append + res = Series(vals1).append(Series(vals2), ignore_index=True) + exp = Series(exp_data, dtype=exp_series_dtype) + tm.assert_series_equal(res, exp, check_index_type=True) + + # concat + res = pd.concat([Series(vals1), Series(vals2)], ignore_index=True) + tm.assert_series_equal(res, exp, check_index_type=True) + + # 3 elements + res = Series(vals1).append( + [Series(vals2), Series(vals3)], ignore_index=True + ) + exp = Series(exp_data3, dtype=exp_series_dtype) + tm.assert_series_equal(res, exp) + + res = pd.concat( + [Series(vals1), Series(vals2), Series(vals3)], + ignore_index=True, + ) + tm.assert_series_equal(res, exp) + + def test_concatlike_common_coerce_to_pandas_object(self): + # GH 13626 + # result must be Timestamp/Timedelta, not datetime.datetime/timedelta + dti = pd.DatetimeIndex(["2011-01-01", "2011-01-02"]) + tdi = pd.TimedeltaIndex(["1 days", "2 days"]) + + exp = Index( + [ + pd.Timestamp("2011-01-01"), + pd.Timestamp("2011-01-02"), + pd.Timedelta("1 days"), + pd.Timedelta("2 days"), + ] + ) + + res = dti.append(tdi) + tm.assert_index_equal(res, exp) + assert isinstance(res[0], pd.Timestamp) + assert isinstance(res[-1], pd.Timedelta) + + dts = Series(dti) + tds = Series(tdi) + res = dts.append(tds) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + assert isinstance(res.iloc[0], pd.Timestamp) + assert isinstance(res.iloc[-1], pd.Timedelta) + + res = pd.concat([dts, tds]) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + assert isinstance(res.iloc[0], pd.Timestamp) + assert isinstance(res.iloc[-1], pd.Timedelta) + + def test_concatlike_datetimetz(self, tz_aware_fixture): + tz = tz_aware_fixture + # GH 7795 + dti1 = pd.DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz) + dti2 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"], tz=tz) + + exp = pd.DatetimeIndex( + ["2011-01-01", "2011-01-02", "2012-01-01", "2012-01-02"], tz=tz + ) + + res = dti1.append(dti2) + tm.assert_index_equal(res, exp) + + dts1 = Series(dti1) + dts2 = Series(dti2) + res = dts1.append(dts2) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + res = pd.concat([dts1, dts2]) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + @pytest.mark.parametrize("tz", ["UTC", "US/Eastern", "Asia/Tokyo", "EST5EDT"]) + def test_concatlike_datetimetz_short(self, tz): + # GH#7795 + ix1 = pd.date_range(start="2014-07-15", end="2014-07-17", freq="D", tz=tz) + ix2 = pd.DatetimeIndex(["2014-07-11", "2014-07-21"], tz=tz) + df1 = DataFrame(0, index=ix1, columns=["A", "B"]) + df2 = DataFrame(0, index=ix2, columns=["A", "B"]) + + exp_idx = pd.DatetimeIndex( + ["2014-07-15", "2014-07-16", "2014-07-17", "2014-07-11", "2014-07-21"], + tz=tz, + ) + exp = DataFrame(0, index=exp_idx, columns=["A", "B"]) + + tm.assert_frame_equal(df1.append(df2), exp) + tm.assert_frame_equal(pd.concat([df1, df2]), exp) + + def test_concatlike_datetimetz_to_object(self, tz_aware_fixture): + tz = tz_aware_fixture + # GH 13660 + + # different tz coerces to object + dti1 = pd.DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz) + dti2 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"]) + + exp = Index( + [ + pd.Timestamp("2011-01-01", tz=tz), + pd.Timestamp("2011-01-02", tz=tz), + pd.Timestamp("2012-01-01"), + pd.Timestamp("2012-01-02"), + ], + dtype=object, + ) + + res = dti1.append(dti2) + tm.assert_index_equal(res, exp) + + dts1 = Series(dti1) + dts2 = Series(dti2) + res = dts1.append(dts2) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + res = pd.concat([dts1, dts2]) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + # different tz + dti3 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"], tz="US/Pacific") + + exp = Index( + [ + pd.Timestamp("2011-01-01", tz=tz), + pd.Timestamp("2011-01-02", tz=tz), + pd.Timestamp("2012-01-01", tz="US/Pacific"), + pd.Timestamp("2012-01-02", tz="US/Pacific"), + ], + dtype=object, + ) + + res = dti1.append(dti3) + # tm.assert_index_equal(res, exp) + + dts1 = Series(dti1) + dts3 = Series(dti3) + res = dts1.append(dts3) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + res = pd.concat([dts1, dts3]) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + def test_concatlike_common_period(self): + # GH 13660 + pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M") + pi2 = pd.PeriodIndex(["2012-01", "2012-02"], freq="M") + + exp = pd.PeriodIndex(["2011-01", "2011-02", "2012-01", "2012-02"], freq="M") + + res = pi1.append(pi2) + tm.assert_index_equal(res, exp) + + ps1 = Series(pi1) + ps2 = Series(pi2) + res = ps1.append(ps2) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + res = pd.concat([ps1, ps2]) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + def test_concatlike_common_period_diff_freq_to_object(self): + # GH 13221 + pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M") + pi2 = pd.PeriodIndex(["2012-01-01", "2012-02-01"], freq="D") + + exp = Index( + [ + pd.Period("2011-01", freq="M"), + pd.Period("2011-02", freq="M"), + pd.Period("2012-01-01", freq="D"), + pd.Period("2012-02-01", freq="D"), + ], + dtype=object, + ) + + res = pi1.append(pi2) + tm.assert_index_equal(res, exp) + + ps1 = Series(pi1) + ps2 = Series(pi2) + res = ps1.append(ps2) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + res = pd.concat([ps1, ps2]) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + def test_concatlike_common_period_mixed_dt_to_object(self): + # GH 13221 + # different datetimelike + pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M") + tdi = pd.TimedeltaIndex(["1 days", "2 days"]) + exp = Index( + [ + pd.Period("2011-01", freq="M"), + pd.Period("2011-02", freq="M"), + pd.Timedelta("1 days"), + pd.Timedelta("2 days"), + ], + dtype=object, + ) + + res = pi1.append(tdi) + tm.assert_index_equal(res, exp) + + ps1 = Series(pi1) + tds = Series(tdi) + res = ps1.append(tds) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + res = pd.concat([ps1, tds]) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + # inverse + exp = Index( + [ + pd.Timedelta("1 days"), + pd.Timedelta("2 days"), + pd.Period("2011-01", freq="M"), + pd.Period("2011-02", freq="M"), + ], + dtype=object, + ) + + res = tdi.append(pi1) + tm.assert_index_equal(res, exp) + + ps1 = Series(pi1) + tds = Series(tdi) + res = tds.append(ps1) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + res = pd.concat([tds, ps1]) + tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) + + def test_concat_categorical(self): + # GH 13524 + + # same categories -> category + s1 = Series([1, 2, np.nan], dtype="category") + s2 = Series([2, 1, 2], dtype="category") + + exp = Series([1, 2, np.nan, 2, 1, 2], dtype="category") + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + + # partially different categories => not-category + s1 = Series([3, 2], dtype="category") + s2 = Series([2, 1], dtype="category") + + exp = Series([3, 2, 2, 1]) + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + + # completely different categories (same dtype) => not-category + s1 = Series([10, 11, np.nan], dtype="category") + s2 = Series([np.nan, 1, 3, 2], dtype="category") + + exp = Series([10, 11, np.nan, np.nan, 1, 3, 2], dtype="object") + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + + def test_union_categorical_same_categories_different_order(self): + # https://github.com/pandas-dev/pandas/issues/19096 + a = Series(Categorical(["a", "b", "c"], categories=["a", "b", "c"])) + b = Series(Categorical(["a", "b", "c"], categories=["b", "a", "c"])) + result = pd.concat([a, b], ignore_index=True) + expected = Series( + Categorical(["a", "b", "c", "a", "b", "c"], categories=["a", "b", "c"]) + ) + tm.assert_series_equal(result, expected) + + def test_concat_categorical_coercion(self): + # GH 13524 + + # category + not-category => not-category + s1 = Series([1, 2, np.nan], dtype="category") + s2 = Series([2, 1, 2]) + + exp = Series([1, 2, np.nan, 2, 1, 2], dtype="object") + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + + # result shouldn't be affected by 1st elem dtype + exp = Series([2, 1, 2, 1, 2, np.nan], dtype="object") + tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) + tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) + + # all values are not in category => not-category + s1 = Series([3, 2], dtype="category") + s2 = Series([2, 1]) + + exp = Series([3, 2, 2, 1]) + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + + exp = Series([2, 1, 3, 2]) + tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) + tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) + + # completely different categories => not-category + s1 = Series([10, 11, np.nan], dtype="category") + s2 = Series([1, 3, 2]) + + exp = Series([10, 11, np.nan, 1, 3, 2], dtype="object") + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + + exp = Series([1, 3, 2, 10, 11, np.nan], dtype="object") + tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) + tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) + + # different dtype => not-category + s1 = Series([10, 11, np.nan], dtype="category") + s2 = Series(["a", "b", "c"]) + + exp = Series([10, 11, np.nan, "a", "b", "c"]) + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + + exp = Series(["a", "b", "c", 10, 11, np.nan]) + tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) + tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) + + # if normal series only contains NaN-likes => not-category + s1 = Series([10, 11], dtype="category") + s2 = Series([np.nan, np.nan, np.nan]) + + exp = Series([10, 11, np.nan, np.nan, np.nan]) + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + + exp = Series([np.nan, np.nan, np.nan, 10, 11]) + tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) + tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) + + def test_concat_categorical_3elem_coercion(self): + # GH 13524 + + # mixed dtypes => not-category + s1 = Series([1, 2, np.nan], dtype="category") + s2 = Series([2, 1, 2], dtype="category") + s3 = Series([1, 2, 1, 2, np.nan]) + + exp = Series([1, 2, np.nan, 2, 1, 2, 1, 2, 1, 2, np.nan], dtype="float") + tm.assert_series_equal(pd.concat([s1, s2, s3], ignore_index=True), exp) + tm.assert_series_equal(s1.append([s2, s3], ignore_index=True), exp) + + exp = Series([1, 2, 1, 2, np.nan, 1, 2, np.nan, 2, 1, 2], dtype="float") + tm.assert_series_equal(pd.concat([s3, s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s3.append([s1, s2], ignore_index=True), exp) + + # values are all in either category => not-category + s1 = Series([4, 5, 6], dtype="category") + s2 = Series([1, 2, 3], dtype="category") + s3 = Series([1, 3, 4]) + + exp = Series([4, 5, 6, 1, 2, 3, 1, 3, 4]) + tm.assert_series_equal(pd.concat([s1, s2, s3], ignore_index=True), exp) + tm.assert_series_equal(s1.append([s2, s3], ignore_index=True), exp) + + exp = Series([1, 3, 4, 4, 5, 6, 1, 2, 3]) + tm.assert_series_equal(pd.concat([s3, s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s3.append([s1, s2], ignore_index=True), exp) + + # values are all in either category => not-category + s1 = Series([4, 5, 6], dtype="category") + s2 = Series([1, 2, 3], dtype="category") + s3 = Series([10, 11, 12]) + + exp = Series([4, 5, 6, 1, 2, 3, 10, 11, 12]) + tm.assert_series_equal(pd.concat([s1, s2, s3], ignore_index=True), exp) + tm.assert_series_equal(s1.append([s2, s3], ignore_index=True), exp) + + exp = Series([10, 11, 12, 4, 5, 6, 1, 2, 3]) + tm.assert_series_equal(pd.concat([s3, s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s3.append([s1, s2], ignore_index=True), exp) + + def test_concat_categorical_multi_coercion(self): + # GH 13524 + + s1 = Series([1, 3], dtype="category") + s2 = Series([3, 4], dtype="category") + s3 = Series([2, 3]) + s4 = Series([2, 2], dtype="category") + s5 = Series([1, np.nan]) + s6 = Series([1, 3, 2], dtype="category") + + # mixed dtype, values are all in categories => not-category + exp = Series([1, 3, 3, 4, 2, 3, 2, 2, 1, np.nan, 1, 3, 2]) + res = pd.concat([s1, s2, s3, s4, s5, s6], ignore_index=True) + tm.assert_series_equal(res, exp) + res = s1.append([s2, s3, s4, s5, s6], ignore_index=True) + tm.assert_series_equal(res, exp) + + exp = Series([1, 3, 2, 1, np.nan, 2, 2, 2, 3, 3, 4, 1, 3]) + res = pd.concat([s6, s5, s4, s3, s2, s1], ignore_index=True) + tm.assert_series_equal(res, exp) + res = s6.append([s5, s4, s3, s2, s1], ignore_index=True) + tm.assert_series_equal(res, exp) + + def test_concat_categorical_ordered(self): + # GH 13524 + + s1 = Series(pd.Categorical([1, 2, np.nan], ordered=True)) + s2 = Series(pd.Categorical([2, 1, 2], ordered=True)) + + exp = Series(pd.Categorical([1, 2, np.nan, 2, 1, 2], ordered=True)) + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + + exp = Series( + pd.Categorical([1, 2, np.nan, 2, 1, 2, 1, 2, np.nan], ordered=True) + ) + tm.assert_series_equal(pd.concat([s1, s2, s1], ignore_index=True), exp) + tm.assert_series_equal(s1.append([s2, s1], ignore_index=True), exp) + + def test_concat_categorical_coercion_nan(self): + # GH 13524 + + # some edge cases + # category + not-category => not category + s1 = Series(np.array([np.nan, np.nan], dtype=np.float64), dtype="category") + s2 = Series([np.nan, 1]) + + exp = Series([np.nan, np.nan, np.nan, 1]) + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + + s1 = Series([1, np.nan], dtype="category") + s2 = Series([np.nan, np.nan]) + + exp = Series([1, np.nan, np.nan, np.nan], dtype="float") + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + + # mixed dtype, all nan-likes => not-category + s1 = Series([np.nan, np.nan], dtype="category") + s2 = Series([np.nan, np.nan]) + + exp = Series([np.nan, np.nan, np.nan, np.nan]) + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) + tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) + + # all category nan-likes => category + s1 = Series([np.nan, np.nan], dtype="category") + s2 = Series([np.nan, np.nan], dtype="category") + + exp = Series([np.nan, np.nan, np.nan, np.nan], dtype="category") + + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + + def test_concat_categorical_empty(self): + # GH 13524 + + s1 = Series([], dtype="category") + s2 = Series([1, 2], dtype="category") + + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), s2) + tm.assert_series_equal(s1.append(s2, ignore_index=True), s2) + + tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), s2) + tm.assert_series_equal(s2.append(s1, ignore_index=True), s2) + + s1 = Series([], dtype="category") + s2 = Series([], dtype="category") + + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), s2) + tm.assert_series_equal(s1.append(s2, ignore_index=True), s2) + + s1 = Series([], dtype="category") + s2 = Series([], dtype="object") + + # different dtype => not-category + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), s2) + tm.assert_series_equal(s1.append(s2, ignore_index=True), s2) + tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), s2) + tm.assert_series_equal(s2.append(s1, ignore_index=True), s2) + + s1 = Series([], dtype="category") + s2 = Series([np.nan, np.nan]) + + # empty Series is ignored + exp = Series([np.nan, np.nan]) + tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) + tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) + + tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) + tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/concat/test_concat.py similarity index 55% rename from pandas/tests/reshape/test_concat.py rename to pandas/tests/reshape/concat/test_concat.py index 33048c0e0e2df..6fa4419f90138 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/concat/test_concat.py @@ -3,7 +3,6 @@ from datetime import datetime from decimal import Decimal from io import StringIO -from itertools import combinations from warnings import catch_warnings import dateutil @@ -24,7 +23,6 @@ Timestamp, concat, date_range, - isna, read_csv, ) import pandas._testing as tm @@ -39,1093 +37,6 @@ def sort(request): return request.param -class TestConcatAppendCommon: - """ - Test common dtype coercion rules between concat and append. - """ - - def setup_method(self, method): - - dt_data = [ - pd.Timestamp("2011-01-01"), - pd.Timestamp("2011-01-02"), - pd.Timestamp("2011-01-03"), - ] - tz_data = [ - pd.Timestamp("2011-01-01", tz="US/Eastern"), - pd.Timestamp("2011-01-02", tz="US/Eastern"), - pd.Timestamp("2011-01-03", tz="US/Eastern"), - ] - - td_data = [ - pd.Timedelta("1 days"), - pd.Timedelta("2 days"), - pd.Timedelta("3 days"), - ] - - period_data = [ - pd.Period("2011-01", freq="M"), - pd.Period("2011-02", freq="M"), - pd.Period("2011-03", freq="M"), - ] - - self.data = { - "bool": [True, False, True], - "int64": [1, 2, 3], - "float64": [1.1, np.nan, 3.3], - "category": pd.Categorical(["X", "Y", "Z"]), - "object": ["a", "b", "c"], - "datetime64[ns]": dt_data, - "datetime64[ns, US/Eastern]": tz_data, - "timedelta64[ns]": td_data, - "period[M]": period_data, - } - - def _check_expected_dtype(self, obj, label): - """ - Check whether obj has expected dtype depending on label - considering not-supported dtypes - """ - if isinstance(obj, Index): - if label == "bool": - assert obj.dtype == "object" - else: - assert obj.dtype == label - elif isinstance(obj, Series): - if label.startswith("period"): - assert obj.dtype == "Period[M]" - else: - assert obj.dtype == label - else: - raise ValueError - - def test_dtypes(self): - # to confirm test case covers intended dtypes - for typ, vals in self.data.items(): - self._check_expected_dtype(Index(vals), typ) - self._check_expected_dtype(Series(vals), typ) - - def test_concatlike_same_dtypes(self): - # GH 13660 - for typ1, vals1 in self.data.items(): - - vals2 = vals1 - vals3 = vals1 - - if typ1 == "category": - exp_data = pd.Categorical(list(vals1) + list(vals2)) - exp_data3 = pd.Categorical(list(vals1) + list(vals2) + list(vals3)) - else: - exp_data = vals1 + vals2 - exp_data3 = vals1 + vals2 + vals3 - - # ----- Index ----- # - - # index.append - res = Index(vals1).append(Index(vals2)) - exp = Index(exp_data) - tm.assert_index_equal(res, exp) - - # 3 elements - res = Index(vals1).append([Index(vals2), Index(vals3)]) - exp = Index(exp_data3) - tm.assert_index_equal(res, exp) - - # index.append name mismatch - i1 = Index(vals1, name="x") - i2 = Index(vals2, name="y") - res = i1.append(i2) - exp = Index(exp_data) - tm.assert_index_equal(res, exp) - - # index.append name match - i1 = Index(vals1, name="x") - i2 = Index(vals2, name="x") - res = i1.append(i2) - exp = Index(exp_data, name="x") - tm.assert_index_equal(res, exp) - - # cannot append non-index - with pytest.raises(TypeError, match="all inputs must be Index"): - Index(vals1).append(vals2) - - with pytest.raises(TypeError, match="all inputs must be Index"): - Index(vals1).append([Index(vals2), vals3]) - - # ----- Series ----- # - - # series.append - res = Series(vals1).append(Series(vals2), ignore_index=True) - exp = Series(exp_data) - tm.assert_series_equal(res, exp, check_index_type=True) - - # concat - res = pd.concat([Series(vals1), Series(vals2)], ignore_index=True) - tm.assert_series_equal(res, exp, check_index_type=True) - - # 3 elements - res = Series(vals1).append( - [Series(vals2), Series(vals3)], ignore_index=True - ) - exp = Series(exp_data3) - tm.assert_series_equal(res, exp) - - res = pd.concat( - [Series(vals1), Series(vals2), Series(vals3)], - ignore_index=True, - ) - tm.assert_series_equal(res, exp) - - # name mismatch - s1 = Series(vals1, name="x") - s2 = Series(vals2, name="y") - res = s1.append(s2, ignore_index=True) - exp = Series(exp_data) - tm.assert_series_equal(res, exp, check_index_type=True) - - res = pd.concat([s1, s2], ignore_index=True) - tm.assert_series_equal(res, exp, check_index_type=True) - - # name match - s1 = Series(vals1, name="x") - s2 = Series(vals2, name="x") - res = s1.append(s2, ignore_index=True) - exp = Series(exp_data, name="x") - tm.assert_series_equal(res, exp, check_index_type=True) - - res = pd.concat([s1, s2], ignore_index=True) - tm.assert_series_equal(res, exp, check_index_type=True) - - # cannot append non-index - msg = ( - r"cannot concatenate object of type '.+'; " - "only Series and DataFrame objs are valid" - ) - with pytest.raises(TypeError, match=msg): - Series(vals1).append(vals2) - - with pytest.raises(TypeError, match=msg): - Series(vals1).append([Series(vals2), vals3]) - - with pytest.raises(TypeError, match=msg): - pd.concat([Series(vals1), vals2]) - - with pytest.raises(TypeError, match=msg): - pd.concat([Series(vals1), Series(vals2), vals3]) - - def test_concatlike_dtypes_coercion(self): - # GH 13660 - for typ1, vals1 in self.data.items(): - for typ2, vals2 in self.data.items(): - - vals3 = vals2 - - # basically infer - exp_index_dtype = None - exp_series_dtype = None - - if typ1 == typ2: - # same dtype is tested in test_concatlike_same_dtypes - continue - elif typ1 == "category" or typ2 == "category": - # TODO: suspicious - continue - - # specify expected dtype - if typ1 == "bool" and typ2 in ("int64", "float64"): - # series coerces to numeric based on numpy rule - # index doesn't because bool is object dtype - exp_series_dtype = typ2 - elif typ2 == "bool" and typ1 in ("int64", "float64"): - exp_series_dtype = typ1 - elif ( - typ1 == "datetime64[ns, US/Eastern]" - or typ2 == "datetime64[ns, US/Eastern]" - or typ1 == "timedelta64[ns]" - or typ2 == "timedelta64[ns]" - ): - exp_index_dtype = object - exp_series_dtype = object - - exp_data = vals1 + vals2 - exp_data3 = vals1 + vals2 + vals3 - - # ----- Index ----- # - - # index.append - res = Index(vals1).append(Index(vals2)) - exp = Index(exp_data, dtype=exp_index_dtype) - tm.assert_index_equal(res, exp) - - # 3 elements - res = Index(vals1).append([Index(vals2), Index(vals3)]) - exp = Index(exp_data3, dtype=exp_index_dtype) - tm.assert_index_equal(res, exp) - - # ----- Series ----- # - - # series.append - res = Series(vals1).append(Series(vals2), ignore_index=True) - exp = Series(exp_data, dtype=exp_series_dtype) - tm.assert_series_equal(res, exp, check_index_type=True) - - # concat - res = pd.concat([Series(vals1), Series(vals2)], ignore_index=True) - tm.assert_series_equal(res, exp, check_index_type=True) - - # 3 elements - res = Series(vals1).append( - [Series(vals2), Series(vals3)], ignore_index=True - ) - exp = Series(exp_data3, dtype=exp_series_dtype) - tm.assert_series_equal(res, exp) - - res = pd.concat( - [Series(vals1), Series(vals2), Series(vals3)], - ignore_index=True, - ) - tm.assert_series_equal(res, exp) - - def test_concatlike_common_coerce_to_pandas_object(self): - # GH 13626 - # result must be Timestamp/Timedelta, not datetime.datetime/timedelta - dti = pd.DatetimeIndex(["2011-01-01", "2011-01-02"]) - tdi = pd.TimedeltaIndex(["1 days", "2 days"]) - - exp = Index( - [ - pd.Timestamp("2011-01-01"), - pd.Timestamp("2011-01-02"), - pd.Timedelta("1 days"), - pd.Timedelta("2 days"), - ] - ) - - res = dti.append(tdi) - tm.assert_index_equal(res, exp) - assert isinstance(res[0], pd.Timestamp) - assert isinstance(res[-1], pd.Timedelta) - - dts = Series(dti) - tds = Series(tdi) - res = dts.append(tds) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - assert isinstance(res.iloc[0], pd.Timestamp) - assert isinstance(res.iloc[-1], pd.Timedelta) - - res = pd.concat([dts, tds]) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - assert isinstance(res.iloc[0], pd.Timestamp) - assert isinstance(res.iloc[-1], pd.Timedelta) - - def test_concatlike_datetimetz(self, tz_aware_fixture): - tz = tz_aware_fixture - # GH 7795 - dti1 = pd.DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz) - dti2 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"], tz=tz) - - exp = pd.DatetimeIndex( - ["2011-01-01", "2011-01-02", "2012-01-01", "2012-01-02"], tz=tz - ) - - res = dti1.append(dti2) - tm.assert_index_equal(res, exp) - - dts1 = Series(dti1) - dts2 = Series(dti2) - res = dts1.append(dts2) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - res = pd.concat([dts1, dts2]) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - @pytest.mark.parametrize("tz", ["UTC", "US/Eastern", "Asia/Tokyo", "EST5EDT"]) - def test_concatlike_datetimetz_short(self, tz): - # GH#7795 - ix1 = pd.date_range(start="2014-07-15", end="2014-07-17", freq="D", tz=tz) - ix2 = pd.DatetimeIndex(["2014-07-11", "2014-07-21"], tz=tz) - df1 = DataFrame(0, index=ix1, columns=["A", "B"]) - df2 = DataFrame(0, index=ix2, columns=["A", "B"]) - - exp_idx = pd.DatetimeIndex( - ["2014-07-15", "2014-07-16", "2014-07-17", "2014-07-11", "2014-07-21"], - tz=tz, - ) - exp = DataFrame(0, index=exp_idx, columns=["A", "B"]) - - tm.assert_frame_equal(df1.append(df2), exp) - tm.assert_frame_equal(pd.concat([df1, df2]), exp) - - def test_concatlike_datetimetz_to_object(self, tz_aware_fixture): - tz = tz_aware_fixture - # GH 13660 - - # different tz coerces to object - dti1 = pd.DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz) - dti2 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"]) - - exp = Index( - [ - pd.Timestamp("2011-01-01", tz=tz), - pd.Timestamp("2011-01-02", tz=tz), - pd.Timestamp("2012-01-01"), - pd.Timestamp("2012-01-02"), - ], - dtype=object, - ) - - res = dti1.append(dti2) - tm.assert_index_equal(res, exp) - - dts1 = Series(dti1) - dts2 = Series(dti2) - res = dts1.append(dts2) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - res = pd.concat([dts1, dts2]) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - # different tz - dti3 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"], tz="US/Pacific") - - exp = Index( - [ - pd.Timestamp("2011-01-01", tz=tz), - pd.Timestamp("2011-01-02", tz=tz), - pd.Timestamp("2012-01-01", tz="US/Pacific"), - pd.Timestamp("2012-01-02", tz="US/Pacific"), - ], - dtype=object, - ) - - res = dti1.append(dti3) - # tm.assert_index_equal(res, exp) - - dts1 = Series(dti1) - dts3 = Series(dti3) - res = dts1.append(dts3) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - res = pd.concat([dts1, dts3]) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - def test_concatlike_common_period(self): - # GH 13660 - pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M") - pi2 = pd.PeriodIndex(["2012-01", "2012-02"], freq="M") - - exp = pd.PeriodIndex(["2011-01", "2011-02", "2012-01", "2012-02"], freq="M") - - res = pi1.append(pi2) - tm.assert_index_equal(res, exp) - - ps1 = Series(pi1) - ps2 = Series(pi2) - res = ps1.append(ps2) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - res = pd.concat([ps1, ps2]) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - def test_concatlike_common_period_diff_freq_to_object(self): - # GH 13221 - pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M") - pi2 = pd.PeriodIndex(["2012-01-01", "2012-02-01"], freq="D") - - exp = Index( - [ - pd.Period("2011-01", freq="M"), - pd.Period("2011-02", freq="M"), - pd.Period("2012-01-01", freq="D"), - pd.Period("2012-02-01", freq="D"), - ], - dtype=object, - ) - - res = pi1.append(pi2) - tm.assert_index_equal(res, exp) - - ps1 = Series(pi1) - ps2 = Series(pi2) - res = ps1.append(ps2) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - res = pd.concat([ps1, ps2]) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - def test_concatlike_common_period_mixed_dt_to_object(self): - # GH 13221 - # different datetimelike - pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M") - tdi = pd.TimedeltaIndex(["1 days", "2 days"]) - exp = Index( - [ - pd.Period("2011-01", freq="M"), - pd.Period("2011-02", freq="M"), - pd.Timedelta("1 days"), - pd.Timedelta("2 days"), - ], - dtype=object, - ) - - res = pi1.append(tdi) - tm.assert_index_equal(res, exp) - - ps1 = Series(pi1) - tds = Series(tdi) - res = ps1.append(tds) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - res = pd.concat([ps1, tds]) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - # inverse - exp = Index( - [ - pd.Timedelta("1 days"), - pd.Timedelta("2 days"), - pd.Period("2011-01", freq="M"), - pd.Period("2011-02", freq="M"), - ], - dtype=object, - ) - - res = tdi.append(pi1) - tm.assert_index_equal(res, exp) - - ps1 = Series(pi1) - tds = Series(tdi) - res = tds.append(ps1) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - res = pd.concat([tds, ps1]) - tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) - - def test_concat_categorical(self): - # GH 13524 - - # same categories -> category - s1 = Series([1, 2, np.nan], dtype="category") - s2 = Series([2, 1, 2], dtype="category") - - exp = Series([1, 2, np.nan, 2, 1, 2], dtype="category") - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - - # partially different categories => not-category - s1 = Series([3, 2], dtype="category") - s2 = Series([2, 1], dtype="category") - - exp = Series([3, 2, 2, 1]) - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - - # completely different categories (same dtype) => not-category - s1 = Series([10, 11, np.nan], dtype="category") - s2 = Series([np.nan, 1, 3, 2], dtype="category") - - exp = Series([10, 11, np.nan, np.nan, 1, 3, 2], dtype="object") - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - - def test_union_categorical_same_categories_different_order(self): - # https://github.com/pandas-dev/pandas/issues/19096 - a = Series(Categorical(["a", "b", "c"], categories=["a", "b", "c"])) - b = Series(Categorical(["a", "b", "c"], categories=["b", "a", "c"])) - result = pd.concat([a, b], ignore_index=True) - expected = Series( - Categorical(["a", "b", "c", "a", "b", "c"], categories=["a", "b", "c"]) - ) - tm.assert_series_equal(result, expected) - - def test_concat_categorical_coercion(self): - # GH 13524 - - # category + not-category => not-category - s1 = Series([1, 2, np.nan], dtype="category") - s2 = Series([2, 1, 2]) - - exp = Series([1, 2, np.nan, 2, 1, 2], dtype="object") - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - - # result shouldn't be affected by 1st elem dtype - exp = Series([2, 1, 2, 1, 2, np.nan], dtype="object") - tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) - tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) - - # all values are not in category => not-category - s1 = Series([3, 2], dtype="category") - s2 = Series([2, 1]) - - exp = Series([3, 2, 2, 1]) - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - - exp = Series([2, 1, 3, 2]) - tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) - tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) - - # completely different categories => not-category - s1 = Series([10, 11, np.nan], dtype="category") - s2 = Series([1, 3, 2]) - - exp = Series([10, 11, np.nan, 1, 3, 2], dtype="object") - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - - exp = Series([1, 3, 2, 10, 11, np.nan], dtype="object") - tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) - tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) - - # different dtype => not-category - s1 = Series([10, 11, np.nan], dtype="category") - s2 = Series(["a", "b", "c"]) - - exp = Series([10, 11, np.nan, "a", "b", "c"]) - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - - exp = Series(["a", "b", "c", 10, 11, np.nan]) - tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) - tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) - - # if normal series only contains NaN-likes => not-category - s1 = Series([10, 11], dtype="category") - s2 = Series([np.nan, np.nan, np.nan]) - - exp = Series([10, 11, np.nan, np.nan, np.nan]) - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - - exp = Series([np.nan, np.nan, np.nan, 10, 11]) - tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) - tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) - - def test_concat_categorical_3elem_coercion(self): - # GH 13524 - - # mixed dtypes => not-category - s1 = Series([1, 2, np.nan], dtype="category") - s2 = Series([2, 1, 2], dtype="category") - s3 = Series([1, 2, 1, 2, np.nan]) - - exp = Series([1, 2, np.nan, 2, 1, 2, 1, 2, 1, 2, np.nan], dtype="float") - tm.assert_series_equal(pd.concat([s1, s2, s3], ignore_index=True), exp) - tm.assert_series_equal(s1.append([s2, s3], ignore_index=True), exp) - - exp = Series([1, 2, 1, 2, np.nan, 1, 2, np.nan, 2, 1, 2], dtype="float") - tm.assert_series_equal(pd.concat([s3, s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s3.append([s1, s2], ignore_index=True), exp) - - # values are all in either category => not-category - s1 = Series([4, 5, 6], dtype="category") - s2 = Series([1, 2, 3], dtype="category") - s3 = Series([1, 3, 4]) - - exp = Series([4, 5, 6, 1, 2, 3, 1, 3, 4]) - tm.assert_series_equal(pd.concat([s1, s2, s3], ignore_index=True), exp) - tm.assert_series_equal(s1.append([s2, s3], ignore_index=True), exp) - - exp = Series([1, 3, 4, 4, 5, 6, 1, 2, 3]) - tm.assert_series_equal(pd.concat([s3, s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s3.append([s1, s2], ignore_index=True), exp) - - # values are all in either category => not-category - s1 = Series([4, 5, 6], dtype="category") - s2 = Series([1, 2, 3], dtype="category") - s3 = Series([10, 11, 12]) - - exp = Series([4, 5, 6, 1, 2, 3, 10, 11, 12]) - tm.assert_series_equal(pd.concat([s1, s2, s3], ignore_index=True), exp) - tm.assert_series_equal(s1.append([s2, s3], ignore_index=True), exp) - - exp = Series([10, 11, 12, 4, 5, 6, 1, 2, 3]) - tm.assert_series_equal(pd.concat([s3, s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s3.append([s1, s2], ignore_index=True), exp) - - def test_concat_categorical_multi_coercion(self): - # GH 13524 - - s1 = Series([1, 3], dtype="category") - s2 = Series([3, 4], dtype="category") - s3 = Series([2, 3]) - s4 = Series([2, 2], dtype="category") - s5 = Series([1, np.nan]) - s6 = Series([1, 3, 2], dtype="category") - - # mixed dtype, values are all in categories => not-category - exp = Series([1, 3, 3, 4, 2, 3, 2, 2, 1, np.nan, 1, 3, 2]) - res = pd.concat([s1, s2, s3, s4, s5, s6], ignore_index=True) - tm.assert_series_equal(res, exp) - res = s1.append([s2, s3, s4, s5, s6], ignore_index=True) - tm.assert_series_equal(res, exp) - - exp = Series([1, 3, 2, 1, np.nan, 2, 2, 2, 3, 3, 4, 1, 3]) - res = pd.concat([s6, s5, s4, s3, s2, s1], ignore_index=True) - tm.assert_series_equal(res, exp) - res = s6.append([s5, s4, s3, s2, s1], ignore_index=True) - tm.assert_series_equal(res, exp) - - def test_concat_categorical_ordered(self): - # GH 13524 - - s1 = Series(pd.Categorical([1, 2, np.nan], ordered=True)) - s2 = Series(pd.Categorical([2, 1, 2], ordered=True)) - - exp = Series(pd.Categorical([1, 2, np.nan, 2, 1, 2], ordered=True)) - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - - exp = Series( - pd.Categorical([1, 2, np.nan, 2, 1, 2, 1, 2, np.nan], ordered=True) - ) - tm.assert_series_equal(pd.concat([s1, s2, s1], ignore_index=True), exp) - tm.assert_series_equal(s1.append([s2, s1], ignore_index=True), exp) - - def test_concat_categorical_coercion_nan(self): - # GH 13524 - - # some edge cases - # category + not-category => not category - s1 = Series(np.array([np.nan, np.nan], dtype=np.float64), dtype="category") - s2 = Series([np.nan, 1]) - - exp = Series([np.nan, np.nan, np.nan, 1]) - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - - s1 = Series([1, np.nan], dtype="category") - s2 = Series([np.nan, np.nan]) - - exp = Series([1, np.nan, np.nan, np.nan], dtype="float") - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - - # mixed dtype, all nan-likes => not-category - s1 = Series([np.nan, np.nan], dtype="category") - s2 = Series([np.nan, np.nan]) - - exp = Series([np.nan, np.nan, np.nan, np.nan]) - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) - tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) - - # all category nan-likes => category - s1 = Series([np.nan, np.nan], dtype="category") - s2 = Series([np.nan, np.nan], dtype="category") - - exp = Series([np.nan, np.nan, np.nan, np.nan], dtype="category") - - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - - def test_concat_categorical_empty(self): - # GH 13524 - - s1 = Series([], dtype="category") - s2 = Series([1, 2], dtype="category") - - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), s2) - tm.assert_series_equal(s1.append(s2, ignore_index=True), s2) - - tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), s2) - tm.assert_series_equal(s2.append(s1, ignore_index=True), s2) - - s1 = Series([], dtype="category") - s2 = Series([], dtype="category") - - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), s2) - tm.assert_series_equal(s1.append(s2, ignore_index=True), s2) - - s1 = Series([], dtype="category") - s2 = Series([], dtype="object") - - # different dtype => not-category - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), s2) - tm.assert_series_equal(s1.append(s2, ignore_index=True), s2) - tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), s2) - tm.assert_series_equal(s2.append(s1, ignore_index=True), s2) - - s1 = Series([], dtype="category") - s2 = Series([np.nan, np.nan]) - - # empty Series is ignored - exp = Series([np.nan, np.nan]) - tm.assert_series_equal(pd.concat([s1, s2], ignore_index=True), exp) - tm.assert_series_equal(s1.append(s2, ignore_index=True), exp) - - tm.assert_series_equal(pd.concat([s2, s1], ignore_index=True), exp) - tm.assert_series_equal(s2.append(s1, ignore_index=True), exp) - - -class TestAppend: - def test_append(self, sort, float_frame): - mixed_frame = float_frame.copy() - mixed_frame["foo"] = "bar" - - begin_index = float_frame.index[:5] - end_index = float_frame.index[5:] - - begin_frame = float_frame.reindex(begin_index) - end_frame = float_frame.reindex(end_index) - - appended = begin_frame.append(end_frame) - tm.assert_almost_equal(appended["A"], float_frame["A"]) - - del end_frame["A"] - partial_appended = begin_frame.append(end_frame, sort=sort) - assert "A" in partial_appended - - partial_appended = end_frame.append(begin_frame, sort=sort) - assert "A" in partial_appended - - # mixed type handling - appended = mixed_frame[:5].append(mixed_frame[5:]) - tm.assert_frame_equal(appended, mixed_frame) - - # what to test here - mixed_appended = mixed_frame[:5].append(float_frame[5:], sort=sort) - mixed_appended2 = float_frame[:5].append(mixed_frame[5:], sort=sort) - - # all equal except 'foo' column - tm.assert_frame_equal( - mixed_appended.reindex(columns=["A", "B", "C", "D"]), - mixed_appended2.reindex(columns=["A", "B", "C", "D"]), - ) - - def test_append_empty(self, float_frame): - empty = DataFrame() - - appended = float_frame.append(empty) - tm.assert_frame_equal(float_frame, appended) - assert appended is not float_frame - - appended = empty.append(float_frame) - tm.assert_frame_equal(float_frame, appended) - assert appended is not float_frame - - def test_append_overlap_raises(self, float_frame): - msg = "Indexes have overlapping values" - with pytest.raises(ValueError, match=msg): - float_frame.append(float_frame, verify_integrity=True) - - def test_append_new_columns(self): - # see gh-6129: new columns - df = DataFrame({"a": {"x": 1, "y": 2}, "b": {"x": 3, "y": 4}}) - row = Series([5, 6, 7], index=["a", "b", "c"], name="z") - expected = DataFrame( - { - "a": {"x": 1, "y": 2, "z": 5}, - "b": {"x": 3, "y": 4, "z": 6}, - "c": {"z": 7}, - } - ) - result = df.append(row) - tm.assert_frame_equal(result, expected) - - def test_append_length0_frame(self, sort): - df = DataFrame(columns=["A", "B", "C"]) - df3 = DataFrame(index=[0, 1], columns=["A", "B"]) - df5 = df.append(df3, sort=sort) - - expected = DataFrame(index=[0, 1], columns=["A", "B", "C"]) - tm.assert_frame_equal(df5, expected) - - def test_append_records(self): - arr1 = np.zeros((2,), dtype=("i4,f4,a10")) - arr1[:] = [(1, 2.0, "Hello"), (2, 3.0, "World")] - - arr2 = np.zeros((3,), dtype=("i4,f4,a10")) - arr2[:] = [(3, 4.0, "foo"), (5, 6.0, "bar"), (7.0, 8.0, "baz")] - - df1 = DataFrame(arr1) - df2 = DataFrame(arr2) - - result = df1.append(df2, ignore_index=True) - expected = DataFrame(np.concatenate((arr1, arr2))) - tm.assert_frame_equal(result, expected) - - # rewrite sort fixture, since we also want to test default of None - def test_append_sorts(self, sort): - df1 = DataFrame({"a": [1, 2], "b": [1, 2]}, columns=["b", "a"]) - df2 = DataFrame({"a": [1, 2], "c": [3, 4]}, index=[2, 3]) - - with tm.assert_produces_warning(None): - result = df1.append(df2, sort=sort) - - # for None / True - expected = DataFrame( - {"b": [1, 2, None, None], "a": [1, 2, 1, 2], "c": [None, None, 3, 4]}, - columns=["a", "b", "c"], - ) - if sort is False: - expected = expected[["b", "a", "c"]] - tm.assert_frame_equal(result, expected) - - def test_append_different_columns(self, sort): - df = DataFrame( - { - "bools": np.random.randn(10) > 0, - "ints": np.random.randint(0, 10, 10), - "floats": np.random.randn(10), - "strings": ["foo", "bar"] * 5, - } - ) - - a = df[:5].loc[:, ["bools", "ints", "floats"]] - b = df[5:].loc[:, ["strings", "ints", "floats"]] - - appended = a.append(b, sort=sort) - assert isna(appended["strings"][0:4]).all() - assert isna(appended["bools"][5:]).all() - - def test_append_many(self, sort, float_frame): - chunks = [ - float_frame[:5], - float_frame[5:10], - float_frame[10:15], - float_frame[15:], - ] - - result = chunks[0].append(chunks[1:]) - tm.assert_frame_equal(result, float_frame) - - chunks[-1] = chunks[-1].copy() - chunks[-1]["foo"] = "bar" - result = chunks[0].append(chunks[1:], sort=sort) - tm.assert_frame_equal(result.loc[:, float_frame.columns], float_frame) - assert (result["foo"][15:] == "bar").all() - assert result["foo"][:15].isna().all() - - def test_append_preserve_index_name(self): - # #980 - df1 = DataFrame(columns=["A", "B", "C"]) - df1 = df1.set_index(["A"]) - df2 = DataFrame(data=[[1, 4, 7], [2, 5, 8], [3, 6, 9]], columns=["A", "B", "C"]) - df2 = df2.set_index(["A"]) - - result = df1.append(df2) - assert result.index.name == "A" - - indexes_can_append = [ - pd.RangeIndex(3), - Index([4, 5, 6]), - Index([4.5, 5.5, 6.5]), - Index(list("abc")), - pd.CategoricalIndex("A B C".split()), - pd.CategoricalIndex("D E F".split(), ordered=True), - pd.IntervalIndex.from_breaks([7, 8, 9, 10]), - pd.DatetimeIndex( - [ - dt.datetime(2013, 1, 3, 0, 0), - dt.datetime(2013, 1, 3, 6, 10), - dt.datetime(2013, 1, 3, 7, 12), - ] - ), - ] - - indexes_cannot_append_with_other = [ - pd.MultiIndex.from_arrays(["A B C".split(), "D E F".split()]) - ] - - all_indexes = indexes_can_append + indexes_cannot_append_with_other - - @pytest.mark.parametrize("index", all_indexes, ids=lambda x: type(x).__name__) - def test_append_same_columns_type(self, index): - # GH18359 - - # df wider than ser - df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=index) - ser_index = index[:2] - ser = Series([7, 8], index=ser_index, name=2) - result = df.append(ser) - expected = DataFrame( - [[1.0, 2.0, 3.0], [4, 5, 6], [7, 8, np.nan]], index=[0, 1, 2], columns=index - ) - tm.assert_frame_equal(result, expected) - - # ser wider than df - ser_index = index - index = index[:2] - df = DataFrame([[1, 2], [4, 5]], columns=index) - ser = Series([7, 8, 9], index=ser_index, name=2) - result = df.append(ser) - expected = DataFrame( - [[1, 2, np.nan], [4, 5, np.nan], [7, 8, 9]], - index=[0, 1, 2], - columns=ser_index, - ) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( - "df_columns, series_index", - combinations(indexes_can_append, r=2), - ids=lambda x: type(x).__name__, - ) - def test_append_different_columns_types(self, df_columns, series_index): - # GH18359 - # See also test 'test_append_different_columns_types_raises' below - # for errors raised when appending - - df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=df_columns) - ser = Series([7, 8, 9], index=series_index, name=2) - - result = df.append(ser) - idx_diff = ser.index.difference(df_columns) - combined_columns = Index(df_columns.tolist()).append(idx_diff) - expected = DataFrame( - [ - [1.0, 2.0, 3.0, np.nan, np.nan, np.nan], - [4, 5, 6, np.nan, np.nan, np.nan], - [np.nan, np.nan, np.nan, 7, 8, 9], - ], - index=[0, 1, 2], - columns=combined_columns, - ) - tm.assert_frame_equal(result, expected) - - @pytest.mark.parametrize( - "index_can_append", indexes_can_append, ids=lambda x: type(x).__name__ - ) - @pytest.mark.parametrize( - "index_cannot_append_with_other", - indexes_cannot_append_with_other, - ids=lambda x: type(x).__name__, - ) - def test_append_different_columns_types_raises( - self, index_can_append, index_cannot_append_with_other - ): - # GH18359 - # Dataframe.append will raise if MultiIndex appends - # or is appended to a different index type - # - # See also test 'test_append_different_columns_types' above for - # appending without raising. - - df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=index_can_append) - ser = Series([7, 8, 9], index=index_cannot_append_with_other, name=2) - msg = ( - r"Expected tuple, got (int|long|float|str|" - r"pandas._libs.interval.Interval)|" - r"object of type '(int|float|Timestamp|" - r"pandas._libs.interval.Interval)' has no len\(\)|" - ) - with pytest.raises(TypeError, match=msg): - df.append(ser) - - df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=index_cannot_append_with_other) - ser = Series([7, 8, 9], index=index_can_append, name=2) - - with pytest.raises(TypeError, match=msg): - df.append(ser) - - def test_append_dtype_coerce(self, sort): - - # GH 4993 - # appending with datetime will incorrectly convert datetime64 - - df1 = DataFrame( - index=[1, 2], - data=[dt.datetime(2013, 1, 1, 0, 0), dt.datetime(2013, 1, 2, 0, 0)], - columns=["start_time"], - ) - df2 = DataFrame( - index=[4, 5], - data=[ - [dt.datetime(2013, 1, 3, 0, 0), dt.datetime(2013, 1, 3, 6, 10)], - [dt.datetime(2013, 1, 4, 0, 0), dt.datetime(2013, 1, 4, 7, 10)], - ], - columns=["start_time", "end_time"], - ) - - expected = concat( - [ - Series( - [ - pd.NaT, - pd.NaT, - dt.datetime(2013, 1, 3, 6, 10), - dt.datetime(2013, 1, 4, 7, 10), - ], - name="end_time", - ), - Series( - [ - dt.datetime(2013, 1, 1, 0, 0), - dt.datetime(2013, 1, 2, 0, 0), - dt.datetime(2013, 1, 3, 0, 0), - dt.datetime(2013, 1, 4, 0, 0), - ], - name="start_time", - ), - ], - axis=1, - sort=sort, - ) - result = df1.append(df2, ignore_index=True, sort=sort) - if sort: - expected = expected[["end_time", "start_time"]] - else: - expected = expected[["start_time", "end_time"]] - - tm.assert_frame_equal(result, expected) - - def test_append_missing_column_proper_upcast(self, sort): - df1 = DataFrame({"A": np.array([1, 2, 3, 4], dtype="i8")}) - df2 = DataFrame({"B": np.array([True, False, True, False], dtype=bool)}) - - appended = df1.append(df2, ignore_index=True, sort=sort) - assert appended["A"].dtype == "f8" - assert appended["B"].dtype == "O" - - def test_append_empty_frame_to_series_with_dateutil_tz(self): - # GH 23682 - date = Timestamp("2018-10-24 07:30:00", tz=dateutil.tz.tzutc()) - s = Series({"date": date, "a": 1.0, "b": 2.0}) - df = DataFrame(columns=["c", "d"]) - result_a = df.append(s, ignore_index=True) - expected = DataFrame( - [[np.nan, np.nan, 1.0, 2.0, date]], columns=["c", "d", "a", "b", "date"] - ) - # These columns get cast to object after append - expected["c"] = expected["c"].astype(object) - expected["d"] = expected["d"].astype(object) - tm.assert_frame_equal(result_a, expected) - - expected = DataFrame( - [[np.nan, np.nan, 1.0, 2.0, date]] * 2, columns=["c", "d", "a", "b", "date"] - ) - expected["c"] = expected["c"].astype(object) - expected["d"] = expected["d"].astype(object) - - result_b = result_a.append(s, ignore_index=True) - tm.assert_frame_equal(result_b, expected) - - # column order is different - expected = expected[["c", "d", "date", "a", "b"]] - result = df.append([s, s], ignore_index=True) - tm.assert_frame_equal(result, expected) - - def test_append_empty_tz_frame_with_datetime64ns(self): - # https://github.com/pandas-dev/pandas/issues/35460 - df = DataFrame(columns=["a"]).astype("datetime64[ns, UTC]") - - # pd.NaT gets inferred as tz-naive, so append result is tz-naive - result = df.append({"a": pd.NaT}, ignore_index=True) - expected = DataFrame({"a": [pd.NaT]}).astype("datetime64[ns]") - tm.assert_frame_equal(result, expected) - - # also test with typed value to append - df = DataFrame(columns=["a"]).astype("datetime64[ns, UTC]") - result = df.append( - Series({"a": pd.NaT}, dtype="datetime64[ns]"), ignore_index=True - ) - expected = DataFrame({"a": [pd.NaT]}).astype("datetime64[ns]") - tm.assert_frame_equal(result, expected) - - class TestConcatenate: def test_concat_copy(self): df = DataFrame(np.random.randn(4, 3)) @@ -2932,349 +1843,3 @@ def test_concat_preserves_extension_int64_dtype(): result = pd.concat([df_a, df_b], ignore_index=True) expected = DataFrame({"a": [-1, None], "b": [None, 1]}, dtype="Int64") tm.assert_frame_equal(result, expected) - - -class TestSeriesConcat: - @pytest.mark.parametrize( - "dtype", ["float64", "int8", "uint8", "bool", "m8[ns]", "M8[ns]"] - ) - def test_concat_empty_series_dtypes_match_roundtrips(self, dtype): - dtype = np.dtype(dtype) - - result = pd.concat([Series(dtype=dtype)]) - assert result.dtype == dtype - - result = pd.concat([Series(dtype=dtype), Series(dtype=dtype)]) - assert result.dtype == dtype - - def test_concat_empty_series_dtypes_roundtrips(self): - - # round-tripping with self & like self - dtypes = map(np.dtype, ["float64", "int8", "uint8", "bool", "m8[ns]", "M8[ns]"]) - - def int_result_type(dtype, dtype2): - typs = {dtype.kind, dtype2.kind} - if not len(typs - {"i", "u", "b"}) and ( - dtype.kind == "i" or dtype2.kind == "i" - ): - return "i" - elif not len(typs - {"u", "b"}) and ( - dtype.kind == "u" or dtype2.kind == "u" - ): - return "u" - return None - - def float_result_type(dtype, dtype2): - typs = {dtype.kind, dtype2.kind} - if not len(typs - {"f", "i", "u"}) and ( - dtype.kind == "f" or dtype2.kind == "f" - ): - return "f" - return None - - def get_result_type(dtype, dtype2): - result = float_result_type(dtype, dtype2) - if result is not None: - return result - result = int_result_type(dtype, dtype2) - if result is not None: - return result - return "O" - - for dtype in dtypes: - for dtype2 in dtypes: - if dtype == dtype2: - continue - - expected = get_result_type(dtype, dtype2) - result = pd.concat([Series(dtype=dtype), Series(dtype=dtype2)]).dtype - assert result.kind == expected - - @pytest.mark.parametrize( - "left,right,expected", - [ - # booleans - (np.bool_, np.int32, np.int32), - (np.bool_, np.float32, np.object_), - # datetime-like - ("m8[ns]", np.bool_, np.object_), - ("m8[ns]", np.int64, np.object_), - ("M8[ns]", np.bool_, np.object_), - ("M8[ns]", np.int64, np.object_), - # categorical - ("category", "category", "category"), - ("category", "object", "object"), - ], - ) - def test_concat_empty_series_dtypes(self, left, right, expected): - result = pd.concat([Series(dtype=left), Series(dtype=right)]) - assert result.dtype == expected - - def test_concat_empty_series_dtypes_triple(self): - - assert ( - pd.concat( - [Series(dtype="M8[ns]"), Series(dtype=np.bool_), Series(dtype=np.int64)] - ).dtype - == np.object_ - ) - - def test_concat_empty_series_dtype_category_with_array(self): - # GH#18515 - assert ( - pd.concat( - [Series(np.array([]), dtype="category"), Series(dtype="float64")] - ).dtype - == "float64" - ) - - def test_concat_empty_series_dtypes_sparse(self): - result = pd.concat( - [ - Series(dtype="float64").astype("Sparse"), - Series(dtype="float64").astype("Sparse"), - ] - ) - assert result.dtype == "Sparse[float64]" - - result = pd.concat( - [Series(dtype="float64").astype("Sparse"), Series(dtype="float64")] - ) - # TODO: release-note: concat sparse dtype - expected = pd.SparseDtype(np.float64) - assert result.dtype == expected - - result = pd.concat( - [Series(dtype="float64").astype("Sparse"), Series(dtype="object")] - ) - # TODO: release-note: concat sparse dtype - expected = pd.SparseDtype("object") - assert result.dtype == expected - - -class TestDataFrameConcat: - def test_concat_multiple_frames_dtypes(self): - - # GH#2759 - A = DataFrame(data=np.ones((10, 2)), columns=["foo", "bar"], dtype=np.float64) - B = DataFrame(data=np.ones((10, 2)), dtype=np.float32) - results = pd.concat((A, B), axis=1).dtypes - expected = Series( - [np.dtype("float64")] * 2 + [np.dtype("float32")] * 2, - index=["foo", "bar", 0, 1], - ) - tm.assert_series_equal(results, expected) - - def test_concat_multiple_tzs(self): - # GH#12467 - # combining datetime tz-aware and naive DataFrames - ts1 = Timestamp("2015-01-01", tz=None) - ts2 = Timestamp("2015-01-01", tz="UTC") - ts3 = Timestamp("2015-01-01", tz="EST") - - df1 = DataFrame(dict(time=[ts1])) - df2 = DataFrame(dict(time=[ts2])) - df3 = DataFrame(dict(time=[ts3])) - - results = pd.concat([df1, df2]).reset_index(drop=True) - expected = DataFrame(dict(time=[ts1, ts2]), dtype=object) - tm.assert_frame_equal(results, expected) - - results = pd.concat([df1, df3]).reset_index(drop=True) - expected = DataFrame(dict(time=[ts1, ts3]), dtype=object) - tm.assert_frame_equal(results, expected) - - results = pd.concat([df2, df3]).reset_index(drop=True) - expected = DataFrame(dict(time=[ts2, ts3])) - tm.assert_frame_equal(results, expected) - - @pytest.mark.parametrize( - "t1", - [ - "2015-01-01", - pytest.param( - pd.NaT, - marks=pytest.mark.xfail( - reason="GH23037 incorrect dtype when concatenating" - ), - ), - ], - ) - def test_concat_tz_NaT(self, t1): - # GH#22796 - # Concating tz-aware multicolumn DataFrames - ts1 = Timestamp(t1, tz="UTC") - ts2 = Timestamp("2015-01-01", tz="UTC") - ts3 = Timestamp("2015-01-01", tz="UTC") - - df1 = DataFrame([[ts1, ts2]]) - df2 = DataFrame([[ts3]]) - - result = pd.concat([df1, df2]) - expected = DataFrame([[ts1, ts2], [ts3, pd.NaT]], index=[0, 0]) - - tm.assert_frame_equal(result, expected) - - def test_concat_tz_not_aligned(self): - # GH#22796 - ts = pd.to_datetime([1, 2]).tz_localize("UTC") - a = DataFrame({"A": ts}) - b = DataFrame({"A": ts, "B": ts}) - result = pd.concat([a, b], sort=True, ignore_index=True) - expected = DataFrame( - {"A": list(ts) + list(ts), "B": [pd.NaT, pd.NaT] + list(ts)} - ) - tm.assert_frame_equal(result, expected) - - def test_concat_tuple_keys(self): - # GH#14438 - df1 = DataFrame(np.ones((2, 2)), columns=list("AB")) - df2 = DataFrame(np.ones((3, 2)) * 2, columns=list("AB")) - results = pd.concat((df1, df2), keys=[("bee", "bah"), ("bee", "boo")]) - expected = DataFrame( - { - "A": { - ("bee", "bah", 0): 1.0, - ("bee", "bah", 1): 1.0, - ("bee", "boo", 0): 2.0, - ("bee", "boo", 1): 2.0, - ("bee", "boo", 2): 2.0, - }, - "B": { - ("bee", "bah", 0): 1.0, - ("bee", "bah", 1): 1.0, - ("bee", "boo", 0): 2.0, - ("bee", "boo", 1): 2.0, - ("bee", "boo", 2): 2.0, - }, - } - ) - tm.assert_frame_equal(results, expected) - - def test_concat_named_keys(self): - # GH#14252 - df = DataFrame({"foo": [1, 2], "bar": [0.1, 0.2]}) - index = Index(["a", "b"], name="baz") - concatted_named_from_keys = pd.concat([df, df], keys=index) - expected_named = DataFrame( - {"foo": [1, 2, 1, 2], "bar": [0.1, 0.2, 0.1, 0.2]}, - index=pd.MultiIndex.from_product((["a", "b"], [0, 1]), names=["baz", None]), - ) - tm.assert_frame_equal(concatted_named_from_keys, expected_named) - - index_no_name = Index(["a", "b"], name=None) - concatted_named_from_names = pd.concat( - [df, df], keys=index_no_name, names=["baz"] - ) - tm.assert_frame_equal(concatted_named_from_names, expected_named) - - concatted_unnamed = pd.concat([df, df], keys=index_no_name) - expected_unnamed = DataFrame( - {"foo": [1, 2, 1, 2], "bar": [0.1, 0.2, 0.1, 0.2]}, - index=pd.MultiIndex.from_product((["a", "b"], [0, 1]), names=[None, None]), - ) - tm.assert_frame_equal(concatted_unnamed, expected_unnamed) - - def test_concat_axis_parameter(self): - # GH#14369 - df1 = DataFrame({"A": [0.1, 0.2]}, index=range(2)) - df2 = DataFrame({"A": [0.3, 0.4]}, index=range(2)) - - # Index/row/0 DataFrame - expected_index = DataFrame({"A": [0.1, 0.2, 0.3, 0.4]}, index=[0, 1, 0, 1]) - - concatted_index = pd.concat([df1, df2], axis="index") - tm.assert_frame_equal(concatted_index, expected_index) - - concatted_row = pd.concat([df1, df2], axis="rows") - tm.assert_frame_equal(concatted_row, expected_index) - - concatted_0 = pd.concat([df1, df2], axis=0) - tm.assert_frame_equal(concatted_0, expected_index) - - # Columns/1 DataFrame - expected_columns = DataFrame( - [[0.1, 0.3], [0.2, 0.4]], index=[0, 1], columns=["A", "A"] - ) - - concatted_columns = pd.concat([df1, df2], axis="columns") - tm.assert_frame_equal(concatted_columns, expected_columns) - - concatted_1 = pd.concat([df1, df2], axis=1) - tm.assert_frame_equal(concatted_1, expected_columns) - - series1 = Series([0.1, 0.2]) - series2 = Series([0.3, 0.4]) - - # Index/row/0 Series - expected_index_series = Series([0.1, 0.2, 0.3, 0.4], index=[0, 1, 0, 1]) - - concatted_index_series = pd.concat([series1, series2], axis="index") - tm.assert_series_equal(concatted_index_series, expected_index_series) - - concatted_row_series = pd.concat([series1, series2], axis="rows") - tm.assert_series_equal(concatted_row_series, expected_index_series) - - concatted_0_series = pd.concat([series1, series2], axis=0) - tm.assert_series_equal(concatted_0_series, expected_index_series) - - # Columns/1 Series - expected_columns_series = DataFrame( - [[0.1, 0.3], [0.2, 0.4]], index=[0, 1], columns=[0, 1] - ) - - concatted_columns_series = pd.concat([series1, series2], axis="columns") - tm.assert_frame_equal(concatted_columns_series, expected_columns_series) - - concatted_1_series = pd.concat([series1, series2], axis=1) - tm.assert_frame_equal(concatted_1_series, expected_columns_series) - - # Testing ValueError - with pytest.raises(ValueError, match="No axis named"): - pd.concat([series1, series2], axis="something") - - def test_concat_numerical_names(self): - # GH#15262, GH#12223 - df = DataFrame( - {"col": range(9)}, - dtype="int32", - index=( - pd.MultiIndex.from_product( - [["A0", "A1", "A2"], ["B0", "B1", "B2"]], names=[1, 2] - ) - ), - ) - result = pd.concat((df.iloc[:2, :], df.iloc[-2:, :])) - expected = DataFrame( - {"col": [0, 1, 7, 8]}, - dtype="int32", - index=pd.MultiIndex.from_tuples( - [("A0", "B0"), ("A0", "B1"), ("A2", "B1"), ("A2", "B2")], names=[1, 2] - ), - ) - tm.assert_frame_equal(result, expected) - - def test_concat_astype_dup_col(self): - # GH#23049 - df = DataFrame([{"a": "b"}]) - df = pd.concat([df, df], axis=1) - - result = df.astype("category") - expected = DataFrame( - np.array(["b", "b"]).reshape(1, 2), columns=["a", "a"] - ).astype("category") - tm.assert_frame_equal(result, expected) - - def test_concat_datetime_datetime64_frame(self): - # GH#2624 - rows = [] - rows.append([datetime(2010, 1, 1), 1]) - rows.append([datetime(2010, 1, 2), "hi"]) - - df2_obj = DataFrame.from_records(rows, columns=["date", "test"]) - - ind = date_range(start="2000/1/1", freq="D", periods=10) - df1 = DataFrame({"date": ind, "test": range(10)}) - - # it works! - pd.concat([df1, df2_obj]) diff --git a/pandas/tests/reshape/concat/test_dataframe.py b/pandas/tests/reshape/concat/test_dataframe.py new file mode 100644 index 0000000000000..21abd1bed7cbc --- /dev/null +++ b/pandas/tests/reshape/concat/test_dataframe.py @@ -0,0 +1,236 @@ +from datetime import datetime + +import numpy as np +import pytest + +import pandas as pd +from pandas import DataFrame, Index, Series, Timestamp, date_range +import pandas._testing as tm + + +class TestDataFrameConcat: + def test_concat_multiple_frames_dtypes(self): + + # GH#2759 + A = DataFrame(data=np.ones((10, 2)), columns=["foo", "bar"], dtype=np.float64) + B = DataFrame(data=np.ones((10, 2)), dtype=np.float32) + results = pd.concat((A, B), axis=1).dtypes + expected = Series( + [np.dtype("float64")] * 2 + [np.dtype("float32")] * 2, + index=["foo", "bar", 0, 1], + ) + tm.assert_series_equal(results, expected) + + def test_concat_multiple_tzs(self): + # GH#12467 + # combining datetime tz-aware and naive DataFrames + ts1 = Timestamp("2015-01-01", tz=None) + ts2 = Timestamp("2015-01-01", tz="UTC") + ts3 = Timestamp("2015-01-01", tz="EST") + + df1 = DataFrame(dict(time=[ts1])) + df2 = DataFrame(dict(time=[ts2])) + df3 = DataFrame(dict(time=[ts3])) + + results = pd.concat([df1, df2]).reset_index(drop=True) + expected = DataFrame(dict(time=[ts1, ts2]), dtype=object) + tm.assert_frame_equal(results, expected) + + results = pd.concat([df1, df3]).reset_index(drop=True) + expected = DataFrame(dict(time=[ts1, ts3]), dtype=object) + tm.assert_frame_equal(results, expected) + + results = pd.concat([df2, df3]).reset_index(drop=True) + expected = DataFrame(dict(time=[ts2, ts3])) + tm.assert_frame_equal(results, expected) + + @pytest.mark.parametrize( + "t1", + [ + "2015-01-01", + pytest.param( + pd.NaT, + marks=pytest.mark.xfail( + reason="GH23037 incorrect dtype when concatenating" + ), + ), + ], + ) + def test_concat_tz_NaT(self, t1): + # GH#22796 + # Concating tz-aware multicolumn DataFrames + ts1 = Timestamp(t1, tz="UTC") + ts2 = Timestamp("2015-01-01", tz="UTC") + ts3 = Timestamp("2015-01-01", tz="UTC") + + df1 = DataFrame([[ts1, ts2]]) + df2 = DataFrame([[ts3]]) + + result = pd.concat([df1, df2]) + expected = DataFrame([[ts1, ts2], [ts3, pd.NaT]], index=[0, 0]) + + tm.assert_frame_equal(result, expected) + + def test_concat_tz_not_aligned(self): + # GH#22796 + ts = pd.to_datetime([1, 2]).tz_localize("UTC") + a = DataFrame({"A": ts}) + b = DataFrame({"A": ts, "B": ts}) + result = pd.concat([a, b], sort=True, ignore_index=True) + expected = DataFrame( + {"A": list(ts) + list(ts), "B": [pd.NaT, pd.NaT] + list(ts)} + ) + tm.assert_frame_equal(result, expected) + + def test_concat_tuple_keys(self): + # GH#14438 + df1 = DataFrame(np.ones((2, 2)), columns=list("AB")) + df2 = DataFrame(np.ones((3, 2)) * 2, columns=list("AB")) + results = pd.concat((df1, df2), keys=[("bee", "bah"), ("bee", "boo")]) + expected = DataFrame( + { + "A": { + ("bee", "bah", 0): 1.0, + ("bee", "bah", 1): 1.0, + ("bee", "boo", 0): 2.0, + ("bee", "boo", 1): 2.0, + ("bee", "boo", 2): 2.0, + }, + "B": { + ("bee", "bah", 0): 1.0, + ("bee", "bah", 1): 1.0, + ("bee", "boo", 0): 2.0, + ("bee", "boo", 1): 2.0, + ("bee", "boo", 2): 2.0, + }, + } + ) + tm.assert_frame_equal(results, expected) + + def test_concat_named_keys(self): + # GH#14252 + df = DataFrame({"foo": [1, 2], "bar": [0.1, 0.2]}) + index = Index(["a", "b"], name="baz") + concatted_named_from_keys = pd.concat([df, df], keys=index) + expected_named = DataFrame( + {"foo": [1, 2, 1, 2], "bar": [0.1, 0.2, 0.1, 0.2]}, + index=pd.MultiIndex.from_product((["a", "b"], [0, 1]), names=["baz", None]), + ) + tm.assert_frame_equal(concatted_named_from_keys, expected_named) + + index_no_name = Index(["a", "b"], name=None) + concatted_named_from_names = pd.concat( + [df, df], keys=index_no_name, names=["baz"] + ) + tm.assert_frame_equal(concatted_named_from_names, expected_named) + + concatted_unnamed = pd.concat([df, df], keys=index_no_name) + expected_unnamed = DataFrame( + {"foo": [1, 2, 1, 2], "bar": [0.1, 0.2, 0.1, 0.2]}, + index=pd.MultiIndex.from_product((["a", "b"], [0, 1]), names=[None, None]), + ) + tm.assert_frame_equal(concatted_unnamed, expected_unnamed) + + def test_concat_axis_parameter(self): + # GH#14369 + df1 = DataFrame({"A": [0.1, 0.2]}, index=range(2)) + df2 = DataFrame({"A": [0.3, 0.4]}, index=range(2)) + + # Index/row/0 DataFrame + expected_index = DataFrame({"A": [0.1, 0.2, 0.3, 0.4]}, index=[0, 1, 0, 1]) + + concatted_index = pd.concat([df1, df2], axis="index") + tm.assert_frame_equal(concatted_index, expected_index) + + concatted_row = pd.concat([df1, df2], axis="rows") + tm.assert_frame_equal(concatted_row, expected_index) + + concatted_0 = pd.concat([df1, df2], axis=0) + tm.assert_frame_equal(concatted_0, expected_index) + + # Columns/1 DataFrame + expected_columns = DataFrame( + [[0.1, 0.3], [0.2, 0.4]], index=[0, 1], columns=["A", "A"] + ) + + concatted_columns = pd.concat([df1, df2], axis="columns") + tm.assert_frame_equal(concatted_columns, expected_columns) + + concatted_1 = pd.concat([df1, df2], axis=1) + tm.assert_frame_equal(concatted_1, expected_columns) + + series1 = Series([0.1, 0.2]) + series2 = Series([0.3, 0.4]) + + # Index/row/0 Series + expected_index_series = Series([0.1, 0.2, 0.3, 0.4], index=[0, 1, 0, 1]) + + concatted_index_series = pd.concat([series1, series2], axis="index") + tm.assert_series_equal(concatted_index_series, expected_index_series) + + concatted_row_series = pd.concat([series1, series2], axis="rows") + tm.assert_series_equal(concatted_row_series, expected_index_series) + + concatted_0_series = pd.concat([series1, series2], axis=0) + tm.assert_series_equal(concatted_0_series, expected_index_series) + + # Columns/1 Series + expected_columns_series = DataFrame( + [[0.1, 0.3], [0.2, 0.4]], index=[0, 1], columns=[0, 1] + ) + + concatted_columns_series = pd.concat([series1, series2], axis="columns") + tm.assert_frame_equal(concatted_columns_series, expected_columns_series) + + concatted_1_series = pd.concat([series1, series2], axis=1) + tm.assert_frame_equal(concatted_1_series, expected_columns_series) + + # Testing ValueError + with pytest.raises(ValueError, match="No axis named"): + pd.concat([series1, series2], axis="something") + + def test_concat_numerical_names(self): + # GH#15262, GH#12223 + df = DataFrame( + {"col": range(9)}, + dtype="int32", + index=( + pd.MultiIndex.from_product( + [["A0", "A1", "A2"], ["B0", "B1", "B2"]], names=[1, 2] + ) + ), + ) + result = pd.concat((df.iloc[:2, :], df.iloc[-2:, :])) + expected = DataFrame( + {"col": [0, 1, 7, 8]}, + dtype="int32", + index=pd.MultiIndex.from_tuples( + [("A0", "B0"), ("A0", "B1"), ("A2", "B1"), ("A2", "B2")], names=[1, 2] + ), + ) + tm.assert_frame_equal(result, expected) + + def test_concat_astype_dup_col(self): + # GH#23049 + df = DataFrame([{"a": "b"}]) + df = pd.concat([df, df], axis=1) + + result = df.astype("category") + expected = DataFrame( + np.array(["b", "b"]).reshape(1, 2), columns=["a", "a"] + ).astype("category") + tm.assert_frame_equal(result, expected) + + def test_concat_datetime_datetime64_frame(self): + # GH#2624 + rows = [] + rows.append([datetime(2010, 1, 1), 1]) + rows.append([datetime(2010, 1, 2), "hi"]) + + df2_obj = DataFrame.from_records(rows, columns=["date", "test"]) + + ind = date_range(start="2000/1/1", freq="D", periods=10) + df1 = DataFrame({"date": ind, "test": range(10)}) + + # it works! + pd.concat([df1, df2_obj]) diff --git a/pandas/tests/reshape/concat/test_series.py b/pandas/tests/reshape/concat/test_series.py new file mode 100644 index 0000000000000..7f84e937736ac --- /dev/null +++ b/pandas/tests/reshape/concat/test_series.py @@ -0,0 +1,123 @@ +import numpy as np +import pytest + +import pandas as pd +from pandas import Series + + +class TestSeriesConcat: + @pytest.mark.parametrize( + "dtype", ["float64", "int8", "uint8", "bool", "m8[ns]", "M8[ns]"] + ) + def test_concat_empty_series_dtypes_match_roundtrips(self, dtype): + dtype = np.dtype(dtype) + + result = pd.concat([Series(dtype=dtype)]) + assert result.dtype == dtype + + result = pd.concat([Series(dtype=dtype), Series(dtype=dtype)]) + assert result.dtype == dtype + + def test_concat_empty_series_dtypes_roundtrips(self): + + # round-tripping with self & like self + dtypes = map(np.dtype, ["float64", "int8", "uint8", "bool", "m8[ns]", "M8[ns]"]) + + def int_result_type(dtype, dtype2): + typs = {dtype.kind, dtype2.kind} + if not len(typs - {"i", "u", "b"}) and ( + dtype.kind == "i" or dtype2.kind == "i" + ): + return "i" + elif not len(typs - {"u", "b"}) and ( + dtype.kind == "u" or dtype2.kind == "u" + ): + return "u" + return None + + def float_result_type(dtype, dtype2): + typs = {dtype.kind, dtype2.kind} + if not len(typs - {"f", "i", "u"}) and ( + dtype.kind == "f" or dtype2.kind == "f" + ): + return "f" + return None + + def get_result_type(dtype, dtype2): + result = float_result_type(dtype, dtype2) + if result is not None: + return result + result = int_result_type(dtype, dtype2) + if result is not None: + return result + return "O" + + for dtype in dtypes: + for dtype2 in dtypes: + if dtype == dtype2: + continue + + expected = get_result_type(dtype, dtype2) + result = pd.concat([Series(dtype=dtype), Series(dtype=dtype2)]).dtype + assert result.kind == expected + + @pytest.mark.parametrize( + "left,right,expected", + [ + # booleans + (np.bool_, np.int32, np.int32), + (np.bool_, np.float32, np.object_), + # datetime-like + ("m8[ns]", np.bool_, np.object_), + ("m8[ns]", np.int64, np.object_), + ("M8[ns]", np.bool_, np.object_), + ("M8[ns]", np.int64, np.object_), + # categorical + ("category", "category", "category"), + ("category", "object", "object"), + ], + ) + def test_concat_empty_series_dtypes(self, left, right, expected): + result = pd.concat([Series(dtype=left), Series(dtype=right)]) + assert result.dtype == expected + + def test_concat_empty_series_dtypes_triple(self): + + assert ( + pd.concat( + [Series(dtype="M8[ns]"), Series(dtype=np.bool_), Series(dtype=np.int64)] + ).dtype + == np.object_ + ) + + def test_concat_empty_series_dtype_category_with_array(self): + # GH#18515 + assert ( + pd.concat( + [Series(np.array([]), dtype="category"), Series(dtype="float64")] + ).dtype + == "float64" + ) + + def test_concat_empty_series_dtypes_sparse(self): + result = pd.concat( + [ + Series(dtype="float64").astype("Sparse"), + Series(dtype="float64").astype("Sparse"), + ] + ) + assert result.dtype == "Sparse[float64]" + + result = pd.concat( + [Series(dtype="float64").astype("Sparse"), Series(dtype="float64")] + ) + # TODO: release-note: concat sparse dtype + expected = pd.SparseDtype(np.float64) + assert result.dtype == expected + + result = pd.concat( + [Series(dtype="float64").astype("Sparse"), Series(dtype="object")] + ) + # TODO: release-note: concat sparse dtype + expected = pd.SparseDtype("object") + assert result.dtype == expected
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37360
2020-10-23T10:05:18Z
2020-10-23T15:27:14Z
2020-10-23T15:27:14Z
2020-10-23T15:27:44Z
DOC: update development documentation for link to built docs #37248
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index 7fbd2e1188901..b281c7cfc7d39 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -598,7 +598,7 @@ Building master branch documentation When pull requests are merged into the pandas ``master`` branch, the main parts of the documentation are also built by Travis-CI. These docs are then hosted `here -<https://dev.pandas.io>`__, see also +<https://pandas.pydata.org/docs/dev/>`__, see also the :ref:`Continuous Integration <contributing.ci>` section. .. _contributing.code:
- [x] closes #37248 cc: @jreback
https://api.github.com/repos/pandas-dev/pandas/pulls/37357
2020-10-23T07:10:36Z
2020-10-24T07:27:52Z
2020-10-24T07:27:51Z
2020-10-24T07:28:07Z
API: require timezone match in DatetimeArray.take
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 99d2a1ee27265..37ea35d044dca 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -370,6 +370,7 @@ Datetimelike - Bug in :meth:`DatetimeIndex.slice_locs` where ``datetime.date`` objects were not accepted (:issue:`34077`) - Bug in :meth:`DatetimeIndex.searchsorted`, :meth:`TimedeltaIndex.searchsorted`, :meth:`PeriodIndex.searchsorted`, and :meth:`Series.searchsorted` with ``datetime64``, ``timedelta64`` or ``Period`` dtype placement of ``NaT`` values being inconsistent with ``NumPy`` (:issue:`36176`, :issue:`36254`) - Inconsistency in :class:`DatetimeArray`, :class:`TimedeltaArray`, and :class:`PeriodArray` setitem casting arrays of strings to datetimelike scalars but not scalar strings (:issue:`36261`) +- Bug in :meth:`DatetimeArray.take` incorrectly allowing ``fill_value`` with a mismatched timezone (:issue:`37356`) - Bug in :class:`DatetimeIndex.shift` incorrectly raising when shifting empty indexes (:issue:`14811`) - :class:`Timestamp` and :class:`DatetimeIndex` comparisons between timezone-aware and timezone-naive objects now follow the standard library ``datetime`` behavior, returning ``True``/``False`` for ``!=``/``==`` and raising for inequality comparisons (:issue:`28507`) - Bug in :meth:`DatetimeIndex.equals` and :meth:`TimedeltaIndex.equals` incorrectly considering ``int64`` indexes as equal (:issue:`36744`) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 444991b38a5b1..4523ea1030ef1 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -480,7 +480,7 @@ def _validate_fill_value(self, fill_value): fill_value = self._validate_scalar(fill_value) except TypeError as err: raise ValueError(msg) from err - return self._unbox(fill_value) + return self._unbox(fill_value, setitem=True) def _validate_shift_value(self, fill_value): # TODO(2.0): once this deprecation is enforced, use _validate_fill_value diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index b1b8b513320e9..0780dcfef23cc 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -473,7 +473,7 @@ def _check_compatible_with(self, other, setitem: bool = False): if setitem: # Stricter check for setitem vs comparison methods if not timezones.tz_compare(self.tz, other.tz): - raise ValueError(f"Timezones don't match. '{self.tz} != {other.tz}'") + raise ValueError(f"Timezones don't match. '{self.tz}' != '{other.tz}'") def _maybe_clear_freq(self): self._freq = None diff --git a/pandas/tests/arrays/test_datetimelike.py b/pandas/tests/arrays/test_datetimelike.py index 3d34948018be4..463196eaa36bf 100644 --- a/pandas/tests/arrays/test_datetimelike.py +++ b/pandas/tests/arrays/test_datetimelike.py @@ -4,7 +4,7 @@ import pytest import pytz -from pandas._libs import OutOfBoundsDatetime +from pandas._libs import OutOfBoundsDatetime, Timestamp from pandas.compat.numpy import np_version_under1p18 import pandas as pd @@ -695,6 +695,15 @@ def test_take_fill_valid(self, arr1d): # require appropriate-dtype if we have a NA value arr.take([-1, 1], allow_fill=True, fill_value=value) + if arr.tz is not None: + # GH#37356 + # Assuming here that arr1d fixture does not include Australia/Melbourne + value = Timestamp.now().tz_localize("Australia/Melbourne") + msg = "Timezones don't match. .* != 'Australia/Melbourne'" + with pytest.raises(ValueError, match=msg): + # require tz match, not just tzawareness match + arr.take([-1, 1], allow_fill=True, fill_value=value) + def test_concat_same_type_invalid(self, arr1d): # different timezones arr = arr1d
Consistent with #37299
https://api.github.com/repos/pandas-dev/pandas/pulls/37356
2020-10-23T04:23:07Z
2020-10-23T17:19:47Z
2020-10-23T17:19:47Z
2020-10-23T18:07:47Z
PERF/ENH: add fast astyping for Categorical
diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py index a0b24342091ec..f3b005b704014 100644 --- a/asv_bench/benchmarks/categoricals.py +++ b/asv_bench/benchmarks/categoricals.py @@ -1,3 +1,5 @@ +import string +import sys import warnings import numpy as np @@ -67,6 +69,47 @@ def time_existing_series(self): pd.Categorical(self.series) +class AsType: + def setup(self): + N = 10 ** 5 + + random_pick = np.random.default_rng().choice + + categories = { + "str": list(string.ascii_letters), + "int": np.random.randint(2 ** 16, size=154), + "float": sys.maxsize * np.random.random((38,)), + "timestamp": [ + pd.Timestamp(x, unit="s") for x in np.random.randint(2 ** 18, size=578) + ], + } + + self.df = pd.DataFrame( + {col: random_pick(cats, N) for col, cats in categories.items()} + ) + + for col in ("int", "float", "timestamp"): + self.df[col + "_as_str"] = self.df[col].astype(str) + + for col in self.df.columns: + self.df[col] = self.df[col].astype("category") + + def astype_str(self): + [self.df[col].astype("str") for col in "int float timestamp".split()] + + def astype_int(self): + [self.df[col].astype("int") for col in "int_as_str timestamp".split()] + + def astype_float(self): + [ + self.df[col].astype("float") + for col in "float_as_str int int_as_str timestamp".split() + ] + + def astype_datetime(self): + self.df["float"].astype(pd.DatetimeTZDtype(tz="US/Pacific")) + + class Concat: def setup(self): N = 10 ** 5 diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index e00b177f2a2fc..669599bb5845a 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -499,6 +499,7 @@ Performance improvements - Reduced peak memory usage in :meth:`DataFrame.to_pickle` when using ``protocol=5`` in python 3.8+ (:issue:`34244`) - faster ``dir`` calls when many index labels, e.g. ``dir(ser)`` (:issue:`37450`) - Performance improvement in :class:`ExpandingGroupby` (:issue:`37064`) +- Performance improvement in :meth:`Series.astype` and :meth:`DataFrame.astype` for :class:`Categorical` (:issue:`8628`) - Performance improvement in :meth:`pd.DataFrame.groupby` for ``float`` ``dtype`` (:issue:`28303`), changes of the underlying hash-function can lead to changes in float based indexes sort ordering for ties (e.g. :meth:`pd.Index.value_counts`) - Performance improvement in :meth:`pd.isin` for inputs with more than 1e6 elements diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index e57ef17272a9d..62e508c491740 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -403,20 +403,42 @@ def astype(self, dtype: Dtype, copy: bool = True) -> ArrayLike: If copy is set to False and dtype is categorical, the original object is returned. """ - if is_categorical_dtype(dtype): + if self.dtype is dtype: + result = self.copy() if copy else self + + elif is_categorical_dtype(dtype): dtype = cast(Union[str, CategoricalDtype], dtype) # GH 10696/18593/18630 dtype = self.dtype.update_dtype(dtype) - result = self.copy() if copy else self - if dtype == self.dtype: - return result - return result._set_dtype(dtype) - if is_extension_array_dtype(dtype): - return array(self, dtype=dtype, copy=copy) - if is_integer_dtype(dtype) and self.isna().any(): + self = self.copy() if copy else self + result = self._set_dtype(dtype) + + # TODO: consolidate with ndarray case? + elif is_extension_array_dtype(dtype): + result = array(self, dtype=dtype, copy=copy) + + elif is_integer_dtype(dtype) and self.isna().any(): raise ValueError("Cannot convert float NaN to integer") - return np.array(self, dtype=dtype, copy=copy) + + elif len(self.codes) == 0 or len(self.categories) == 0: + result = np.array(self, dtype=dtype, copy=copy) + + else: + # GH8628 (PERF): astype category codes instead of astyping array + try: + astyped_cats = self.categories.astype(dtype=dtype, copy=copy) + except ( + TypeError, # downstream error msg for CategoricalIndex is misleading + ValueError, + ): + msg = f"Cannot cast {self.categories.dtype} dtype to {dtype}" + raise ValueError(msg) + + astyped_cats = extract_array(astyped_cats, extract_numpy=True) + result = take_1d(astyped_cats, libalgos.ensure_platform_int(self._codes)) + + return result @cache_readonly def itemsize(self) -> int: diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index d52a8ae935688..0b0f985697da9 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -6,7 +6,7 @@ from pandas._libs import index as libindex from pandas._libs.tslibs import BaseOffset, Period, Resolution, Tick from pandas._libs.tslibs.parsing import DateParseError, parse_time_string -from pandas._typing import DtypeObj, Label +from pandas._typing import DtypeObj from pandas.errors import InvalidIndexError from pandas.util._decorators import Appender, cache_readonly, doc diff --git a/pandas/tests/arrays/categorical/test_dtypes.py b/pandas/tests/arrays/categorical/test_dtypes.py index deafa22a6e8eb..12654388de904 100644 --- a/pandas/tests/arrays/categorical/test_dtypes.py +++ b/pandas/tests/arrays/categorical/test_dtypes.py @@ -127,7 +127,7 @@ def test_astype(self, ordered): expected = np.array(cat) tm.assert_numpy_array_equal(result, expected) - msg = "could not convert string to float" + msg = r"Cannot cast object dtype to <class 'float'>" with pytest.raises(ValueError, match=msg): cat.astype(float) @@ -138,7 +138,7 @@ def test_astype(self, ordered): tm.assert_numpy_array_equal(result, expected) result = cat.astype(int) - expected = np.array(cat, dtype=int) + expected = np.array(cat, dtype="int64") tm.assert_numpy_array_equal(result, expected) result = cat.astype(float) diff --git a/pandas/tests/series/test_dtypes.py b/pandas/tests/series/test_dtypes.py index 46c41efc09fdf..865ae565b6501 100644 --- a/pandas/tests/series/test_dtypes.py +++ b/pandas/tests/series/test_dtypes.py @@ -60,7 +60,7 @@ def test_astype_categorical_to_other(self): 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\(\)" + msg = r"Cannot cast object dtype to float64" with pytest.raises(ValueError, match=msg): ser.astype("float64") @@ -68,7 +68,7 @@ def test_astype_categorical_to_other(self): exp = Series(["a", "b", "b", "a", "a", "c", "c", "c"]) tm.assert_series_equal(cat.astype("str"), exp) s2 = Series(Categorical(["1", "2", "3", "4"])) - exp2 = Series([1, 2, 3, 4]).astype(int) + exp2 = Series([1, 2, 3, 4]).astype("int64") tm.assert_series_equal(s2.astype("int"), exp2) # object don't sort correctly, so just compare that we have the same
- [x] closes #8628 - [ ] tests added / passed - [x] benchmarks added - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry To illustrate the speed-up, the set-up is (from OP): ```python import numpy as np import pandas as pd rng = np.random.default_rng() df = pd.DataFrame( rng.choice(np.array(list("abcde")), 4_000_000).reshape(1_000_000, 4), columns=list("ABCD"), ) for col in df.columns: df[col] = df[col].astype("category") ``` On master ``` python In [5]: %timeit [df[col].astype('unicode') for col in df.columns] 250 ms ± 601 µs per loop (mean ± std. dev. of 7 runs, 1 loop each) ``` versus on this branch ``` python In [5]: %timeit [df[col].astype('unicode') for col in df.columns] 5.38 ms ± 47 µs per loop (mean ± std. dev. of 7 runs, 100 loops each) ```
https://api.github.com/repos/pandas-dev/pandas/pulls/37355
2020-10-23T04:14:28Z
2020-11-18T18:21:51Z
2020-11-18T18:21:51Z
2020-11-18T20:36:45Z
TST/REF: collect tests by method, some misplaced
diff --git a/pandas/tests/arithmetic/test_categorical.py b/pandas/tests/arithmetic/test_categorical.py new file mode 100644 index 0000000000000..a978f763fbaaa --- /dev/null +++ b/pandas/tests/arithmetic/test_categorical.py @@ -0,0 +1,12 @@ +import numpy as np + +from pandas import Categorical, Series +import pandas._testing as tm + + +class TestCategoricalComparisons: + def test_categorical_nan_equality(self): + cat = Series(Categorical(["a", "b", "c", np.nan])) + expected = Series([True, True, True, False]) + result = cat == cat + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/frame/methods/test_asfreq.py b/pandas/tests/frame/methods/test_asfreq.py index 40b0ec0c0d811..cdcd922949bcf 100644 --- a/pandas/tests/frame/methods/test_asfreq.py +++ b/pandas/tests/frame/methods/test_asfreq.py @@ -2,13 +2,31 @@ import numpy as np -from pandas import DataFrame, DatetimeIndex, Series, date_range +from pandas import DataFrame, DatetimeIndex, Series, date_range, to_datetime import pandas._testing as tm from pandas.tseries import offsets class TestAsFreq: + def test_asfreq_resample_set_correct_freq(self): + # GH#5613 + # we test if .asfreq() and .resample() set the correct value for .freq + df = DataFrame( + {"date": ["2012-01-01", "2012-01-02", "2012-01-03"], "col": [1, 2, 3]} + ) + df = df.set_index(to_datetime(df.date)) + + # testing the settings before calling .asfreq() and .resample() + assert df.index.freq is None + assert df.index.inferred_freq == "D" + + # does .asfreq() set .freq correctly? + assert df.asfreq("D").index.freq == "D" + + # does .resample() set .freq correctly? + assert df.resample("D").asfreq().index.freq == "D" + def test_asfreq(self, datetime_frame): offset_monthly = datetime_frame.asfreq(offsets.BMonthEnd()) rule_monthly = datetime_frame.asfreq("BM") diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index cb12365f38605..e0506df5cd939 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -618,6 +618,16 @@ def test_get_indexer_out_of_bounds_date(self, target, positions): expected = np.array(positions, dtype=np.intp) tm.assert_numpy_array_equal(result, expected) + def test_get_indexer_pad_requires_monotonicity(self): + rng = date_range("1/1/2000", "3/1/2000", freq="B") + + # neither monotonic increasing or decreasing + rng2 = rng[[1, 0, 2]] + + msg = "index must be monotonic increasing or decreasing" + with pytest.raises(ValueError, match=msg): + rng2.get_indexer(rng, method="pad") + class TestMaybeCastSliceBound: def test_maybe_cast_slice_bounds_empty(self): diff --git a/pandas/tests/series/methods/test_convert.py b/pandas/tests/series/methods/test_convert.py new file mode 100644 index 0000000000000..b213e4a6c4c8a --- /dev/null +++ b/pandas/tests/series/methods/test_convert.py @@ -0,0 +1,203 @@ +from datetime import datetime + +import numpy as np +import pytest + +from pandas import NaT, Series, Timestamp +import pandas._testing as tm + + +class TestConvert: + def test_convert(self): + # GH#10265 + # Tests: All to nans, coerce, true + # Test coercion returns correct type + ser = Series(["a", "b", "c"]) + results = ser._convert(datetime=True, coerce=True) + expected = Series([NaT] * 3) + tm.assert_series_equal(results, expected) + + results = ser._convert(numeric=True, coerce=True) + expected = Series([np.nan] * 3) + tm.assert_series_equal(results, expected) + + expected = Series([NaT] * 3, dtype=np.dtype("m8[ns]")) + results = ser._convert(timedelta=True, coerce=True) + tm.assert_series_equal(results, expected) + + dt = datetime(2001, 1, 1, 0, 0) + td = dt - datetime(2000, 1, 1, 0, 0) + + # Test coercion with mixed types + ser = Series(["a", "3.1415", dt, td]) + results = ser._convert(datetime=True, coerce=True) + expected = Series([NaT, NaT, dt, NaT]) + tm.assert_series_equal(results, expected) + + results = ser._convert(numeric=True, coerce=True) + expected = Series([np.nan, 3.1415, np.nan, np.nan]) + tm.assert_series_equal(results, expected) + + results = ser._convert(timedelta=True, coerce=True) + expected = Series([NaT, NaT, NaT, td], dtype=np.dtype("m8[ns]")) + tm.assert_series_equal(results, expected) + + # Test standard conversion returns original + results = ser._convert(datetime=True) + tm.assert_series_equal(results, ser) + results = ser._convert(numeric=True) + expected = Series([np.nan, 3.1415, np.nan, np.nan]) + tm.assert_series_equal(results, expected) + results = ser._convert(timedelta=True) + tm.assert_series_equal(results, ser) + + # test pass-through and non-conversion when other types selected + ser = Series(["1.0", "2.0", "3.0"]) + results = ser._convert(datetime=True, numeric=True, timedelta=True) + expected = Series([1.0, 2.0, 3.0]) + tm.assert_series_equal(results, expected) + results = ser._convert(True, False, True) + tm.assert_series_equal(results, ser) + + ser = Series( + [datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 1, 0, 0)], dtype="O" + ) + results = ser._convert(datetime=True, numeric=True, timedelta=True) + expected = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 1, 0, 0)]) + tm.assert_series_equal(results, expected) + results = ser._convert(datetime=False, numeric=True, timedelta=True) + tm.assert_series_equal(results, ser) + + td = datetime(2001, 1, 1, 0, 0) - datetime(2000, 1, 1, 0, 0) + ser = Series([td, td], dtype="O") + results = ser._convert(datetime=True, numeric=True, timedelta=True) + expected = Series([td, td]) + tm.assert_series_equal(results, expected) + results = ser._convert(True, True, False) + tm.assert_series_equal(results, ser) + + ser = Series([1.0, 2, 3], index=["a", "b", "c"]) + result = ser._convert(numeric=True) + tm.assert_series_equal(result, ser) + + # force numeric conversion + res = ser.copy().astype("O") + res["a"] = "1" + result = res._convert(numeric=True) + tm.assert_series_equal(result, ser) + + res = ser.copy().astype("O") + res["a"] = "1." + result = res._convert(numeric=True) + tm.assert_series_equal(result, ser) + + res = ser.copy().astype("O") + res["a"] = "garbled" + result = res._convert(numeric=True) + expected = ser.copy() + expected["a"] = np.nan + tm.assert_series_equal(result, expected) + + # GH 4119, not converting a mixed type (e.g.floats and object) + ser = Series([1, "na", 3, 4]) + result = ser._convert(datetime=True, numeric=True) + expected = Series([1, np.nan, 3, 4]) + tm.assert_series_equal(result, expected) + + ser = Series([1, "", 3, 4]) + result = ser._convert(datetime=True, numeric=True) + tm.assert_series_equal(result, expected) + + # dates + ser = Series( + [ + datetime(2001, 1, 1, 0, 0), + datetime(2001, 1, 2, 0, 0), + datetime(2001, 1, 3, 0, 0), + ] + ) + s2 = Series( + [ + datetime(2001, 1, 1, 0, 0), + datetime(2001, 1, 2, 0, 0), + datetime(2001, 1, 3, 0, 0), + "foo", + 1.0, + 1, + Timestamp("20010104"), + "20010105", + ], + dtype="O", + ) + + result = ser._convert(datetime=True) + expected = Series( + [Timestamp("20010101"), Timestamp("20010102"), Timestamp("20010103")], + dtype="M8[ns]", + ) + tm.assert_series_equal(result, expected) + + result = ser._convert(datetime=True, coerce=True) + tm.assert_series_equal(result, expected) + + expected = Series( + [ + Timestamp("20010101"), + Timestamp("20010102"), + Timestamp("20010103"), + NaT, + NaT, + NaT, + Timestamp("20010104"), + Timestamp("20010105"), + ], + dtype="M8[ns]", + ) + result = s2._convert(datetime=True, numeric=False, timedelta=False, coerce=True) + tm.assert_series_equal(result, expected) + result = s2._convert(datetime=True, coerce=True) + tm.assert_series_equal(result, expected) + + ser = Series(["foo", "bar", 1, 1.0], dtype="O") + result = ser._convert(datetime=True, coerce=True) + expected = Series([NaT] * 2 + [Timestamp(1)] * 2) + tm.assert_series_equal(result, expected) + + # preserver if non-object + ser = Series([1], dtype="float32") + result = ser._convert(datetime=True, coerce=True) + tm.assert_series_equal(result, ser) + + # FIXME: dont leave commented-out + # res = ser.copy() + # r[0] = np.nan + # result = res._convert(convert_dates=True,convert_numeric=False) + # assert result.dtype == 'M8[ns]' + + # dateutil parses some single letters into today's value as a date + expected = Series([NaT]) + for x in "abcdefghijklmnopqrstuvwxyz": + ser = Series([x]) + result = ser._convert(datetime=True, coerce=True) + tm.assert_series_equal(result, expected) + ser = Series([x.upper()]) + result = ser._convert(datetime=True, coerce=True) + tm.assert_series_equal(result, expected) + + def test_convert_no_arg_error(self): + ser = Series(["1.0", "2"]) + msg = r"At least one of datetime, numeric or timedelta must be True\." + with pytest.raises(ValueError, match=msg): + ser._convert() + + def test_convert_preserve_bool(self): + ser = Series([1, True, 3, 5], dtype=object) + res = ser._convert(datetime=True, numeric=True) + expected = Series([1, 1, 3, 5], dtype="i8") + tm.assert_series_equal(res, expected) + + def test_convert_preserve_all_bool(self): + ser = Series([False, True, False, False], dtype=object) + res = ser._convert(datetime=True, numeric=True) + expected = Series([False, True, False, False], dtype=bool) + tm.assert_series_equal(res, expected) diff --git a/pandas/tests/series/methods/test_dropna.py b/pandas/tests/series/methods/test_dropna.py new file mode 100644 index 0000000000000..f56230daea190 --- /dev/null +++ b/pandas/tests/series/methods/test_dropna.py @@ -0,0 +1,96 @@ +import numpy as np +import pytest + +from pandas import DatetimeIndex, IntervalIndex, NaT, Period, Series, Timestamp +import pandas._testing as tm + + +class TestDropna: + def test_dropna_empty(self): + ser = Series([], dtype=object) + + assert len(ser.dropna()) == 0 + return_value = ser.dropna(inplace=True) + assert return_value is None + assert len(ser) == 0 + + # invalid axis + msg = "No axis named 1 for object type Series" + with pytest.raises(ValueError, match=msg): + ser.dropna(axis=1) + + def test_dropna_preserve_name(self, datetime_series): + datetime_series[:5] = np.nan + result = datetime_series.dropna() + assert result.name == datetime_series.name + name = datetime_series.name + ts = datetime_series.copy() + return_value = ts.dropna(inplace=True) + assert return_value is None + assert ts.name == name + + def test_dropna_no_nan(self): + for ser in [ + Series([1, 2, 3], name="x"), + Series([False, True, False], name="x"), + ]: + + result = ser.dropna() + tm.assert_series_equal(result, ser) + assert result is not ser + + s2 = ser.copy() + return_value = s2.dropna(inplace=True) + assert return_value is None + tm.assert_series_equal(s2, ser) + + def test_dropna_intervals(self): + ser = Series( + [np.nan, 1, 2, 3], + IntervalIndex.from_arrays([np.nan, 0, 1, 2], [np.nan, 1, 2, 3]), + ) + + result = ser.dropna() + expected = ser.iloc[1:] + tm.assert_series_equal(result, expected) + + def test_dropna_period_dtype(self): + # GH#13737 + ser = Series([Period("2011-01", freq="M"), Period("NaT", freq="M")]) + result = ser.dropna() + expected = Series([Period("2011-01", freq="M")]) + + tm.assert_series_equal(result, expected) + + def test_datetime64_tz_dropna(self): + # DatetimeBlock + ser = Series( + [ + Timestamp("2011-01-01 10:00"), + NaT, + Timestamp("2011-01-03 10:00"), + NaT, + ] + ) + result = ser.dropna() + expected = Series( + [Timestamp("2011-01-01 10:00"), Timestamp("2011-01-03 10:00")], index=[0, 2] + ) + tm.assert_series_equal(result, expected) + + # DatetimeBlockTZ + idx = DatetimeIndex( + ["2011-01-01 10:00", NaT, "2011-01-03 10:00", NaT], tz="Asia/Tokyo" + ) + ser = Series(idx) + assert ser.dtype == "datetime64[ns, Asia/Tokyo]" + result = ser.dropna() + expected = Series( + [ + Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), + Timestamp("2011-01-03 10:00", tz="Asia/Tokyo"), + ], + index=[0, 2], + ) + assert result.dtype == "datetime64[ns, Asia/Tokyo]" + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py index 02214d66347e1..d45486b9bdb29 100644 --- a/pandas/tests/series/methods/test_fillna.py +++ b/pandas/tests/series/methods/test_fillna.py @@ -19,6 +19,43 @@ class TestSeriesFillNA: + def test_fillna_nat(self): + series = Series([0, 1, 2, NaT.value], dtype="M8[ns]") + + filled = series.fillna(method="pad") + filled2 = series.fillna(value=series.values[2]) + + expected = series.copy() + expected.values[3] = expected.values[2] + + tm.assert_series_equal(filled, expected) + tm.assert_series_equal(filled2, expected) + + df = DataFrame({"A": series}) + filled = df.fillna(method="pad") + filled2 = df.fillna(value=series.values[2]) + expected = DataFrame({"A": expected}) + tm.assert_frame_equal(filled, expected) + tm.assert_frame_equal(filled2, expected) + + series = Series([NaT.value, 0, 1, 2], dtype="M8[ns]") + + filled = series.fillna(method="bfill") + filled2 = series.fillna(value=series[1]) + + expected = series.copy() + expected[0] = expected[1] + + tm.assert_series_equal(filled, expected) + tm.assert_series_equal(filled2, expected) + + df = DataFrame({"A": series}) + filled = df.fillna(method="bfill") + filled2 = df.fillna(value=series[1]) + expected = DataFrame({"A": expected}) + tm.assert_frame_equal(filled, expected) + tm.assert_frame_equal(filled2, expected) + def test_fillna(self, datetime_series): ts = Series([0.0, 1.0, 2.0, 3.0, 4.0], index=tm.makeDateIndex(5)) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index efa2ab0f22442..1958e44b6d1a3 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -19,6 +19,7 @@ from pandas import ( Categorical, DataFrame, + DatetimeIndex, Index, Interval, IntervalIndex, @@ -1507,3 +1508,22 @@ def test_construction_from_large_int_scalar_no_overflow(self): result = Series(n, index=[0]) expected = Series(n) tm.assert_series_equal(result, expected) + + def test_constructor_list_of_periods_infers_period_dtype(self): + series = Series(list(period_range("2000-01-01", periods=10, freq="D"))) + assert series.dtype == "Period[D]" + + series = Series( + [pd.Period("2011-01-01", freq="D"), pd.Period("2011-02-01", freq="D")] + ) + assert series.dtype == "Period[D]" + + +class TestSeriesConstructorIndexCoercion: + def test_series_constructor_datetimelike_index_coercion(self): + idx = tm.makeDateIndex(10000) + with tm.assert_produces_warning(FutureWarning): + ser = Series(np.random.randn(len(idx)), idx.astype(object)) + with tm.assert_produces_warning(FutureWarning): + assert ser.index.is_all_dates + assert isinstance(ser.index, DatetimeIndex) diff --git a/pandas/tests/series/test_dt_accessor.py b/pandas/tests/series/test_dt_accessor.py index 0e31ffcb30b93..2f30c0621cc06 100644 --- a/pandas/tests/series/test_dt_accessor.py +++ b/pandas/tests/series/test_dt_accessor.py @@ -16,6 +16,7 @@ DataFrame, DatetimeIndex, Index, + Period, PeriodIndex, Series, TimedeltaIndex, @@ -675,6 +676,45 @@ def test_isocalendar(self, input_series, expected_output): tm.assert_frame_equal(result, expected_frame) +class TestSeriesPeriodValuesDtAccessor: + @pytest.mark.parametrize( + "input_vals", + [ + [Period("2016-01", freq="M"), Period("2016-02", freq="M")], + [Period("2016-01-01", freq="D"), Period("2016-01-02", freq="D")], + [ + Period("2016-01-01 00:00:00", freq="H"), + Period("2016-01-01 01:00:00", freq="H"), + ], + [ + Period("2016-01-01 00:00:00", freq="M"), + Period("2016-01-01 00:01:00", freq="M"), + ], + [ + Period("2016-01-01 00:00:00", freq="S"), + Period("2016-01-01 00:00:01", freq="S"), + ], + ], + ) + def test_end_time_timevalues(self, input_vals): + # GH#17157 + # Check that the time part of the Period is adjusted by end_time + # when using the dt accessor on a Series + input_vals = PeriodArray._from_sequence(np.asarray(input_vals)) + + s = Series(input_vals) + result = s.dt.end_time + expected = s.apply(lambda x: x.end_time) + tm.assert_series_equal(result, expected) + + @pytest.mark.parametrize("input_vals", [("2001"), ("NaT")]) + def test_to_period(self, input_vals): + # GH#21205 + expected = Series([input_vals], dtype="Period[D]") + result = Series([input_vals], dtype="datetime64[ns]").dt.to_period("D") + tm.assert_series_equal(result, expected) + + def test_week_and_weekofyear_are_deprecated(): # GH#33595 Deprecate week and weekofyear series = pd.to_datetime(Series(["2020-01-01"])) diff --git a/pandas/tests/series/test_internals.py b/pandas/tests/series/test_internals.py index 488bd120ac405..be106e8b1fef4 100644 --- a/pandas/tests/series/test_internals.py +++ b/pandas/tests/series/test_internals.py @@ -1,208 +1,12 @@ -from datetime import datetime - import numpy as np -import pytest import pandas as pd -from pandas import NaT, Series, Timestamp +from pandas import Series import pandas._testing as tm from pandas.core.internals.blocks import IntBlock class TestSeriesInternals: - - # GH 10265 - def test_convert(self): - # Tests: All to nans, coerce, true - # Test coercion returns correct type - s = Series(["a", "b", "c"]) - results = s._convert(datetime=True, coerce=True) - expected = Series([NaT] * 3) - tm.assert_series_equal(results, expected) - - results = s._convert(numeric=True, coerce=True) - expected = Series([np.nan] * 3) - tm.assert_series_equal(results, expected) - - expected = Series([NaT] * 3, dtype=np.dtype("m8[ns]")) - results = s._convert(timedelta=True, coerce=True) - tm.assert_series_equal(results, expected) - - dt = datetime(2001, 1, 1, 0, 0) - td = dt - datetime(2000, 1, 1, 0, 0) - - # Test coercion with mixed types - s = Series(["a", "3.1415", dt, td]) - results = s._convert(datetime=True, coerce=True) - expected = Series([NaT, NaT, dt, NaT]) - tm.assert_series_equal(results, expected) - - results = s._convert(numeric=True, coerce=True) - expected = Series([np.nan, 3.1415, np.nan, np.nan]) - tm.assert_series_equal(results, expected) - - results = s._convert(timedelta=True, coerce=True) - expected = Series([NaT, NaT, NaT, td], dtype=np.dtype("m8[ns]")) - tm.assert_series_equal(results, expected) - - # Test standard conversion returns original - results = s._convert(datetime=True) - tm.assert_series_equal(results, s) - results = s._convert(numeric=True) - expected = Series([np.nan, 3.1415, np.nan, np.nan]) - tm.assert_series_equal(results, expected) - results = s._convert(timedelta=True) - tm.assert_series_equal(results, s) - - # test pass-through and non-conversion when other types selected - s = Series(["1.0", "2.0", "3.0"]) - results = s._convert(datetime=True, numeric=True, timedelta=True) - expected = Series([1.0, 2.0, 3.0]) - tm.assert_series_equal(results, expected) - results = s._convert(True, False, True) - tm.assert_series_equal(results, s) - - s = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 1, 0, 0)], dtype="O") - results = s._convert(datetime=True, numeric=True, timedelta=True) - expected = Series([datetime(2001, 1, 1, 0, 0), datetime(2001, 1, 1, 0, 0)]) - tm.assert_series_equal(results, expected) - results = s._convert(datetime=False, numeric=True, timedelta=True) - tm.assert_series_equal(results, s) - - td = datetime(2001, 1, 1, 0, 0) - datetime(2000, 1, 1, 0, 0) - s = Series([td, td], dtype="O") - results = s._convert(datetime=True, numeric=True, timedelta=True) - expected = Series([td, td]) - tm.assert_series_equal(results, expected) - results = s._convert(True, True, False) - tm.assert_series_equal(results, s) - - s = Series([1.0, 2, 3], index=["a", "b", "c"]) - result = s._convert(numeric=True) - tm.assert_series_equal(result, s) - - # force numeric conversion - r = s.copy().astype("O") - r["a"] = "1" - result = r._convert(numeric=True) - tm.assert_series_equal(result, s) - - r = s.copy().astype("O") - r["a"] = "1." - result = r._convert(numeric=True) - tm.assert_series_equal(result, s) - - r = s.copy().astype("O") - r["a"] = "garbled" - result = r._convert(numeric=True) - expected = s.copy() - expected["a"] = np.nan - tm.assert_series_equal(result, expected) - - # GH 4119, not converting a mixed type (e.g.floats and object) - s = Series([1, "na", 3, 4]) - result = s._convert(datetime=True, numeric=True) - expected = Series([1, np.nan, 3, 4]) - tm.assert_series_equal(result, expected) - - s = Series([1, "", 3, 4]) - result = s._convert(datetime=True, numeric=True) - tm.assert_series_equal(result, expected) - - # dates - s = Series( - [ - datetime(2001, 1, 1, 0, 0), - datetime(2001, 1, 2, 0, 0), - datetime(2001, 1, 3, 0, 0), - ] - ) - s2 = Series( - [ - datetime(2001, 1, 1, 0, 0), - datetime(2001, 1, 2, 0, 0), - datetime(2001, 1, 3, 0, 0), - "foo", - 1.0, - 1, - Timestamp("20010104"), - "20010105", - ], - dtype="O", - ) - - result = s._convert(datetime=True) - expected = Series( - [Timestamp("20010101"), Timestamp("20010102"), Timestamp("20010103")], - dtype="M8[ns]", - ) - tm.assert_series_equal(result, expected) - - result = s._convert(datetime=True, coerce=True) - tm.assert_series_equal(result, expected) - - expected = Series( - [ - Timestamp("20010101"), - Timestamp("20010102"), - Timestamp("20010103"), - NaT, - NaT, - NaT, - Timestamp("20010104"), - Timestamp("20010105"), - ], - dtype="M8[ns]", - ) - result = s2._convert(datetime=True, numeric=False, timedelta=False, coerce=True) - tm.assert_series_equal(result, expected) - result = s2._convert(datetime=True, coerce=True) - tm.assert_series_equal(result, expected) - - s = Series(["foo", "bar", 1, 1.0], dtype="O") - result = s._convert(datetime=True, coerce=True) - expected = Series([NaT] * 2 + [Timestamp(1)] * 2) - tm.assert_series_equal(result, expected) - - # preserver if non-object - s = Series([1], dtype="float32") - result = s._convert(datetime=True, coerce=True) - tm.assert_series_equal(result, s) - - # FIXME: dont leave commented-out - # r = s.copy() - # r[0] = np.nan - # result = r._convert(convert_dates=True,convert_numeric=False) - # assert result.dtype == 'M8[ns]' - - # dateutil parses some single letters into today's value as a date - expected = Series([NaT]) - for x in "abcdefghijklmnopqrstuvwxyz": - s = Series([x]) - result = s._convert(datetime=True, coerce=True) - tm.assert_series_equal(result, expected) - s = Series([x.upper()]) - result = s._convert(datetime=True, coerce=True) - tm.assert_series_equal(result, expected) - - def test_convert_no_arg_error(self): - s = Series(["1.0", "2"]) - msg = r"At least one of datetime, numeric or timedelta must be True\." - with pytest.raises(ValueError, match=msg): - s._convert() - - def test_convert_preserve_bool(self): - s = Series([1, True, 3, 5], dtype=object) - r = s._convert(datetime=True, numeric=True) - e = Series([1, 1, 3, 5], dtype="i8") - tm.assert_series_equal(r, e) - - def test_convert_preserve_all_bool(self): - s = Series([False, True, False, False], dtype=object) - r = s._convert(datetime=True, numeric=True) - e = Series([False, True, False, False], dtype=bool) - tm.assert_series_equal(r, e) - def test_constructor_no_pandas_array(self): ser = Series([1, 2, 3]) result = Series(ser.array) diff --git a/pandas/tests/series/test_missing.py b/pandas/tests/series/test_missing.py index 6d8d0703acdb5..f601d7cb655b3 100644 --- a/pandas/tests/series/test_missing.py +++ b/pandas/tests/series/test_missing.py @@ -1,32 +1,15 @@ from datetime import timedelta import numpy as np -import pytest from pandas._libs import iNaT import pandas as pd -from pandas import ( - Categorical, - DataFrame, - Index, - IntervalIndex, - NaT, - Series, - Timestamp, - date_range, - isna, -) +from pandas import Categorical, Index, NaT, Series, isna import pandas._testing as tm class TestSeriesMissingData: - def test_categorical_nan_equality(self): - cat = Series(Categorical(["a", "b", "c", np.nan])) - exp = Series([True, True, True, False]) - res = cat == cat - tm.assert_series_equal(res, exp) - def test_categorical_nan_handling(self): # NaNs are represented as -1 in labels @@ -36,43 +19,6 @@ def test_categorical_nan_handling(self): s.values.codes, np.array([0, 1, -1, 0], dtype=np.int8) ) - def test_fillna_nat(self): - series = Series([0, 1, 2, iNaT], dtype="M8[ns]") - - filled = series.fillna(method="pad") - filled2 = series.fillna(value=series.values[2]) - - expected = series.copy() - expected.values[3] = expected.values[2] - - tm.assert_series_equal(filled, expected) - tm.assert_series_equal(filled2, expected) - - df = DataFrame({"A": series}) - filled = df.fillna(method="pad") - filled2 = df.fillna(value=series.values[2]) - expected = DataFrame({"A": expected}) - tm.assert_frame_equal(filled, expected) - tm.assert_frame_equal(filled2, expected) - - series = Series([iNaT, 0, 1, 2], dtype="M8[ns]") - - filled = series.fillna(method="bfill") - filled2 = series.fillna(value=series[1]) - - expected = series.copy() - expected[0] = expected[1] - - tm.assert_series_equal(filled, expected) - tm.assert_series_equal(filled2, expected) - - df = DataFrame({"A": series}) - filled = df.fillna(method="bfill") - filled2 = df.fillna(value=series[1]) - expected = DataFrame({"A": expected}) - tm.assert_frame_equal(filled, expected) - tm.assert_frame_equal(filled2, expected) - def test_isna_for_inf(self): s = Series(["a", np.inf, np.nan, pd.NA, 1.0]) with pd.option_context("mode.use_inf_as_na", True): @@ -136,74 +82,6 @@ def test_timedelta64_nan(self): # expected = (datetime_series >= -0.5) & (datetime_series <= 0.5) # tm.assert_series_equal(selector, expected) - def test_dropna_empty(self): - s = Series([], dtype=object) - - assert len(s.dropna()) == 0 - return_value = s.dropna(inplace=True) - assert return_value is None - assert len(s) == 0 - - # invalid axis - msg = "No axis named 1 for object type Series" - with pytest.raises(ValueError, match=msg): - s.dropna(axis=1) - - def test_datetime64_tz_dropna(self): - # DatetimeBlock - s = Series( - [ - Timestamp("2011-01-01 10:00"), - pd.NaT, - Timestamp("2011-01-03 10:00"), - pd.NaT, - ] - ) - result = s.dropna() - expected = Series( - [Timestamp("2011-01-01 10:00"), Timestamp("2011-01-03 10:00")], index=[0, 2] - ) - tm.assert_series_equal(result, expected) - - # DatetimeBlockTZ - idx = pd.DatetimeIndex( - ["2011-01-01 10:00", pd.NaT, "2011-01-03 10:00", pd.NaT], tz="Asia/Tokyo" - ) - s = Series(idx) - assert s.dtype == "datetime64[ns, Asia/Tokyo]" - result = s.dropna() - expected = Series( - [ - Timestamp("2011-01-01 10:00", tz="Asia/Tokyo"), - Timestamp("2011-01-03 10:00", tz="Asia/Tokyo"), - ], - index=[0, 2], - ) - assert result.dtype == "datetime64[ns, Asia/Tokyo]" - tm.assert_series_equal(result, expected) - - def test_dropna_no_nan(self): - for s in [Series([1, 2, 3], name="x"), Series([False, True, False], name="x")]: - - result = s.dropna() - tm.assert_series_equal(result, s) - assert result is not s - - s2 = s.copy() - return_value = s2.dropna(inplace=True) - assert return_value is None - tm.assert_series_equal(s2, s) - - def test_dropna_intervals(self): - s = Series( - [np.nan, 1, 2, 3], - IntervalIndex.from_arrays([np.nan, 0, 1, 2], [np.nan, 1, 2, 3]), - ) - - result = s.dropna() - expected = s.iloc[1:] - tm.assert_series_equal(result, expected) - def test_valid(self, datetime_series): ts = datetime_series.copy() ts.index = ts.index._with_freq(None) @@ -231,23 +109,3 @@ def test_notna(self): ser = Series(["hi", "", np.nan]) expected = Series([True, True, False]) tm.assert_series_equal(ser.notna(), expected) - - def test_pad_require_monotonicity(self): - rng = date_range("1/1/2000", "3/1/2000", freq="B") - - # neither monotonic increasing or decreasing - rng2 = rng[[1, 0, 2]] - - msg = "index must be monotonic increasing or decreasing" - with pytest.raises(ValueError, match=msg): - rng2.get_indexer(rng, method="pad") - - def test_dropna_preserve_name(self, datetime_series): - datetime_series[:5] = np.nan - result = datetime_series.dropna() - assert result.name == datetime_series.name - name = datetime_series.name - ts = datetime_series.copy() - return_value = ts.dropna(inplace=True) - assert return_value is None - assert ts.name == name diff --git a/pandas/tests/series/test_period.py b/pandas/tests/series/test_period.py index 2c32342f8802a..c73c57c3d2d91 100644 --- a/pandas/tests/series/test_period.py +++ b/pandas/tests/series/test_period.py @@ -2,35 +2,20 @@ import pytest import pandas as pd -from pandas import DataFrame, Period, Series, period_range +from pandas import DataFrame, Series, period_range import pandas._testing as tm -from pandas.core.arrays import PeriodArray class TestSeriesPeriod: def setup_method(self, method): self.series = Series(period_range("2000-01-01", periods=10, freq="D")) - def test_auto_conversion(self): - series = Series(list(period_range("2000-01-01", periods=10, freq="D"))) - assert series.dtype == "Period[D]" - - series = Series( - [pd.Period("2011-01-01", freq="D"), pd.Period("2011-02-01", freq="D")] - ) - assert series.dtype == "Period[D]" - def test_isna(self): # GH 13737 s = Series([pd.Period("2011-01", freq="M"), pd.Period("NaT", freq="M")]) tm.assert_series_equal(s.isna(), Series([False, True])) tm.assert_series_equal(s.notna(), Series([True, False])) - def test_dropna(self): - # GH 13737 - s = Series([pd.Period("2011-01", freq="M"), pd.Period("NaT", freq="M")]) - tm.assert_series_equal(s.dropna(), Series([pd.Period("2011-01", freq="M")])) - # --------------------------------------------------------------------- # NaT support @@ -61,40 +46,3 @@ def test_intercept_astype_object(self): result = df.values.squeeze() assert (result[:, 0] == expected.values).all() - - @pytest.mark.parametrize( - "input_vals", - [ - [Period("2016-01", freq="M"), Period("2016-02", freq="M")], - [Period("2016-01-01", freq="D"), Period("2016-01-02", freq="D")], - [ - Period("2016-01-01 00:00:00", freq="H"), - Period("2016-01-01 01:00:00", freq="H"), - ], - [ - Period("2016-01-01 00:00:00", freq="M"), - Period("2016-01-01 00:01:00", freq="M"), - ], - [ - Period("2016-01-01 00:00:00", freq="S"), - Period("2016-01-01 00:00:01", freq="S"), - ], - ], - ) - def test_end_time_timevalues(self, input_vals): - # GH 17157 - # Check that the time part of the Period is adjusted by end_time - # when using the dt accessor on a Series - input_vals = PeriodArray._from_sequence(np.asarray(input_vals)) - - s = Series(input_vals) - result = s.dt.end_time - expected = s.apply(lambda x: x.end_time) - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize("input_vals", [("2001"), ("NaT")]) - def test_to_period(self, input_vals): - # GH 21205 - expected = Series([input_vals], dtype="Period[D]") - result = Series([input_vals], dtype="datetime64[ns]").dt.to_period("D") - tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index 31c0e7f54d12b..ba270448c19ed 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -2,19 +2,11 @@ import pytest import pandas as pd -from pandas import DataFrame, DatetimeIndex, Series, date_range, timedelta_range +from pandas import DataFrame, Series, date_range, timedelta_range import pandas._testing as tm class TestTimeSeries: - def test_timeseries_coercion(self): - idx = tm.makeDateIndex(10000) - with tm.assert_produces_warning(FutureWarning): - ser = Series(np.random.randn(len(idx)), idx.astype(object)) - with tm.assert_produces_warning(FutureWarning): - assert ser.index.is_all_dates - assert isinstance(ser.index, DatetimeIndex) - def test_contiguous_boolean_preserve_freq(self): rng = date_range("1/1/2000", "3/1/2000", freq="B") @@ -79,24 +71,6 @@ def f(x): s.apply(f) DataFrame(s).applymap(f) - def test_asfreq_resample_set_correct_freq(self): - # GH5613 - # we test if .asfreq() and .resample() set the correct value for .freq - df = DataFrame( - {"date": ["2012-01-01", "2012-01-02", "2012-01-03"], "col": [1, 2, 3]} - ) - df = df.set_index(pd.to_datetime(df.date)) - - # testing the settings before calling .asfreq() and .resample() - assert df.index.freq is None - assert df.index.inferred_freq == "D" - - # does .asfreq() set .freq correctly? - assert df.asfreq("D").index.freq == "D" - - # does .resample() set .freq correctly? - assert df.resample("D").asfreq().index.freq == "D" - def test_view_tz(self): # GH#24024 ser = Series(pd.date_range("2000", periods=4, tz="US/Central"))
Looking to get rid of some more of the not-obviously-scoped test files
https://api.github.com/repos/pandas-dev/pandas/pulls/37354
2020-10-23T02:26:45Z
2020-10-23T17:18:33Z
2020-10-23T17:18:33Z
2020-10-23T18:06:47Z
TST: collect indexing tests by method
diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index d462917277f99..38f6b6d38008c 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -791,15 +791,15 @@ def _join_by_hand(a, b, how="left"): def test_join_inner_multiindex_deterministic_order(): # GH: 36910 - left = pd.DataFrame( + left = DataFrame( data={"e": 5}, index=pd.MultiIndex.from_tuples([(1, 2, 4)], names=("a", "b", "d")), ) - right = pd.DataFrame( + right = DataFrame( data={"f": 6}, index=pd.MultiIndex.from_tuples([(2, 3)], names=("b", "c")) ) result = left.join(right, how="inner") - expected = pd.DataFrame( + expected = DataFrame( {"e": [5], "f": [6]}, index=pd.MultiIndex.from_tuples([(2, 1, 4, 3)], names=("b", "a", "d", "c")), ) diff --git a/pandas/tests/series/indexing/test_boolean.py b/pandas/tests/series/indexing/test_boolean.py deleted file mode 100644 index 3f88f4193e770..0000000000000 --- a/pandas/tests/series/indexing/test_boolean.py +++ /dev/null @@ -1,146 +0,0 @@ -import numpy as np -import pytest - -from pandas import Index, Series, date_range -import pandas._testing as tm -from pandas.core.indexing import IndexingError - -from pandas.tseries.offsets import BDay - - -def test_getitem_boolean(string_series): - s = string_series - mask = s > s.median() - - # passing list is OK - result = s[list(mask)] - expected = s[mask] - tm.assert_series_equal(result, expected) - tm.assert_index_equal(result.index, s.index[mask]) - - -def test_getitem_boolean_empty(): - s = Series([], dtype=np.int64) - s.index.name = "index_name" - s = s[s.isna()] - assert s.index.name == "index_name" - assert s.dtype == np.int64 - - # GH5877 - # indexing with empty series - s = Series(["A", "B"]) - expected = Series(dtype=object, index=Index([], dtype="int64")) - result = s[Series([], dtype=object)] - tm.assert_series_equal(result, expected) - - # invalid because of the boolean indexer - # that's empty or not-aligned - msg = ( - r"Unalignable boolean Series provided as indexer \(index of " - r"the boolean Series and of the indexed object do not match" - ) - with pytest.raises(IndexingError, match=msg): - s[Series([], dtype=bool)] - - with pytest.raises(IndexingError, match=msg): - s[Series([True], dtype=bool)] - - -def test_getitem_boolean_object(string_series): - # using column from DataFrame - - s = string_series - mask = s > s.median() - omask = mask.astype(object) - - # getitem - result = s[omask] - expected = s[mask] - tm.assert_series_equal(result, expected) - - # setitem - s2 = s.copy() - cop = s.copy() - cop[omask] = 5 - s2[mask] = 5 - tm.assert_series_equal(cop, s2) - - # nans raise exception - omask[5:10] = np.nan - msg = "Cannot mask with non-boolean array containing NA / NaN values" - with pytest.raises(ValueError, match=msg): - s[omask] - with pytest.raises(ValueError, match=msg): - s[omask] = 5 - - -def test_getitem_setitem_boolean_corner(datetime_series): - ts = datetime_series - mask_shifted = ts.shift(1, freq=BDay()) > ts.median() - - # these used to raise...?? - - msg = ( - r"Unalignable boolean Series provided as indexer \(index of " - r"the boolean Series and of the indexed object do not match" - ) - with pytest.raises(IndexingError, match=msg): - ts[mask_shifted] - with pytest.raises(IndexingError, match=msg): - ts[mask_shifted] = 1 - - with pytest.raises(IndexingError, match=msg): - ts.loc[mask_shifted] - with pytest.raises(IndexingError, match=msg): - ts.loc[mask_shifted] = 1 - - -def test_setitem_boolean(string_series): - mask = string_series > string_series.median() - - # similar indexed series - result = string_series.copy() - result[mask] = string_series * 2 - expected = string_series * 2 - tm.assert_series_equal(result[mask], expected[mask]) - - # needs alignment - result = string_series.copy() - result[mask] = (string_series * 2)[0:5] - expected = (string_series * 2)[0:5].reindex_like(string_series) - expected[-mask] = string_series[mask] - tm.assert_series_equal(result[mask], expected[mask]) - - -def test_get_set_boolean_different_order(string_series): - ordered = string_series.sort_values() - - # setting - copy = string_series.copy() - copy[ordered > 0] = 0 - - expected = string_series.copy() - expected[expected > 0] = 0 - - tm.assert_series_equal(copy, expected) - - # getting - sel = string_series[ordered > 0] - exp = string_series[string_series > 0] - tm.assert_series_equal(sel, exp) - - -def test_getitem_boolean_dt64_copies(): - # GH#36210 - dti = date_range("2016-01-01", periods=4, tz="US/Pacific") - key = np.array([True, True, False, False]) - - ser = Series(dti._data) - - res = ser[key] - assert res._values._data.base is None - - # compare with numeric case for reference - ser2 = Series(range(4)) - res2 = ser2[key] - assert res2._values.base is None diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py index 06c14a95ab04e..b4c861312ad3d 100644 --- a/pandas/tests/series/indexing/test_getitem.py +++ b/pandas/tests/series/indexing/test_getitem.py @@ -9,8 +9,11 @@ from pandas._libs.tslibs import conversion, timezones import pandas as pd -from pandas import Series, Timestamp, date_range, period_range +from pandas import Index, Series, Timestamp, date_range, period_range import pandas._testing as tm +from pandas.core.indexing import IndexingError + +from pandas.tseries.offsets import BDay class TestSeriesGetitemScalars: @@ -124,6 +127,107 @@ def test_getitem_intlist_multiindex_numeric_level(self, dtype, box): ser[key] +class TestGetitemBooleanMask: + def test_getitem_boolean(self, string_series): + ser = string_series + mask = ser > ser.median() + + # passing list is OK + result = ser[list(mask)] + expected = ser[mask] + tm.assert_series_equal(result, expected) + tm.assert_index_equal(result.index, ser.index[mask]) + + def test_getitem_boolean_empty(self): + ser = Series([], dtype=np.int64) + ser.index.name = "index_name" + ser = ser[ser.isna()] + assert ser.index.name == "index_name" + assert ser.dtype == np.int64 + + # GH#5877 + # indexing with empty series + ser = Series(["A", "B"]) + expected = Series(dtype=object, index=Index([], dtype="int64")) + result = ser[Series([], dtype=object)] + tm.assert_series_equal(result, expected) + + # invalid because of the boolean indexer + # that's empty or not-aligned + msg = ( + r"Unalignable boolean Series provided as indexer \(index of " + r"the boolean Series and of the indexed object do not match" + ) + with pytest.raises(IndexingError, match=msg): + ser[Series([], dtype=bool)] + + with pytest.raises(IndexingError, match=msg): + ser[Series([True], dtype=bool)] + + def test_getitem_boolean_object(self, string_series): + # using column from DataFrame + + ser = string_series + mask = ser > ser.median() + omask = mask.astype(object) + + # getitem + result = ser[omask] + expected = ser[mask] + tm.assert_series_equal(result, expected) + + # setitem + s2 = ser.copy() + cop = ser.copy() + cop[omask] = 5 + s2[mask] = 5 + tm.assert_series_equal(cop, s2) + + # nans raise exception + omask[5:10] = np.nan + msg = "Cannot mask with non-boolean array containing NA / NaN values" + with pytest.raises(ValueError, match=msg): + ser[omask] + with pytest.raises(ValueError, match=msg): + ser[omask] = 5 + + def test_getitem_boolean_dt64_copies(self): + # GH#36210 + dti = date_range("2016-01-01", periods=4, tz="US/Pacific") + key = np.array([True, True, False, False]) + + ser = Series(dti._data) + + res = ser[key] + assert res._values._data.base is None + + # compare with numeric case for reference + ser2 = Series(range(4)) + res2 = ser2[key] + assert res2._values.base is None + + def test_getitem_boolean_corner(self, datetime_series): + ts = datetime_series + mask_shifted = ts.shift(1, freq=BDay()) > ts.median() + + msg = ( + r"Unalignable boolean Series provided as indexer \(index of " + r"the boolean Series and of the indexed object do not match" + ) + with pytest.raises(IndexingError, match=msg): + ts[mask_shifted] + + with pytest.raises(IndexingError, match=msg): + ts.loc[mask_shifted] + + def test_getitem_boolean_different_order(self, string_series): + ordered = string_series.sort_values() + + sel = string_series[ordered > 0] + exp = string_series[string_series > 0] + tm.assert_series_equal(sel, exp) + + def test_getitem_generator(string_series): gen = (x > 0 for x in string_series) result = string_series[gen] diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 6ac1397fa7695..c069b689c1710 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -4,8 +4,11 @@ import pytest from pandas import MultiIndex, NaT, Series, Timestamp, date_range, period_range +from pandas.core.indexing import IndexingError import pandas.testing as tm +from pandas.tseries.offsets import BDay + class TestSetitemDT64Values: def test_setitem_none_nan(self): @@ -61,3 +64,46 @@ def test_setitem_na_period_dtype_casts_to_nat(self, na_val): ser[3:5] = na_val assert ser[4] is NaT + + +class TestSetitemBooleanMask: + def test_setitem_boolean(self, string_series): + mask = string_series > string_series.median() + + # similar indexed series + result = string_series.copy() + result[mask] = string_series * 2 + expected = string_series * 2 + tm.assert_series_equal(result[mask], expected[mask]) + + # needs alignment + result = string_series.copy() + result[mask] = (string_series * 2)[0:5] + expected = (string_series * 2)[0:5].reindex_like(string_series) + expected[-mask] = string_series[mask] + tm.assert_series_equal(result[mask], expected[mask]) + + def test_setitem_boolean_corner(self, datetime_series): + ts = datetime_series + mask_shifted = ts.shift(1, freq=BDay()) > ts.median() + + msg = ( + r"Unalignable boolean Series provided as indexer \(index of " + r"the boolean Series and of the indexed object do not match" + ) + with pytest.raises(IndexingError, match=msg): + ts[mask_shifted] = 1 + + with pytest.raises(IndexingError, match=msg): + ts.loc[mask_shifted] = 1 + + def test_setitem_boolean_different_order(self, string_series): + ordered = string_series.sort_values() + + copy = string_series.copy() + copy[ordered > 0] = 0 + + expected = string_series.copy() + expected[expected > 0] = 0 + + tm.assert_series_equal(copy, expected)
https://api.github.com/repos/pandas-dev/pandas/pulls/37353
2020-10-23T01:50:05Z
2020-10-23T03:29:04Z
2020-10-23T03:29:04Z
2020-10-23T04:04:28Z
CI/CLN: Add more test file linting
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 926e90f3dfa0c..877e136492518 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -178,10 +178,10 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then RET=$(($RET + $?)) ; echo $MSG "DONE" MSG='Check for inconsistent use of pandas namespace in tests' ; echo $MSG - check_namespace "Series" - RET=$(($RET + $?)) - check_namespace "DataFrame" - RET=$(($RET + $?)) + for class in "Series" "DataFrame" "Index"; do + check_namespace ${class} + RET=$(($RET + $?)) + done echo $MSG "DONE" fi diff --git a/pandas/tests/arithmetic/test_numeric.py b/pandas/tests/arithmetic/test_numeric.py index 9716cffd626a8..1418aec015b92 100644 --- a/pandas/tests/arithmetic/test_numeric.py +++ b/pandas/tests/arithmetic/test_numeric.py @@ -42,7 +42,7 @@ def adjust_negative_zero(zero, expected): # TODO: remove this kludge once mypy stops giving false positives here # List comprehension has incompatible type List[PandasObject]; expected List[RangeIndex] # See GH#29725 -ser_or_index: List[Any] = [Series, pd.Index] +ser_or_index: List[Any] = [Series, Index] lefts: List[Any] = [pd.RangeIndex(10, 40, 10)] lefts.extend( [ @@ -100,7 +100,7 @@ def test_compare_invalid(self): def test_numeric_cmp_string_numexpr_path(self, box_with_array): # GH#36377, GH#35700 box = box_with_array - xbox = box if box is not pd.Index else np.ndarray + xbox = box if box is not Index else np.ndarray obj = Series(np.random.randn(10 ** 5)) obj = tm.box_expected(obj, box, transpose=False) @@ -126,7 +126,7 @@ def test_numeric_cmp_string_numexpr_path(self, box_with_array): class TestNumericArraylikeArithmeticWithDatetimeLike: # TODO: also check name retentention - @pytest.mark.parametrize("box_cls", [np.array, pd.Index, Series]) + @pytest.mark.parametrize("box_cls", [np.array, Index, Series]) @pytest.mark.parametrize( "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype) ) @@ -146,7 +146,7 @@ def test_mul_td64arr(self, left, box_cls): tm.assert_equal(result, expected) # TODO: also check name retentention - @pytest.mark.parametrize("box_cls", [np.array, pd.Index, Series]) + @pytest.mark.parametrize("box_cls", [np.array, Index, Series]) @pytest.mark.parametrize( "left", lefts, ids=lambda x: type(x).__name__ + str(x.dtype) ) @@ -318,7 +318,7 @@ class TestDivisionByZero: def test_div_zero(self, zero, numeric_idx): idx = numeric_idx - expected = pd.Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64) + expected = Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64) # We only adjust for Index, because Series does not yet apply # the adjustment correctly. expected2 = adjust_negative_zero(zero, expected) @@ -331,7 +331,7 @@ def test_div_zero(self, zero, numeric_idx): def test_floordiv_zero(self, zero, numeric_idx): idx = numeric_idx - expected = pd.Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64) + expected = Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64) # We only adjust for Index, because Series does not yet apply # the adjustment correctly. expected2 = adjust_negative_zero(zero, expected) @@ -344,7 +344,7 @@ def test_floordiv_zero(self, zero, numeric_idx): def test_mod_zero(self, zero, numeric_idx): idx = numeric_idx - expected = pd.Index([np.nan, np.nan, np.nan, np.nan, np.nan], dtype=np.float64) + expected = Index([np.nan, np.nan, np.nan, np.nan, np.nan], dtype=np.float64) result = idx % zero tm.assert_index_equal(result, expected) ser_compat = Series(idx).astype("i8") % np.array(zero).astype("i8") @@ -353,8 +353,8 @@ def test_mod_zero(self, zero, numeric_idx): def test_divmod_zero(self, zero, numeric_idx): idx = numeric_idx - exleft = pd.Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64) - exright = pd.Index([np.nan, np.nan, np.nan, np.nan, np.nan], dtype=np.float64) + exleft = Index([np.nan, np.inf, np.inf, np.inf, np.inf], dtype=np.float64) + exright = Index([np.nan, np.nan, np.nan, np.nan, np.nan], dtype=np.float64) exleft = adjust_negative_zero(zero, exleft) result = divmod(idx, zero) @@ -368,9 +368,7 @@ def test_div_negative_zero(self, zero, numeric_idx, op): return idx = numeric_idx - 3 - expected = pd.Index( - [-np.inf, -np.inf, -np.inf, np.nan, np.inf], dtype=np.float64 - ) + expected = Index([-np.inf, -np.inf, -np.inf, np.nan, np.inf], dtype=np.float64) expected = adjust_negative_zero(zero, expected) result = op(idx, zero) @@ -1045,7 +1043,7 @@ class TestUFuncCompat: [pd.Int64Index, pd.UInt64Index, pd.Float64Index, pd.RangeIndex, Series], ) def test_ufunc_compat(self, holder): - box = Series if holder is Series else pd.Index + box = Series if holder is Series else Index if holder is pd.RangeIndex: idx = pd.RangeIndex(0, 5) @@ -1060,7 +1058,7 @@ def test_ufunc_compat(self, holder): ) def test_ufunc_coercions(self, holder): idx = holder([1, 2, 3, 4, 5], name="x") - box = Series if holder is Series else pd.Index + box = Series if holder is Series else Index result = np.sqrt(idx) assert result.dtype == "f8" and isinstance(result, box) @@ -1104,7 +1102,7 @@ def test_ufunc_coercions(self, holder): ) def test_ufunc_multiple_return_values(self, holder): obj = holder([1, 2, 3], name="x") - box = Series if holder is Series else pd.Index + box = Series if holder is Series else Index result = np.modf(obj) assert isinstance(result, tuple) @@ -1299,14 +1297,14 @@ def test_numeric_compat2(self): def test_addsub_arithmetic(self, dtype, delta): # GH#8142 delta = dtype(delta) - index = pd.Index([10, 11, 12], dtype=dtype) + index = Index([10, 11, 12], dtype=dtype) result = index + delta - expected = pd.Index(index.values + delta, dtype=dtype) + expected = Index(index.values + delta, dtype=dtype) tm.assert_index_equal(result, expected) # this subtraction used to fail result = index - delta - expected = pd.Index(index.values - delta, dtype=dtype) + expected = Index(index.values - delta, dtype=dtype) tm.assert_index_equal(result, expected) tm.assert_index_equal(index + index, 2 * index) diff --git a/pandas/tests/arrays/categorical/test_constructors.py b/pandas/tests/arrays/categorical/test_constructors.py index 1eef86980f974..471e11cff9fd7 100644 --- a/pandas/tests/arrays/categorical/test_constructors.py +++ b/pandas/tests/arrays/categorical/test_constructors.py @@ -638,7 +638,7 @@ def test_constructor_imaginary(self): def test_constructor_string_and_tuples(self): # GH 21416 c = pd.Categorical(np.array(["c", ("a", "b"), ("b", "a"), "c"], dtype=object)) - expected_index = pd.Index([("a", "b"), ("b", "a"), "c"]) + expected_index = Index([("a", "b"), ("b", "a"), "c"]) assert c.categories.equals(expected_index) def test_interval(self): diff --git a/pandas/tests/base/test_misc.py b/pandas/tests/base/test_misc.py index 96aec2e27939a..f7952c81cfd61 100644 --- a/pandas/tests/base/test_misc.py +++ b/pandas/tests/base/test_misc.py @@ -200,6 +200,6 @@ def test_access_by_position(index): def test_get_indexer_non_unique_dtype_mismatch(): # GH 25459 - indexes, missing = pd.Index(["A", "B"]).get_indexer_non_unique(pd.Index([0])) + indexes, missing = Index(["A", "B"]).get_indexer_non_unique(Index([0])) tm.assert_numpy_array_equal(np.array([-1], dtype=np.intp), indexes) tm.assert_numpy_array_equal(np.array([0], dtype=np.intp), missing) diff --git a/pandas/tests/base/test_value_counts.py b/pandas/tests/base/test_value_counts.py index 602133bb4122e..def7e41e22fb1 100644 --- a/pandas/tests/base/test_value_counts.py +++ b/pandas/tests/base/test_value_counts.py @@ -33,7 +33,7 @@ def test_value_counts(index_or_series_obj): expected = Series(dict(counter.most_common()), dtype=np.int64, name=obj.name) expected.index = expected.index.astype(obj.dtype) if isinstance(obj, pd.MultiIndex): - expected.index = pd.Index(expected.index) + expected.index = Index(expected.index) # TODO: Order of entries with the same count is inconsistent on CI (gh-32449) if obj.duplicated().any(): diff --git a/pandas/tests/dtypes/test_inference.py b/pandas/tests/dtypes/test_inference.py index d9b229d61248d..afae6ab7b9c07 100644 --- a/pandas/tests/dtypes/test_inference.py +++ b/pandas/tests/dtypes/test_inference.py @@ -584,7 +584,7 @@ def test_maybe_convert_objects_nullable_integer(self, exp): def test_maybe_convert_objects_bool_nan(self): # GH32146 - ind = pd.Index([True, False, np.nan], dtype=object) + ind = Index([True, False, np.nan], dtype=object) exp = np.array([True, False, np.nan], dtype=object) out = lib.maybe_convert_objects(ind.values, safe=1) tm.assert_numpy_array_equal(out, exp) diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 752cea5cf757c..d7be4d071ad74 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -801,7 +801,7 @@ def test_setitem_empty_frame_with_boolean(self, dtype, kwargs): def test_setitem_with_empty_listlike(self): # GH #17101 - index = pd.Index([], name="idx") + index = Index([], name="idx") result = DataFrame(columns=["A"], index=index) result["A"] = [] expected = DataFrame(columns=["A"], index=index) @@ -1630,11 +1630,11 @@ def test_loc_getitem_index_namedtuple(self): @pytest.mark.parametrize("tpl", [tuple([1]), tuple([1, 2])]) def test_loc_getitem_index_single_double_tuples(self, tpl): # GH 20991 - idx = pd.Index([tuple([1]), tuple([1, 2])], name="A", tupleize_cols=False) + idx = Index([tuple([1]), tuple([1, 2])], name="A", tupleize_cols=False) df = DataFrame(index=idx) result = df.loc[[tpl]] - idx = pd.Index([tpl], name="A", tupleize_cols=False) + idx = Index([tpl], name="A", tupleize_cols=False) expected = DataFrame(index=idx) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/indexing/test_xs.py b/pandas/tests/frame/indexing/test_xs.py index 0fd2471a14fc9..20e8e252615d3 100644 --- a/pandas/tests/frame/indexing/test_xs.py +++ b/pandas/tests/frame/indexing/test_xs.py @@ -3,8 +3,7 @@ import numpy as np import pytest -import pandas as pd -from pandas import DataFrame, Series +from pandas import DataFrame, Index, Series import pandas._testing as tm from pandas.tseries.offsets import BDay @@ -59,7 +58,7 @@ def test_xs_corner(self): # no columns but Index(dtype=object) df = DataFrame(index=["a", "b", "c"]) result = df.xs("a") - expected = Series([], name="a", index=pd.Index([]), dtype=np.float64) + expected = Series([], name="a", index=Index([]), dtype=np.float64) tm.assert_series_equal(result, expected) def test_xs_duplicates(self): diff --git a/pandas/tests/frame/methods/test_align.py b/pandas/tests/frame/methods/test_align.py index 36a57fadff623..5dd4f7f8f8800 100644 --- a/pandas/tests/frame/methods/test_align.py +++ b/pandas/tests/frame/methods/test_align.py @@ -160,8 +160,8 @@ def test_align_mixed_int(self, mixed_int_frame): "l_ordered,r_ordered,expected", [ [True, True, pd.CategoricalIndex], - [True, False, pd.Index], - [False, True, pd.Index], + [True, False, Index], + [False, True, Index], [False, False, pd.CategoricalIndex], ], ) @@ -196,7 +196,7 @@ def test_align_multiindex(self): midx = pd.MultiIndex.from_product( [range(2), range(3), range(2)], names=("a", "b", "c") ) - idx = pd.Index(range(2), name="b") + idx = Index(range(2), name="b") df1 = DataFrame(np.arange(12, dtype="int64"), index=midx) df2 = DataFrame(np.arange(2, dtype="int64"), index=idx) diff --git a/pandas/tests/frame/methods/test_drop.py b/pandas/tests/frame/methods/test_drop.py index c45d774b3bb9e..09c10861e87c2 100644 --- a/pandas/tests/frame/methods/test_drop.py +++ b/pandas/tests/frame/methods/test_drop.py @@ -141,7 +141,7 @@ def test_drop(self): tm.assert_frame_equal(nu_df.drop("b", axis="columns"), nu_df["a"]) tm.assert_frame_equal(nu_df.drop([]), nu_df) # GH 16398 - nu_df = nu_df.set_index(pd.Index(["X", "Y", "X"])) + nu_df = nu_df.set_index(Index(["X", "Y", "X"])) nu_df.columns = list("abc") tm.assert_frame_equal(nu_df.drop("X", axis="rows"), nu_df.loc[["Y"], :]) tm.assert_frame_equal(nu_df.drop(["X", "Y"], axis=0), nu_df.loc[[], :]) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 25795c242528c..69f36f039e6db 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -1661,16 +1661,16 @@ def test_constructor_Series_differently_indexed(self): def test_constructor_index_names(self, name_in1, name_in2, name_in3, name_out): # GH13475 indices = [ - pd.Index(["a", "b", "c"], name=name_in1), - pd.Index(["b", "c", "d"], name=name_in2), - pd.Index(["c", "d", "e"], name=name_in3), + Index(["a", "b", "c"], name=name_in1), + Index(["b", "c", "d"], name=name_in2), + Index(["c", "d", "e"], name=name_in3), ] series = { c: Series([0, 1, 2], index=i) for i, c in zip(indices, ["x", "y", "z"]) } result = DataFrame(series) - exp_ind = pd.Index(["a", "b", "c", "d", "e"], name=name_out) + exp_ind = Index(["a", "b", "c", "d", "e"], name=name_out) expected = DataFrame( { "x": [0, 1, 2, np.nan, np.nan], diff --git a/pandas/tests/frame/test_stack_unstack.py b/pandas/tests/frame/test_stack_unstack.py index 3db061cd6a31c..c34f5b35c1ab7 100644 --- a/pandas/tests/frame/test_stack_unstack.py +++ b/pandas/tests/frame/test_stack_unstack.py @@ -280,7 +280,7 @@ def test_unstack_tuplename_in_multiindex(self): ], names=[None, ("A", "a")], ), - index=pd.Index([1, 2, 3], name=("B", "b")), + index=Index([1, 2, 3], name=("B", "b")), ) tm.assert_frame_equal(result, expected) @@ -301,7 +301,7 @@ def test_unstack_tuplename_in_multiindex(self): ( (("A", "a"), "B"), [[1, 1, 1, 1, 2, 2, 2, 2], [1, 1, 1, 1, 2, 2, 2, 2]], - pd.Index([3, 4], name="C"), + Index([3, 4], name="C"), pd.MultiIndex.from_tuples( [ ("d", "a", 1), @@ -512,7 +512,7 @@ def test_unstack_level_binding(self): [[np.nan, 0], [0, np.nan], [np.nan, 0], [0, np.nan]], dtype=np.float64 ), index=expected_mi, - columns=pd.Index(["a", "b"], name="third"), + columns=Index(["a", "b"], name="third"), ) tm.assert_frame_equal(result, expected) @@ -703,7 +703,7 @@ def test_unstack_long_index(self): [[0, 0, 1, 0, 0, 0, 1]], names=["c1", "i2", "i3", "i4", "i5", "i6", "i7"], ), - index=pd.Index([0], name="i1"), + index=Index([0], name="i1"), ) tm.assert_frame_equal(result, expected) @@ -1153,7 +1153,7 @@ def test_unstack_timezone_aware_values(): result = df.set_index(["a", "b"]).unstack() expected = DataFrame( [[pd.Timestamp("2017-08-27 01:00:00.709949+0000", tz="UTC"), "c"]], - index=pd.Index(["a"], name="a"), + index=Index(["a"], name="a"), columns=pd.MultiIndex( levels=[["timestamp", "c"], ["b"]], codes=[[0, 1], [0, 0]], @@ -1216,7 +1216,7 @@ def test_stack_positional_level_duplicate_column_names(): df = DataFrame([[1, 1, 1, 1]], columns=columns) result = df.stack(0) - new_columns = pd.Index(["y", "z"], name="a") + new_columns = Index(["y", "z"], name="a") new_index = pd.MultiIndex.from_tuples([(0, "x"), (0, "y")], names=[None, "a"]) expected = DataFrame([[1, 1], [1, 1]], index=new_index, columns=new_columns) @@ -1276,7 +1276,7 @@ def test_unstack_partial( columns=pd.MultiIndex.from_product( [result_columns[2:], [index_product]], names=[None, "ix2"] ), - index=pd.Index([2], name="ix1"), + index=Index([2], name="ix1"), ) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py index 38032ff717afc..5bf1ce508dfc4 100644 --- a/pandas/tests/frame/test_to_csv.py +++ b/pandas/tests/frame/test_to_csv.py @@ -135,7 +135,7 @@ def test_to_csv_from_csv4(self): dt = pd.Timedelta(seconds=1) df = DataFrame( {"dt_data": [i * dt for i in range(3)]}, - index=pd.Index([i * dt for i in range(3)], name="dt_index"), + index=Index([i * dt for i in range(3)], name="dt_index"), ) df.to_csv(path) @@ -1310,7 +1310,7 @@ def test_multi_index_header(self): def test_to_csv_single_level_multi_index(self): # see gh-26303 - index = pd.Index([(1,), (2,), (3,)]) + index = Index([(1,), (2,), (3,)]) df = DataFrame([[1, 2, 3]], columns=index) df = df.reindex(columns=[(1,), (3,)]) expected = ",1,3\n0,1,3\n" diff --git a/pandas/tests/groupby/aggregate/test_aggregate.py b/pandas/tests/groupby/aggregate/test_aggregate.py index a1cbf38d8eae6..dba039b66d22d 100644 --- a/pandas/tests/groupby/aggregate/test_aggregate.py +++ b/pandas/tests/groupby/aggregate/test_aggregate.py @@ -132,7 +132,7 @@ def test_agg_apply_corner(ts, tsframe): assert ts.dtype == np.float64 # groupby float64 values results in Float64Index - exp = Series([], dtype=np.float64, index=pd.Index([], dtype=np.float64)) + exp = Series([], dtype=np.float64, index=Index([], dtype=np.float64)) tm.assert_series_equal(grouped.sum(), exp) tm.assert_series_equal(grouped.agg(np.sum), exp) tm.assert_series_equal(grouped.apply(np.sum), exp, check_index_type=False) @@ -140,7 +140,7 @@ def test_agg_apply_corner(ts, tsframe): # DataFrame grouped = tsframe.groupby(tsframe["A"] * np.nan) exp_df = DataFrame( - columns=tsframe.columns, dtype=float, index=pd.Index([], dtype=np.float64) + columns=tsframe.columns, dtype=float, index=Index([], dtype=np.float64) ) tm.assert_frame_equal(grouped.sum(), exp_df, check_names=False) tm.assert_frame_equal(grouped.agg(np.sum), exp_df, check_names=False) @@ -427,7 +427,7 @@ def test_order_aggregate_multiple_funcs(): res = df.groupby("A").agg(["sum", "max", "mean", "ohlc", "min"]) result = res.columns.levels[1] - expected = pd.Index(["sum", "max", "mean", "ohlc", "min"]) + expected = Index(["sum", "max", "mean", "ohlc", "min"]) tm.assert_index_equal(result, expected) @@ -481,7 +481,7 @@ def test_agg_split_block(): result = df.groupby("key1").min() expected = DataFrame( {"key2": ["one", "one"], "key3": ["six", "six"]}, - index=pd.Index(["a", "b"], name="key1"), + index=Index(["a", "b"], name="key1"), ) tm.assert_frame_equal(result, expected) @@ -573,7 +573,7 @@ def test_agg_relabel(self): result = df.groupby("group").agg(a_max=("A", "max"), b_max=("B", "max")) expected = DataFrame( {"a_max": [1, 3], "b_max": [6, 8]}, - index=pd.Index(["a", "b"], name="group"), + index=Index(["a", "b"], name="group"), columns=["a_max", "b_max"], ) tm.assert_frame_equal(result, expected) @@ -597,7 +597,7 @@ def test_agg_relabel(self): "b_max": [6, 8], "a_98": [0.98, 2.98], }, - index=pd.Index(["a", "b"], name="group"), + index=Index(["a", "b"], name="group"), columns=["b_min", "a_min", "a_mean", "a_max", "b_max", "a_98"], ) tm.assert_frame_equal(result, expected) @@ -608,9 +608,7 @@ def test_agg_relabel_non_identifier(self): ) result = df.groupby("group").agg(**{"my col": ("A", "max")}) - expected = DataFrame( - {"my col": [1, 3]}, index=pd.Index(["a", "b"], name="group") - ) + expected = DataFrame({"my col": [1, 3]}, index=Index(["a", "b"], name="group")) tm.assert_frame_equal(result, expected) def test_duplicate_no_raises(self): @@ -619,9 +617,7 @@ def test_duplicate_no_raises(self): df = DataFrame({"A": [0, 0, 1, 1], "B": [1, 2, 3, 4]}) grouped = df.groupby("A").agg(a=("B", "min"), b=("B", "min")) - expected = DataFrame( - {"a": [1, 3], "b": [1, 3]}, index=pd.Index([0, 1], name="A") - ) + expected = DataFrame({"a": [1, 3], "b": [1, 3]}, index=Index([0, 1], name="A")) tm.assert_frame_equal(grouped, expected) quant50 = functools.partial(np.percentile, q=50) @@ -636,7 +632,7 @@ def test_duplicate_no_raises(self): ) expected = DataFrame( {"quantile_50": [1.5, 4.0], "quantile_70": [1.7, 4.4]}, - index=pd.Index(["a", "b"], name="col1"), + index=Index(["a", "b"], name="col1"), ) tm.assert_frame_equal(grouped, expected) @@ -682,9 +678,7 @@ def test_agg_namedtuple(self): def test_mangled(self): df = DataFrame({"A": [0, 1], "B": [1, 2], "C": [3, 4]}) result = df.groupby("A").agg(b=("B", lambda x: 0), c=("C", lambda x: 1)) - expected = DataFrame( - {"b": [0, 0], "c": [1, 1]}, index=pd.Index([0, 1], name="A") - ) + expected = DataFrame({"b": [0, 0], "c": [1, 1]}, index=Index([0, 1], name="A")) tm.assert_frame_equal(result, expected) @@ -725,7 +719,7 @@ def test_agg_relabel_multiindex_column( {"group": ["a", "a", "b", "b"], "A": [0, 1, 2, 3], "B": [5, 6, 7, 8]} ) df.columns = pd.MultiIndex.from_tuples([("x", "group"), ("y", "A"), ("y", "B")]) - idx = pd.Index(["a", "b"], name=("x", "group")) + idx = Index(["a", "b"], name=("x", "group")) result = df.groupby(("x", "group")).agg(a_max=(("y", "A"), "max")) expected = DataFrame({"a_max": [1, 3]}, index=idx) @@ -763,7 +757,7 @@ def test_agg_relabel_multiindex_duplicates(): result = df.groupby(("x", "group")).agg( a=(("y", "A"), "min"), b=(("y", "A"), "min") ) - idx = pd.Index(["a", "b"], name=("x", "group")) + idx = Index(["a", "b"], name=("x", "group")) expected = DataFrame({"a": [0, 2], "b": [0, 2]}, index=idx) tm.assert_frame_equal(result, expected) @@ -775,7 +769,7 @@ def test_groupby_aggregate_empty_key(kwargs): result = df.groupby("a").agg(kwargs) expected = DataFrame( [1, 4], - index=pd.Index([1, 2], dtype="int64", name="a"), + index=Index([1, 2], dtype="int64", name="a"), columns=pd.MultiIndex.from_tuples([["c", "min"]]), ) tm.assert_frame_equal(result, expected) @@ -936,7 +930,7 @@ def test_basic(self): expected = DataFrame( {("B", "<lambda_0>"): [0, 0], ("B", "<lambda_1>"): [1, 1]}, - index=pd.Index([0, 1], name="A"), + index=Index([0, 1], name="A"), ) tm.assert_frame_equal(result, expected) @@ -975,7 +969,7 @@ def test_agg_with_one_lambda(self): "height_max": [9.5, 34.0], "weight_max": [9.9, 198.0], }, - index=pd.Index(["cat", "dog"], name="kind"), + index=Index(["cat", "dog"], name="kind"), columns=columns, ) @@ -1022,7 +1016,7 @@ def test_agg_multiple_lambda(self): "height_max_2": [9.5, 34.0], "weight_min": [7.9, 7.5], }, - index=pd.Index(["cat", "dog"], name="kind"), + index=Index(["cat", "dog"], name="kind"), columns=columns, ) diff --git a/pandas/tests/groupby/test_apply.py b/pandas/tests/groupby/test_apply.py index ab44bd17d3f15..f5078930a7b4b 100644 --- a/pandas/tests/groupby/test_apply.py +++ b/pandas/tests/groupby/test_apply.py @@ -40,7 +40,7 @@ def test_apply_issues(): # GH 5789 # don't auto coerce dates df = pd.read_csv(StringIO(s), header=None, names=["date", "time", "value"]) - exp_idx = pd.Index( + exp_idx = Index( ["2011.05.16", "2011.05.17", "2011.05.18"], dtype=object, name="date" ) expected = Series(["00:00", "02:00", "02:00"], index=exp_idx) @@ -886,7 +886,7 @@ def test_apply_multi_level_name(category): b = pd.Categorical(b, categories=[1, 2, 3]) expected_index = pd.CategoricalIndex([1, 2], categories=[1, 2, 3], name="B") else: - expected_index = pd.Index([1, 2], name="B") + expected_index = Index([1, 2], name="B") df = DataFrame( {"A": np.arange(10), "B": b, "C": list(range(10)), "D": list(range(10))} ).set_index(["A", "B"]) @@ -951,7 +951,7 @@ def test_apply_function_returns_non_pandas_non_scalar(function, expected_values) # GH 31441 df = DataFrame(["A", "A", "B", "B"], columns=["groups"]) result = df.groupby("groups").apply(function) - expected = Series(expected_values, index=pd.Index(["A", "B"], name="groups")) + expected = Series(expected_values, index=Index(["A", "B"], name="groups")) tm.assert_series_equal(result, expected) @@ -964,7 +964,7 @@ def fct(group): result = df.groupby("A").apply(fct) expected = Series( - [[1.0, 2.0], [3.0], [np.nan]], index=pd.Index(["a", "b", "none"], name="A") + [[1.0, 2.0], [3.0], [np.nan]], index=Index(["a", "b", "none"], name="A") ) tm.assert_series_equal(result, expected) @@ -975,8 +975,8 @@ def test_apply_function_index_return(function): df = DataFrame([1, 2, 2, 2, 1, 2, 3, 1, 3, 1], columns=["id"]) result = df.groupby("id").apply(function) expected = Series( - [pd.Index([0, 4, 7, 9]), pd.Index([1, 2, 3, 5]), pd.Index([6, 8])], - index=pd.Index([1, 2, 3], name="id"), + [Index([0, 4, 7, 9]), Index([1, 2, 3, 5]), Index([6, 8])], + index=Index([1, 2, 3], name="id"), ) tm.assert_series_equal(result, expected) @@ -1042,7 +1042,7 @@ def test_apply_is_unchanged_when_other_methods_are_called_first(reduction_func): expected = DataFrame( {"a": [264, 297], "b": [15, 6], "c": [150, 60]}, - index=pd.Index([88, 99], name="a"), + index=Index([88, 99], name="a"), ) # Check output when no other methods are called before .apply() @@ -1072,7 +1072,7 @@ def test_apply_with_date_in_multiindex_does_not_convert_to_timestamp(): ], "C": [1, 2, 3, 4], }, - index=pd.Index([100, 101, 102, 103], name="idx"), + index=Index([100, 101, 102, 103], name="idx"), ) grp = df.groupby(["A", "B"]) diff --git a/pandas/tests/groupby/test_categorical.py b/pandas/tests/groupby/test_categorical.py index 9785a95f3b6cb..c29c9e15ada79 100644 --- a/pandas/tests/groupby/test_categorical.py +++ b/pandas/tests/groupby/test_categorical.py @@ -1447,7 +1447,7 @@ def test_groupby_agg_categorical_columns(func, expected_values): result = df.groupby("groups").agg(func) expected = DataFrame( - {"value": expected_values}, index=pd.Index([0, 1, 2], name="groups") + {"value": expected_values}, index=Index([0, 1, 2], name="groups") ) tm.assert_frame_equal(result, expected) @@ -1470,7 +1470,7 @@ def test_groupy_first_returned_categorical_instead_of_dataframe(func): df = DataFrame({"A": [1997], "B": Series(["b"], dtype="category").cat.as_ordered()}) df_grouped = df.groupby("A")["B"] result = getattr(df_grouped, func)() - expected = Series(["b"], index=pd.Index([1997], name="A"), name="B") + expected = Series(["b"], index=Index([1997], name="A"), name="B") tm.assert_series_equal(result, expected) @@ -1537,9 +1537,7 @@ def test_agg_cython_category_not_implemented_fallback(): df["col_cat"] = df["col_num"].astype("category") result = df.groupby("col_num").col_cat.first() - expected = Series( - [1, 2, 3], index=pd.Index([1, 2, 3], name="col_num"), name="col_cat" - ) + expected = Series([1, 2, 3], index=Index([1, 2, 3], name="col_num"), name="col_cat") tm.assert_series_equal(result, expected) result = df.groupby("col_num").agg({"col_cat": "first"}) @@ -1553,7 +1551,7 @@ def test_aggregate_categorical_lost_index(func: str): ds = Series(["b"], dtype="category").cat.as_ordered() df = DataFrame({"A": [1997], "B": ds}) result = df.groupby("A").agg({"B": func}) - expected = DataFrame({"B": ["b"]}, index=pd.Index([1997], name="A")) + expected = DataFrame({"B": ["b"]}, index=Index([1997], name="A")) tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/groupby/test_function.py b/pandas/tests/groupby/test_function.py index 6d760035246c7..05a959ea6f22b 100644 --- a/pandas/tests/groupby/test_function.py +++ b/pandas/tests/groupby/test_function.py @@ -303,7 +303,7 @@ def test_non_cython_api(): tm.assert_frame_equal(result, expected) # describe - expected_index = pd.Index([1, 3], name="A") + expected_index = Index([1, 3], name="A") expected_col = pd.MultiIndex( levels=[["B"], ["count", "mean", "std", "min", "25%", "50%", "75%", "max"]], codes=[[0] * 8, list(range(8))], @@ -325,7 +325,7 @@ def test_non_cython_api(): df[df.A == 3].describe().unstack().to_frame().T, ] ) - expected.index = pd.Index([0, 1]) + expected.index = Index([0, 1]) result = gni.describe() tm.assert_frame_equal(result, expected) @@ -933,7 +933,7 @@ def test_frame_describe_unstacked_format(): ] expected = DataFrame( data, - index=pd.Index([24990, 25499], name="PRICE"), + index=Index([24990, 25499], name="PRICE"), columns=["count", "mean", "std", "min", "25%", "50%", "75%", "max"], ) tm.assert_frame_equal(result, expected) @@ -989,7 +989,7 @@ def test_describe_with_duplicate_output_column_names(as_index): .T ) expected.columns.names = [None, None] - expected.index = pd.Index([88, 99], name="a") + expected.index = Index([88, 99], name="a") if as_index: expected = expected.drop(columns=["a"], level=0) @@ -1027,7 +1027,7 @@ def test_apply_to_nullable_integer_returns_float(values, function): # https://github.com/pandas-dev/pandas/issues/32219 output = 0.5 if function == "var" else 1.5 arr = np.array([output] * 3, dtype=float) - idx = pd.Index([1, 2, 3], dtype=object, name="a") + idx = Index([1, 2, 3], dtype=object, name="a") expected = DataFrame({"b": arr}, index=idx) groups = DataFrame(values, dtype="Int64").groupby("a") @@ -1047,7 +1047,7 @@ def test_groupby_sum_below_mincount_nullable_integer(): # https://github.com/pandas-dev/pandas/issues/32861 df = DataFrame({"a": [0, 1, 2], "b": [0, 1, 2], "c": [0, 1, 2]}, dtype="Int64") grouped = df.groupby("a") - idx = pd.Index([0, 1, 2], dtype=object, name="a") + idx = Index([0, 1, 2], dtype=object, name="a") result = grouped["b"].sum(min_count=2) expected = Series([pd.NA] * 3, dtype="Int64", index=idx, name="b") diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 1c8c7cbaa68c5..2e51fca71e139 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -1255,7 +1255,7 @@ def test_groupby_nat_exclude(): ) grouped = df.groupby("dt") - expected = [pd.Index([1, 7]), pd.Index([3, 5])] + expected = [Index([1, 7]), Index([3, 5])] keys = sorted(grouped.groups.keys()) assert len(keys) == 2 for k, e in zip(keys, expected): @@ -1775,7 +1775,7 @@ def test_tuple_as_grouping(): df[["a", "b", "c"]].groupby(("a", "b")) result = df.groupby(("a", "b"))["c"].sum() - expected = Series([4], name="c", index=pd.Index([1], name=("a", "b"))) + expected = Series([4], name="c", index=Index([1], name=("a", "b"))) tm.assert_series_equal(result, expected) @@ -1990,7 +1990,7 @@ def test_bool_aggs_dup_column_labels(bool_agg_func): @pytest.mark.parametrize( - "idx", [pd.Index(["a", "a"]), pd.MultiIndex.from_tuples((("a", "a"), ("a", "a")))] + "idx", [Index(["a", "a"]), pd.MultiIndex.from_tuples((("a", "a"), ("a", "a")))] ) @pytest.mark.filterwarnings("ignore:tshift is deprecated:FutureWarning") def test_dup_labels_output_shape(groupby_func, idx): @@ -2118,7 +2118,7 @@ def test_subsetting_columns_keeps_attrs(klass, attr, value): @pytest.mark.parametrize("func", ["sum", "any", "shift"]) def test_groupby_column_index_name_lost(func): # GH: 29764 groupby loses index sometimes - expected = pd.Index(["a"], name="idx") + expected = Index(["a"], name="idx") df = DataFrame([[1]], columns=expected) df_grouped = df.groupby([1]) result = getattr(df_grouped, func)().columns diff --git a/pandas/tests/groupby/test_grouping.py b/pandas/tests/groupby/test_grouping.py index 48859db305e46..6c74e1521eeeb 100644 --- a/pandas/tests/groupby/test_grouping.py +++ b/pandas/tests/groupby/test_grouping.py @@ -167,7 +167,7 @@ def test_grouper_multilevel_freq(self): .sum() ) # reset index changes columns dtype to object - expected.columns = pd.Index([0], dtype="int64") + expected.columns = Index([0], dtype="int64") result = df.groupby( [pd.Grouper(level="foo", freq="W"), pd.Grouper(level="bar", freq="W")] @@ -297,7 +297,7 @@ def test_groupby_levels_and_columns(self): tm.assert_frame_equal(by_levels, by_columns, check_column_type=False) - by_columns.columns = pd.Index(by_columns.columns, dtype=np.int64) + by_columns.columns = Index(by_columns.columns, dtype=np.int64) tm.assert_frame_equal(by_levels, by_columns) def test_groupby_categorical_index_and_columns(self, observed): @@ -602,7 +602,7 @@ def test_list_grouper_with_nat(self): # Grouper in a list grouping result = df.groupby([grouper]) - expected = {pd.Timestamp("2011-01-01"): pd.Index(list(range(364)))} + expected = {pd.Timestamp("2011-01-01"): Index(list(range(364)))} tm.assert_dict_equal(result.groups, expected) # Test case without a list @@ -787,7 +787,7 @@ def test_groupby_with_single_column(self): df = DataFrame({"a": list("abssbab")}) tm.assert_frame_equal(df.groupby("a").get_group("a"), df.iloc[[0, 5]]) # GH 13530 - exp = DataFrame(index=pd.Index(["a", "b", "s"], name="a")) + exp = DataFrame(index=Index(["a", "b", "s"], name="a")) tm.assert_frame_equal(df.groupby("a").count(), exp) tm.assert_frame_equal(df.groupby("a").sum(), exp) tm.assert_frame_equal(df.groupby("a").nth(1), exp) diff --git a/pandas/tests/groupby/test_nth.py b/pandas/tests/groupby/test_nth.py index fe35f6f5d9416..e82b23054f1cb 100644 --- a/pandas/tests/groupby/test_nth.py +++ b/pandas/tests/groupby/test_nth.py @@ -66,7 +66,7 @@ def test_first_last_with_na_object(method, nulls_fixture): values = [2, 3] values = np.array(values, dtype=result["b"].dtype) - idx = pd.Index([1, 2], name="a") + idx = Index([1, 2], name="a") expected = DataFrame({"b": values}, index=idx) tm.assert_frame_equal(result, expected) @@ -84,7 +84,7 @@ def test_nth_with_na_object(index, nulls_fixture): values = [2, nulls_fixture] values = np.array(values, dtype=result["b"].dtype) - idx = pd.Index([1, 2], name="a") + idx = Index([1, 2], name="a") expected = DataFrame({"b": values}, index=idx) tm.assert_frame_equal(result, expected) @@ -398,7 +398,7 @@ def test_first_last_tz_multi_column(method, ts, alpha): ), "datetimetz": [ts, Timestamp("2013-01-03", tz="US/Eastern")], }, - index=pd.Index([1, 2], name="group"), + index=Index([1, 2], name="group"), ) tm.assert_frame_equal(result, expected) @@ -496,9 +496,7 @@ def test_groupby_head_tail(): tm.assert_frame_equal(df.loc[[0, 2]], g_not_as.head(1)) tm.assert_frame_equal(df.loc[[1, 2]], g_not_as.tail(1)) - empty_not_as = DataFrame( - columns=df.columns, index=pd.Index([], dtype=df.index.dtype) - ) + empty_not_as = DataFrame(columns=df.columns, index=Index([], dtype=df.index.dtype)) empty_not_as["A"] = empty_not_as["A"].astype(df.A.dtype) empty_not_as["B"] = empty_not_as["B"].astype(df.B.dtype) tm.assert_frame_equal(empty_not_as, g_not_as.head(0)) diff --git a/pandas/tests/groupby/test_pipe.py b/pandas/tests/groupby/test_pipe.py index 6812ac6ce8f34..1acbc8cf5c0ad 100644 --- a/pandas/tests/groupby/test_pipe.py +++ b/pandas/tests/groupby/test_pipe.py @@ -64,7 +64,7 @@ def h(df, arg3): result = df.groupby("group").pipe(f, 0).pipe(g, 10).pipe(h, 100) # Assert the results here - index = pd.Index(["A", "B", "C"], name="group") + index = Index(["A", "B", "C"], name="group") expected = pd.Series([-79.5160891089, -78.4839108911, -80], index=index) tm.assert_series_equal(expected, result) diff --git a/pandas/tests/indexes/base_class/test_reshape.py b/pandas/tests/indexes/base_class/test_reshape.py index 61826f2403a4b..5ebab965e6f04 100644 --- a/pandas/tests/indexes/base_class/test_reshape.py +++ b/pandas/tests/indexes/base_class/test_reshape.py @@ -3,7 +3,6 @@ """ import pytest -import pandas as pd from pandas import Index import pandas._testing as tm @@ -11,8 +10,8 @@ class TestReshape: def test_repeat(self): repeats = 2 - index = pd.Index([1, 2, 3]) - expected = pd.Index([1, 1, 2, 2, 3, 3]) + index = Index([1, 2, 3]) + expected = Index([1, 1, 2, 2, 3, 3]) result = index.repeat(repeats) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/base_class/test_setops.py b/pandas/tests/indexes/base_class/test_setops.py index 77b5e2780464d..94c6d2ad6dc95 100644 --- a/pandas/tests/indexes/base_class/test_setops.py +++ b/pandas/tests/indexes/base_class/test_setops.py @@ -12,14 +12,14 @@ class TestIndexSetOps: "method", ["union", "intersection", "difference", "symmetric_difference"] ) def test_setops_disallow_true(self, method): - idx1 = pd.Index(["a", "b"]) - idx2 = pd.Index(["b", "c"]) + idx1 = Index(["a", "b"]) + idx2 = Index(["b", "c"]) with pytest.raises(ValueError, match="The 'sort' keyword only takes"): getattr(idx1, method)(idx2, sort=True) def test_setops_preserve_object_dtype(self): - idx = pd.Index([1, 2, 3], dtype=object) + idx = Index([1, 2, 3], dtype=object) result = idx.intersection(idx[1:]) expected = idx[1:] tm.assert_index_equal(result, expected) @@ -67,7 +67,7 @@ def test_union_different_type_base(self, klass): def test_union_sort_other_incomparable(self): # https://github.com/pandas-dev/pandas/issues/24959 - idx = pd.Index([1, pd.Timestamp("2000")]) + idx = Index([1, pd.Timestamp("2000")]) # default (sort=None) with tm.assert_produces_warning(RuntimeWarning): result = idx.union(idx[:1]) @@ -87,7 +87,7 @@ def test_union_sort_other_incomparable(self): def test_union_sort_other_incomparable_true(self): # TODO decide on True behaviour # sort=True - idx = pd.Index([1, pd.Timestamp("2000")]) + idx = Index([1, pd.Timestamp("2000")]) with pytest.raises(TypeError, match=".*"): idx.union(idx[:1], sort=True) @@ -112,12 +112,12 @@ def test_intersection_different_type_base(self, klass, sort): assert tm.equalContents(result, second) def test_intersect_nosort(self): - result = pd.Index(["c", "b", "a"]).intersection(["b", "a"]) - expected = pd.Index(["b", "a"]) + result = Index(["c", "b", "a"]).intersection(["b", "a"]) + expected = Index(["b", "a"]) tm.assert_index_equal(result, expected) def test_intersection_equal_sort(self): - idx = pd.Index(["c", "a", "b"]) + idx = Index(["c", "a", "b"]) tm.assert_index_equal(idx.intersection(idx, sort=False), idx) tm.assert_index_equal(idx.intersection(idx, sort=None), idx) diff --git a/pandas/tests/indexes/categorical/test_category.py b/pandas/tests/indexes/categorical/test_category.py index 81b31e3ea180c..2bfe9bf0194ec 100644 --- a/pandas/tests/indexes/categorical/test_category.py +++ b/pandas/tests/indexes/categorical/test_category.py @@ -42,7 +42,7 @@ def test_can_hold_identifiers(self): def test_disallow_addsub_ops(self, func, op_name): # GH 10039 # set ops (+/-) raise TypeError - idx = pd.Index(pd.Categorical(["a", "b"])) + idx = Index(pd.Categorical(["a", "b"])) cat_or_list = "'(Categorical|list)' and '(Categorical|list)'" msg = "|".join( [ diff --git a/pandas/tests/indexes/categorical/test_map.py b/pandas/tests/indexes/categorical/test_map.py index 6cef555275444..55e050ebdb2d8 100644 --- a/pandas/tests/indexes/categorical/test_map.py +++ b/pandas/tests/indexes/categorical/test_map.py @@ -64,13 +64,13 @@ def f(x): def test_map_with_categorical_series(self): # GH 12756 - a = pd.Index([1, 2, 3, 4]) + a = Index([1, 2, 3, 4]) b = pd.Series(["even", "odd", "even", "odd"], dtype="category") c = pd.Series(["even", "odd", "even", "odd"]) exp = CategoricalIndex(["odd", "even", "odd", np.nan]) tm.assert_index_equal(a.map(b), exp) - exp = pd.Index(["odd", "even", "odd", np.nan]) + exp = Index(["odd", "even", "odd", np.nan]) tm.assert_index_equal(a.map(c), exp) @pytest.mark.parametrize( @@ -91,5 +91,5 @@ def test_map_with_nan(self, data, f): # GH 24241 expected = pd.Categorical([False, False, np.nan]) tm.assert_categorical_equal(result, expected) else: - expected = pd.Index([False, False, np.nan]) + expected = Index([False, False, np.nan]) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index d6d8854f4f78a..b20026b20e1d7 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -93,15 +93,15 @@ def test_create_index_existing_name(self): expected = self.create_index() if not isinstance(expected, MultiIndex): expected.name = "foo" - result = pd.Index(expected) + result = Index(expected) tm.assert_index_equal(result, expected) - result = pd.Index(expected, name="bar") + result = Index(expected, name="bar") expected.name = "bar" tm.assert_index_equal(result, expected) else: expected.names = ["foo", "bar"] - result = pd.Index(expected) + result = Index(expected) tm.assert_index_equal( result, Index( @@ -120,7 +120,7 @@ def test_create_index_existing_name(self): ), ) - result = pd.Index(expected, names=["A", "B"]) + result = Index(expected, names=["A", "B"]) tm.assert_index_equal( result, Index( @@ -410,12 +410,12 @@ def test_take_invalid_kwargs(self): def test_repeat(self): rep = 2 i = self.create_index() - expected = pd.Index(i.values.repeat(rep), name=i.name) + expected = Index(i.values.repeat(rep), name=i.name) tm.assert_index_equal(i.repeat(rep), expected) i = self.create_index() rep = np.arange(len(i)) - expected = pd.Index(i.values.repeat(rep), name=i.name) + expected = Index(i.values.repeat(rep), name=i.name) tm.assert_index_equal(i.repeat(rep), expected) def test_numpy_repeat(self): @@ -441,7 +441,7 @@ def test_where(self, klass): tm.assert_index_equal(result, expected) cond = [False] + [True] * len(i[1:]) - expected = pd.Index([i._na_value] + i[1:].tolist(), dtype=i.dtype) + expected = Index([i._na_value] + i[1:].tolist(), dtype=i.dtype) result = i.where(klass(cond)) tm.assert_index_equal(result, expected) @@ -824,7 +824,7 @@ def test_map_dictlike(self, mapper): tm.assert_index_equal(result, expected) # empty mappable - expected = pd.Index([np.nan] * len(index)) + expected = Index([np.nan] * len(index)) result = index.map(mapper(expected, index)) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/datetimes/test_astype.py b/pandas/tests/indexes/datetimes/test_astype.py index 3e7e76bba0dde..13b658b31e3ee 100644 --- a/pandas/tests/indexes/datetimes/test_astype.py +++ b/pandas/tests/indexes/datetimes/test_astype.py @@ -179,7 +179,7 @@ def test_astype_object_tz(self, tz): Timestamp("2013-03-31", tz=tz), Timestamp("2013-04-30", tz=tz), ] - expected = pd.Index(expected_list, dtype=object, name="idx") + expected = Index(expected_list, dtype=object, name="idx") result = idx.astype(object) tm.assert_index_equal(result, expected) assert idx.tolist() == expected_list @@ -195,7 +195,7 @@ def test_astype_object_with_nat(self): pd.NaT, Timestamp("2013-01-04"), ] - expected = pd.Index(expected_list, dtype=object, name="idx") + expected = Index(expected_list, dtype=object, name="idx") result = idx.astype(object) tm.assert_index_equal(result, expected) assert idx.tolist() == expected_list @@ -269,7 +269,7 @@ def _check_rng(rng): def test_integer_index_astype_datetime(self, tz, dtype): # GH 20997, 20964, 24559 val = [pd.Timestamp("2018-01-01", tz=tz).value] - result = pd.Index(val, name="idx").astype(dtype) + result = Index(val, name="idx").astype(dtype) expected = pd.DatetimeIndex(["2018-01-01"], tz=tz, name="idx") tm.assert_index_equal(result, expected) @@ -304,7 +304,7 @@ def test_astype_category(self, tz): def test_astype_array_fallback(self, tz): obj = pd.date_range("2000", periods=2, tz=tz, name="idx") result = obj.astype(bool) - expected = pd.Index(np.array([True, True]), name="idx") + expected = Index(np.array([True, True]), name="idx") tm.assert_index_equal(result, expected) result = obj._data.astype(bool) diff --git a/pandas/tests/indexes/datetimes/test_constructors.py b/pandas/tests/indexes/datetimes/test_constructors.py index d3c79f231449a..0c562e7b8f848 100644 --- a/pandas/tests/indexes/datetimes/test_constructors.py +++ b/pandas/tests/indexes/datetimes/test_constructors.py @@ -464,12 +464,12 @@ def test_construction_dti_with_mixed_timezones(self): def test_construction_base_constructor(self): arr = [pd.Timestamp("2011-01-01"), pd.NaT, pd.Timestamp("2011-01-03")] - tm.assert_index_equal(pd.Index(arr), pd.DatetimeIndex(arr)) - tm.assert_index_equal(pd.Index(np.array(arr)), pd.DatetimeIndex(np.array(arr))) + tm.assert_index_equal(Index(arr), pd.DatetimeIndex(arr)) + tm.assert_index_equal(Index(np.array(arr)), pd.DatetimeIndex(np.array(arr))) arr = [np.nan, pd.NaT, pd.Timestamp("2011-01-03")] - tm.assert_index_equal(pd.Index(arr), pd.DatetimeIndex(arr)) - tm.assert_index_equal(pd.Index(np.array(arr)), pd.DatetimeIndex(np.array(arr))) + tm.assert_index_equal(Index(arr), pd.DatetimeIndex(arr)) + tm.assert_index_equal(Index(np.array(arr)), pd.DatetimeIndex(np.array(arr))) def test_construction_outofbounds(self): # GH 13663 @@ -856,7 +856,7 @@ def test_constructor_no_precision_raises(self): pd.DatetimeIndex(["2000"], dtype="datetime64") with pytest.raises(ValueError, match=msg): - pd.Index(["2000"], dtype="datetime64") + Index(["2000"], dtype="datetime64") def test_constructor_wrong_precision_raises(self): msg = "Unexpected value for 'dtype': 'datetime64\\[us\\]'" diff --git a/pandas/tests/indexes/datetimes/test_misc.py b/pandas/tests/indexes/datetimes/test_misc.py index 51841727d510b..375a88f2f2634 100644 --- a/pandas/tests/indexes/datetimes/test_misc.py +++ b/pandas/tests/indexes/datetimes/test_misc.py @@ -375,7 +375,7 @@ def test_datetime_name_accessors(self, time_locale): def test_nanosecond_field(self): dti = DatetimeIndex(np.arange(10)) - tm.assert_index_equal(dti.nanosecond, pd.Index(np.arange(10, dtype=np.int64))) + tm.assert_index_equal(dti.nanosecond, Index(np.arange(10, dtype=np.int64))) def test_iter_readonly(): diff --git a/pandas/tests/indexes/datetimes/test_ops.py b/pandas/tests/indexes/datetimes/test_ops.py index ada4902f6900b..4c632aba51c45 100644 --- a/pandas/tests/indexes/datetimes/test_ops.py +++ b/pandas/tests/indexes/datetimes/test_ops.py @@ -349,7 +349,7 @@ def test_equals(self): assert not idx.equals(Series(idx3)) # check that we do not raise when comparing with OutOfBounds objects - oob = pd.Index([datetime(2500, 1, 1)] * 3, dtype=object) + oob = Index([datetime(2500, 1, 1)] * 3, dtype=object) assert not idx.equals(oob) assert not idx2.equals(oob) assert not idx3.equals(oob) diff --git a/pandas/tests/indexes/datetimes/test_setops.py b/pandas/tests/indexes/datetimes/test_setops.py index a8baf67273490..c02441b5883df 100644 --- a/pandas/tests/indexes/datetimes/test_setops.py +++ b/pandas/tests/indexes/datetimes/test_setops.py @@ -201,7 +201,7 @@ def test_intersection2(self): third = Index(["a", "b", "c"]) result = first.intersection(third) - expected = pd.Index([], dtype=object) + expected = Index([], dtype=object) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( diff --git a/pandas/tests/indexes/multi/test_analytics.py b/pandas/tests/indexes/multi/test_analytics.py index d661a56311e6c..bd4926880c13d 100644 --- a/pandas/tests/indexes/multi/test_analytics.py +++ b/pandas/tests/indexes/multi/test_analytics.py @@ -127,9 +127,9 @@ def test_append_mixed_dtypes(): [1, 2, 3, "x", "y", "z"], [1.1, np.nan, 3.3, "x", "y", "z"], ["a", "b", "c", "x", "y", "z"], - dti.append(pd.Index(["x", "y", "z"])), - dti_tz.append(pd.Index(["x", "y", "z"])), - pi.append(pd.Index(["x", "y", "z"])), + dti.append(Index(["x", "y", "z"])), + dti_tz.append(Index(["x", "y", "z"])), + pi.append(Index(["x", "y", "z"])), ] ) tm.assert_index_equal(res, exp) @@ -203,7 +203,7 @@ def test_map_dictlike(idx, mapper): tm.assert_index_equal(result, expected) # empty mappable - expected = pd.Index([np.nan] * len(idx)) + expected = Index([np.nan] * len(idx)) result = idx.map(mapper(expected, idx)) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/multi/test_constructors.py b/pandas/tests/indexes/multi/test_constructors.py index 70580f0a83f83..63afd5e130508 100644 --- a/pandas/tests/indexes/multi/test_constructors.py +++ b/pandas/tests/indexes/multi/test_constructors.py @@ -402,9 +402,9 @@ def test_tuples_with_name_string(): li = [(0, 0, 1), (0, 1, 0), (1, 0, 0)] msg = "Names should be list-like for a MultiIndex" with pytest.raises(ValueError, match=msg): - pd.Index(li, name="abc") + Index(li, name="abc") with pytest.raises(ValueError, match=msg): - pd.Index(li, name="a") + Index(li, name="a") def test_from_tuples_with_tuple_label(): @@ -429,7 +429,7 @@ def test_from_product_empty_zero_levels(): def test_from_product_empty_one_level(): result = MultiIndex.from_product([[]], names=["A"]) - expected = pd.Index([], name="A") + expected = Index([], name="A") tm.assert_index_equal(result.levels[0], expected) assert result.names == ["A"] @@ -597,7 +597,7 @@ def test_create_index_existing_name(idx): # specified, the new index should inherit the previous object name index = idx index.names = ["foo", "bar"] - result = pd.Index(index) + result = Index(index) expected = Index( Index( [ @@ -613,7 +613,7 @@ def test_create_index_existing_name(idx): ) tm.assert_index_equal(result, expected) - result = pd.Index(index, name="A") + result = Index(index, name="A") expected = Index( Index( [ @@ -652,7 +652,7 @@ def test_from_frame(): Series([1, 2, 3, 4]), [1, 2, 3, 4], [[1, 2], [3, 4], [5, 6]], - pd.Index([1, 2, 3, 4]), + Index([1, 2, 3, 4]), np.array([[1, 2], [3, 4], [5, 6]]), 27, ], diff --git a/pandas/tests/indexes/multi/test_get_level_values.py b/pandas/tests/indexes/multi/test_get_level_values.py index 985fe5773ceed..ec65ec2c54689 100644 --- a/pandas/tests/indexes/multi/test_get_level_values.py +++ b/pandas/tests/indexes/multi/test_get_level_values.py @@ -44,11 +44,11 @@ def test_get_level_values_all_na(): arrays = [[np.nan, np.nan, np.nan], ["a", np.nan, 1]] index = pd.MultiIndex.from_arrays(arrays) result = index.get_level_values(0) - expected = pd.Index([np.nan, np.nan, np.nan], dtype=np.float64) + expected = Index([np.nan, np.nan, np.nan], dtype=np.float64) tm.assert_index_equal(result, expected) result = index.get_level_values(1) - expected = pd.Index(["a", np.nan, 1], dtype=object) + expected = Index(["a", np.nan, 1], dtype=object) tm.assert_index_equal(result, expected) @@ -71,11 +71,11 @@ def test_get_level_values_na(): arrays = [[np.nan, np.nan, np.nan], ["a", np.nan, 1]] index = pd.MultiIndex.from_arrays(arrays) result = index.get_level_values(0) - expected = pd.Index([np.nan, np.nan, np.nan]) + expected = Index([np.nan, np.nan, np.nan]) tm.assert_index_equal(result, expected) result = index.get_level_values(1) - expected = pd.Index(["a", np.nan, 1]) + expected = Index(["a", np.nan, 1]) tm.assert_index_equal(result, expected) arrays = [["a", "b", "b"], pd.DatetimeIndex([0, 1, pd.NaT])] @@ -87,7 +87,7 @@ def test_get_level_values_na(): arrays = [[], []] index = pd.MultiIndex.from_arrays(arrays) result = index.get_level_values(0) - expected = pd.Index([], dtype=object) + expected = Index([], dtype=object) tm.assert_index_equal(result, expected) diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py index cf494b2ce87cc..81be110fd11e5 100644 --- a/pandas/tests/indexes/multi/test_indexing.py +++ b/pandas/tests/indexes/multi/test_indexing.py @@ -461,10 +461,10 @@ def test_getitem_group_select(idx): assert sorted_idx.get_loc("foo") == slice(0, 2) -@pytest.mark.parametrize("ind1", [[True] * 5, pd.Index([True] * 5)]) +@pytest.mark.parametrize("ind1", [[True] * 5, Index([True] * 5)]) @pytest.mark.parametrize( "ind2", - [[True, False, True, False, False], pd.Index([True, False, True, False, False])], + [[True, False, True, False, False], Index([True, False, True, False, False])], ) def test_getitem_bool_index_all(ind1, ind2): # GH#22533 @@ -475,8 +475,8 @@ def test_getitem_bool_index_all(ind1, ind2): tm.assert_index_equal(idx[ind2], expected) -@pytest.mark.parametrize("ind1", [[True], pd.Index([True])]) -@pytest.mark.parametrize("ind2", [[False], pd.Index([False])]) +@pytest.mark.parametrize("ind1", [[True], Index([True])]) +@pytest.mark.parametrize("ind2", [[False], Index([False])]) def test_getitem_bool_index_single(ind1, ind2): # GH#22533 idx = MultiIndex.from_tuples([(10, 1)]) diff --git a/pandas/tests/indexes/multi/test_join.py b/pandas/tests/indexes/multi/test_join.py index 562d07d283293..6b6b9346fe1fe 100644 --- a/pandas/tests/indexes/multi/test_join.py +++ b/pandas/tests/indexes/multi/test_join.py @@ -52,7 +52,7 @@ def test_join_self(idx, join_type): def test_join_multi(): # GH 10665 midx = pd.MultiIndex.from_product([np.arange(4), np.arange(4)], names=["a", "b"]) - idx = pd.Index([1, 2, 5], name="b") + idx = Index([1, 2, 5], name="b") # inner jidx, lidx, ridx = midx.join(idx, how="inner", return_indexers=True) diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py index 899c8cbc0425d..cd3a0e7b2241c 100644 --- a/pandas/tests/indexes/ranges/test_range.py +++ b/pandas/tests/indexes/ranges/test_range.py @@ -105,7 +105,7 @@ def test_insert(self): tm.assert_index_equal(result, expected) result = RangeIndex(5).insert(1, pd.NaT) - expected = pd.Index([0, pd.NaT, 1, 2, 3, 4], dtype=object) + expected = Index([0, pd.NaT, 1, 2, 3, 4], dtype=object) tm.assert_index_equal(result, expected) def test_delete(self): diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index 0e963531810df..70898367f6a40 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -108,9 +108,9 @@ def test_constructor_copy(self, index): ) def test_constructor_from_index_dtlike(self, cast_as_obj, index): if cast_as_obj: - result = pd.Index(index.astype(object)) + result = Index(index.astype(object)) else: - result = pd.Index(index) + result = Index(index) tm.assert_index_equal(result, index) @@ -121,7 +121,7 @@ def test_constructor_from_index_dtlike(self, cast_as_obj, index): # incorrectly raise ValueError, and that nanoseconds are not # dropped index += pd.Timedelta(nanoseconds=50) - result = pd.Index(index, dtype=object) + result = Index(index, dtype=object) assert result.dtype == np.object_ assert list(result) == list(index) @@ -137,7 +137,7 @@ def test_constructor_from_index_dtlike(self, cast_as_obj, index): ], ) def test_constructor_from_series_dtlike(self, index, has_tz): - result = pd.Index(Series(index)) + result = Index(Series(index)) tm.assert_index_equal(result, index) if has_tz: @@ -195,8 +195,8 @@ def __init__(self, array): def __array__(self, dtype=None) -> np.ndarray: return self.array - expected = pd.Index(array) - result = pd.Index(ArrayLike(array)) + expected = Index(array) + result = Index(ArrayLike(array)) tm.assert_index_equal(result, expected) def test_constructor_int_dtype_nan(self): @@ -216,8 +216,8 @@ def test_constructor_int_dtype_nan_raises(self, dtype): def test_constructor_no_pandas_array(self): ser = Series([1, 2, 3]) - result = pd.Index(ser.array) - expected = pd.Index([1, 2, 3]) + result = Index(ser.array) + expected = Index([1, 2, 3]) tm.assert_index_equal(result, expected) @pytest.mark.parametrize( @@ -338,7 +338,7 @@ def test_constructor_dtypes_to_timedelta(self, cast_index, vals): assert isinstance(index, TimedeltaIndex) @pytest.mark.parametrize("attr", ["values", "asi8"]) - @pytest.mark.parametrize("klass", [pd.Index, pd.DatetimeIndex]) + @pytest.mark.parametrize("klass", [Index, pd.DatetimeIndex]) def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass): # Test constructing with a datetimetz dtype # .values produces numpy datetimes, so these are considered naive @@ -375,7 +375,7 @@ def test_constructor_dtypes_datetime(self, tz_naive_fixture, attr, klass): tm.assert_index_equal(result, index) @pytest.mark.parametrize("attr", ["values", "asi8"]) - @pytest.mark.parametrize("klass", [pd.Index, pd.TimedeltaIndex]) + @pytest.mark.parametrize("klass", [Index, pd.TimedeltaIndex]) def test_constructor_dtypes_timedelta(self, attr, klass): index = pd.timedelta_range("1 days", periods=5) index = index._with_freq(None) # wont be preserved by constructors @@ -706,8 +706,8 @@ def test_intersect_str_dates(self, sort): @pytest.mark.xfail(reason="Not implemented") def test_intersection_equal_sort_true(self): # TODO decide on True behaviour - idx = pd.Index(["c", "a", "b"]) - sorted_ = pd.Index(["a", "b", "c"]) + idx = Index(["c", "a", "b"]) + sorted_ = Index(["a", "b", "c"]) tm.assert_index_equal(idx.intersection(idx, sort=True), sorted_) def test_chained_union(self, sort): @@ -741,7 +741,7 @@ def test_union(self, index, sort): def test_union_sort_other_special(self, slice_): # https://github.com/pandas-dev/pandas/issues/24959 - idx = pd.Index([1, 0, 2]) + idx = Index([1, 0, 2]) # default, sort=None other = idx[slice_] tm.assert_index_equal(idx.union(other), idx) @@ -755,12 +755,12 @@ def test_union_sort_other_special(self, slice_): def test_union_sort_special_true(self, slice_): # TODO decide on True behaviour # sort=True - idx = pd.Index([1, 0, 2]) + idx = Index([1, 0, 2]) # default, sort=None other = idx[slice_] result = idx.union(other, sort=True) - expected = pd.Index([0, 1, 2]) + expected = Index([0, 1, 2]) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("klass", [np.array, Series, list]) @@ -1016,13 +1016,13 @@ def test_symmetric_difference(self, sort): @pytest.mark.parametrize("opname", ["difference", "symmetric_difference"]) def test_difference_incomparable(self, opname): - a = pd.Index([3, pd.Timestamp("2000"), 1]) - b = pd.Index([2, pd.Timestamp("1999"), 1]) + a = Index([3, pd.Timestamp("2000"), 1]) + b = Index([2, pd.Timestamp("1999"), 1]) op = operator.methodcaller(opname, b) # sort=None, the default result = op(a) - expected = pd.Index([3, pd.Timestamp("2000"), 2, pd.Timestamp("1999")]) + expected = Index([3, pd.Timestamp("2000"), 2, pd.Timestamp("1999")]) if opname == "difference": expected = expected[:2] tm.assert_index_equal(result, expected) @@ -1037,8 +1037,8 @@ def test_difference_incomparable(self, opname): def test_difference_incomparable_true(self, opname): # TODO decide on True behaviour # # sort=True, raises - a = pd.Index([3, pd.Timestamp("2000"), 1]) - b = pd.Index([2, pd.Timestamp("1999"), 1]) + a = Index([3, pd.Timestamp("2000"), 1]) + b = Index([2, pd.Timestamp("1999"), 1]) op = operator.methodcaller(opname, b, sort=True) with pytest.raises(TypeError, match="Cannot compare"): @@ -1337,13 +1337,13 @@ def test_get_indexer_nearest_decreasing(self, method, expected): ], ) def test_get_indexer_strings(self, method, expected): - index = pd.Index(["b", "c"]) + index = Index(["b", "c"]) actual = index.get_indexer(["a", "b", "c", "d"], method=method) tm.assert_numpy_array_equal(actual, expected) def test_get_indexer_strings_raises(self): - index = pd.Index(["b", "c"]) + index = Index(["b", "c"]) msg = r"unsupported operand type\(s\) for -: 'str' and 'str'" with pytest.raises(TypeError, match=msg): @@ -1375,7 +1375,7 @@ def test_get_indexer_with_NA_values( if unique_nulls_fixture is unique_nulls_fixture2: return # skip it, values are not unique arr = np.array([unique_nulls_fixture, unique_nulls_fixture2], dtype=object) - index = pd.Index(arr, dtype=object) + index = Index(arr, dtype=object) result = index.get_indexer( [unique_nulls_fixture, unique_nulls_fixture2, "Unknown"] ) @@ -1384,7 +1384,7 @@ def test_get_indexer_with_NA_values( @pytest.mark.parametrize("method", [None, "pad", "backfill", "nearest"]) def test_get_loc(self, method): - index = pd.Index([0, 1, 2]) + index = Index([0, 1, 2]) assert index.get_loc(1, method=method) == 1 if method: @@ -1392,7 +1392,7 @@ def test_get_loc(self, method): @pytest.mark.parametrize("method", [None, "pad", "backfill", "nearest"]) def test_get_loc_raises_bad_label(self, method): - index = pd.Index([0, 1, 2]) + index = Index([0, 1, 2]) if method: msg = "not supported between" else: @@ -1405,38 +1405,38 @@ def test_get_loc_raises_bad_label(self, method): "method,loc", [("pad", 1), ("backfill", 2), ("nearest", 1)] ) def test_get_loc_tolerance(self, method, loc): - index = pd.Index([0, 1, 2]) + index = Index([0, 1, 2]) assert index.get_loc(1.1, method) == loc assert index.get_loc(1.1, method, tolerance=1) == loc @pytest.mark.parametrize("method", ["pad", "backfill", "nearest"]) def test_get_loc_outside_tolerance_raises(self, method): - index = pd.Index([0, 1, 2]) + index = Index([0, 1, 2]) with pytest.raises(KeyError, match="1.1"): index.get_loc(1.1, method, tolerance=0.05) def test_get_loc_bad_tolerance_raises(self): - index = pd.Index([0, 1, 2]) + index = Index([0, 1, 2]) with pytest.raises(ValueError, match="must be numeric"): index.get_loc(1.1, "nearest", tolerance="invalid") def test_get_loc_tolerance_no_method_raises(self): - index = pd.Index([0, 1, 2]) + index = Index([0, 1, 2]) with pytest.raises(ValueError, match="tolerance .* valid if"): index.get_loc(1.1, tolerance=1) def test_get_loc_raises_missized_tolerance(self): - index = pd.Index([0, 1, 2]) + index = Index([0, 1, 2]) with pytest.raises(ValueError, match="tolerance size must match"): index.get_loc(1.1, "nearest", tolerance=[1, 1]) def test_get_loc_raises_object_nearest(self): - index = pd.Index(["a", "c"]) + index = Index(["a", "c"]) with pytest.raises(TypeError, match="unsupported operand type"): index.get_loc("a", method="nearest") def test_get_loc_raises_object_tolerance(self): - index = pd.Index(["a", "c"]) + index = Index(["a", "c"]) with pytest.raises(TypeError, match="unsupported operand type"): index.get_loc("a", method="pad", tolerance="invalid") @@ -1535,7 +1535,7 @@ def test_slice_locs_negative_step(self, in_slice, expected): s_start, s_stop = index.slice_locs(in_slice.start, in_slice.stop, in_slice.step) result = index[s_start : s_stop : in_slice.step] - expected = pd.Index(list(expected)) + expected = Index(list(expected)) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("index", ["string", "int", "float"], indirect=True) @@ -1600,8 +1600,8 @@ def test_drop_by_numeric_label_errors_ignore(self, key, expected): @pytest.mark.parametrize("to_drop", [[("c", "d"), "a"], ["a", ("c", "d")]]) def test_drop_tuple(self, values, to_drop): # GH 18304 - index = pd.Index(values) - expected = pd.Index(["b"]) + index = Index(values) + expected = Index(["b"]) result = index.drop(to_drop) tm.assert_index_equal(result, expected) @@ -1916,8 +1916,8 @@ def test_tab_completion(self, index, expected): def test_indexing_doesnt_change_class(self): index = Index([1, 2, 3, "a", "b", "c"]) - assert index[1:3].identical(pd.Index([2, 3], dtype=np.object_)) - assert index[[0, 1]].identical(pd.Index([1, 2], dtype=np.object_)) + assert index[1:3].identical(Index([2, 3], dtype=np.object_)) + assert index[[0, 1]].identical(Index([1, 2], dtype=np.object_)) def test_outer_join_sort(self): left_index = Index(np.random.permutation(15)) @@ -1941,23 +1941,23 @@ def test_nan_first_take_datetime(self): def test_take_fill_value(self): # GH 12631 - index = pd.Index(list("ABC"), name="xxx") + index = Index(list("ABC"), name="xxx") result = index.take(np.array([1, 0, -1])) - expected = pd.Index(list("BAC"), name="xxx") + expected = Index(list("BAC"), name="xxx") tm.assert_index_equal(result, expected) # fill_value result = index.take(np.array([1, 0, -1]), fill_value=True) - expected = pd.Index(["B", "A", np.nan], name="xxx") + expected = Index(["B", "A", np.nan], name="xxx") tm.assert_index_equal(result, expected) # allow_fill=False result = index.take(np.array([1, 0, -1]), allow_fill=False, fill_value=True) - expected = pd.Index(["B", "A", "C"], name="xxx") + expected = Index(["B", "A", "C"], name="xxx") tm.assert_index_equal(result, expected) def test_take_fill_value_none_raises(self): - index = pd.Index(list("ABC"), name="xxx") + index = Index(list("ABC"), name="xxx") msg = ( "When allow_fill=True and fill_value is not None, " "all indices must be >= -1" @@ -1969,7 +1969,7 @@ def test_take_fill_value_none_raises(self): index.take(np.array([1, 0, -5]), fill_value=True) def test_take_bad_bounds_raises(self): - index = pd.Index(list("ABC"), name="xxx") + index = Index(list("ABC"), name="xxx") with pytest.raises(IndexError, match="out of bounds"): index.take(np.array([1, -5])) @@ -1990,14 +1990,14 @@ def test_take_bad_bounds_raises(self): ) def test_reindex_preserves_name_if_target_is_list_or_ndarray(self, name, labels): # GH6552 - index = pd.Index([0, 1, 2]) + index = Index([0, 1, 2]) index.name = name assert index.reindex(labels)[0].name == name @pytest.mark.parametrize("labels", [[], np.array([]), np.array([], dtype=np.int64)]) def test_reindex_preserves_type_if_target_is_empty_list_or_array(self, labels): # GH7774 - index = pd.Index(list("abc")) + index = Index(list("abc")) assert index.reindex(labels)[0].dtype.type == np.object_ @pytest.mark.parametrize( @@ -2010,11 +2010,11 @@ def test_reindex_preserves_type_if_target_is_empty_list_or_array(self, labels): ) def test_reindex_doesnt_preserve_type_if_target_is_empty_index(self, labels, dtype): # GH7774 - index = pd.Index(list("abc")) + index = Index(list("abc")) assert index.reindex(labels)[0].dtype.type == dtype def test_reindex_no_type_preserve_target_empty_mi(self): - index = pd.Index(list("abc")) + index = Index(list("abc")) result = index.reindex( pd.MultiIndex([pd.Int64Index([]), pd.Float64Index([])], [[], []]) )[0] @@ -2024,7 +2024,7 @@ def test_reindex_no_type_preserve_target_empty_mi(self): def test_groupby(self): index = Index(range(5)) result = index.groupby(np.array([1, 1, 2, 2, 2])) - expected = {1: pd.Index([0, 1]), 2: pd.Index([2, 3, 4])} + expected = {1: Index([0, 1]), 2: Index([2, 3, 4])} tm.assert_dict_equal(result, expected) @@ -2074,7 +2074,7 @@ def test_equals_op_index_vs_mi_same_length(self): @pytest.mark.parametrize("dt_conv", [pd.to_datetime, pd.to_timedelta]) def test_dt_conversion_preserves_name(self, dt_conv): # GH 10875 - index = pd.Index(["01:02:03", "01:02:04"], name="label") + index = Index(["01:02:03", "01:02:04"], name="label") assert index.name == dt_conv(index).name @pytest.mark.parametrize( @@ -2083,12 +2083,12 @@ def test_dt_conversion_preserves_name(self, dt_conv): # ASCII # short ( - pd.Index(["a", "bb", "ccc"]), + Index(["a", "bb", "ccc"]), """Index(['a', 'bb', 'ccc'], dtype='object')""", ), # multiple lines ( - pd.Index(["a", "bb", "ccc"] * 10), + Index(["a", "bb", "ccc"] * 10), """\ Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', @@ -2097,7 +2097,7 @@ def test_dt_conversion_preserves_name(self, dt_conv): ), # truncated ( - pd.Index(["a", "bb", "ccc"] * 100), + Index(["a", "bb", "ccc"] * 100), """\ Index(['a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', 'bb', 'ccc', 'a', ... @@ -2107,12 +2107,12 @@ def test_dt_conversion_preserves_name(self, dt_conv): # Non-ASCII # short ( - pd.Index(["あ", "いい", "ううう"]), + Index(["あ", "いい", "ううう"]), """Index(['あ', 'いい', 'ううう'], dtype='object')""", ), # multiple lines ( - pd.Index(["あ", "いい", "ううう"] * 10), + Index(["あ", "いい", "ううう"] * 10), ( "Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', " "'あ', 'いい', 'ううう', 'あ', 'いい', 'ううう',\n" @@ -2125,7 +2125,7 @@ def test_dt_conversion_preserves_name(self, dt_conv): ), # truncated ( - pd.Index(["あ", "いい", "ううう"] * 100), + Index(["あ", "いい", "ううう"] * 100), ( "Index(['あ', 'いい', 'ううう', 'あ', 'いい', 'ううう', " "'あ', 'いい', 'ううう', 'あ',\n" @@ -2146,12 +2146,12 @@ def test_string_index_repr(self, index, expected): [ # short ( - pd.Index(["あ", "いい", "ううう"]), + Index(["あ", "いい", "ううう"]), ("Index(['あ', 'いい', 'ううう'], dtype='object')"), ), # multiple lines ( - pd.Index(["あ", "いい", "ううう"] * 10), + Index(["あ", "いい", "ううう"] * 10), ( "Index(['あ', 'いい', 'ううう', 'あ', 'いい', " "'ううう', 'あ', 'いい', 'ううう',\n" @@ -2166,7 +2166,7 @@ def test_string_index_repr(self, index, expected): ), # truncated ( - pd.Index(["あ", "いい", "ううう"] * 100), + Index(["あ", "いい", "ううう"] * 100), ( "Index(['あ', 'いい', 'ううう', 'あ', 'いい', " "'ううう', 'あ', 'いい', 'ううう',\n" @@ -2187,7 +2187,7 @@ def test_string_index_repr_with_unicode_option(self, index, expected): assert result == expected def test_cached_properties_not_settable(self): - index = pd.Index([1, 2, 3]) + index = Index([1, 2, 3]) with pytest.raises(AttributeError, match="Can't set attribute"): index.is_unique = False @@ -2197,7 +2197,7 @@ async def test_tab_complete_warning(self, ip): pytest.importorskip("IPython", minversion="6.0.0") from IPython.core.completer import provisionalcompleter - code = "import pandas as pd; idx = pd.Index([1, 2])" + code = "import pandas as pd; idx = Index([1, 2])" await ip.run_code(code) # GH 31324 newer jedi version raises Deprecation warning @@ -2223,7 +2223,7 @@ def test_contains_method_removed(self, index): index.contains(1) def test_sortlevel(self): - index = pd.Index([5, 4, 3, 2, 1]) + index = Index([5, 4, 3, 2, 1]) with pytest.raises(Exception, match="ascending must be a single bool value or"): index.sortlevel(ascending="True") @@ -2235,15 +2235,15 @@ def test_sortlevel(self): with pytest.raises(Exception, match="ascending must be a bool value"): index.sortlevel(ascending=["True"]) - expected = pd.Index([1, 2, 3, 4, 5]) + expected = Index([1, 2, 3, 4, 5]) result = index.sortlevel(ascending=[True]) tm.assert_index_equal(result[0], expected) - expected = pd.Index([1, 2, 3, 4, 5]) + expected = Index([1, 2, 3, 4, 5]) result = index.sortlevel(ascending=True) tm.assert_index_equal(result[0], expected) - expected = pd.Index([5, 4, 3, 2, 1]) + expected = Index([5, 4, 3, 2, 1]) result = index.sortlevel(ascending=False) tm.assert_index_equal(result[0], expected) @@ -2296,7 +2296,7 @@ def test_copy_name(self): def test_copy_name2(self): # Check that adding a "name" parameter to the copy is honored # GH14302 - index = pd.Index([1, 2], name="MyName") + index = Index([1, 2], name="MyName") index1 = index.copy() tm.assert_index_equal(index, index1) @@ -2314,8 +2314,8 @@ def test_copy_name2(self): assert index3.names == ["NewName"] def test_unique_na(self): - idx = pd.Index([2, np.nan, 2, 1], name="my_index") - expected = pd.Index([2, np.nan, 1], name="my_index") + idx = Index([2, np.nan, 2, 1], name="my_index") + expected = Index([2, np.nan, 1], name="my_index") result = idx.unique() tm.assert_index_equal(result, expected) @@ -2338,9 +2338,9 @@ def test_logical_compat(self): ) def test_dropna(self, how, dtype, vals, expected): # GH 6194 - index = pd.Index(vals, dtype=dtype) + index = Index(vals, dtype=dtype) result = index.dropna(how=how) - expected = pd.Index(expected, dtype=dtype) + expected = Index(expected, dtype=dtype) tm.assert_index_equal(result, expected) @pytest.mark.parametrize("how", ["any", "all"]) @@ -2380,7 +2380,7 @@ def test_dropna_dt_like(self, how, index, expected): def test_dropna_invalid_how_raises(self): msg = "invalid how option: xxx" with pytest.raises(ValueError, match=msg): - pd.Index([1, 2, 3]).dropna(how="xxx") + Index([1, 2, 3]).dropna(how="xxx") def test_get_combined_index(self): result = _get_combined_index([]) @@ -2390,10 +2390,10 @@ def test_get_combined_index(self): @pytest.mark.parametrize( "index", [ - pd.Index([np.nan]), - pd.Index([np.nan, 1]), - pd.Index([1, 2, np.nan]), - pd.Index(["a", "b", np.nan]), + Index([np.nan]), + Index([np.nan, 1]), + Index([1, 2, np.nan]), + Index(["a", "b", np.nan]), pd.to_datetime(["NaT"]), pd.to_datetime(["NaT", "2000-01-01"]), pd.to_datetime(["2000-01-01", "NaT", "2000-01-02"]), @@ -2408,7 +2408,7 @@ def test_is_monotonic_na(self, index): def test_repr_summary(self): with cf.option_context("display.max_seq_items", 10): - result = repr(pd.Index(np.arange(1000))) + result = repr(Index(np.arange(1000))) assert len(result) < 200 assert "..." in result @@ -2519,7 +2519,7 @@ def test_ensure_index_mixed_closed_intervals(self): ) def test_generated_op_names(opname, index): if isinstance(index, ABCIndex) and opname == "rsub": - # pd.Index.__rsub__ does not exist; though the method does exist + # Index.__rsub__ does not exist; though the method does exist # for subclasses. see GH#19723 return opname = f"__{opname}__" @@ -2537,7 +2537,7 @@ def test_index_subclass_constructor_wrong_kwargs(index_maker): def test_deprecated_fastpath(): msg = "[Uu]nexpected keyword argument" with pytest.raises(TypeError, match=msg): - pd.Index(np.array(["a", "b"], dtype=object), name="test", fastpath=True) + Index(np.array(["a", "b"], dtype=object), name="test", fastpath=True) with pytest.raises(TypeError, match=msg): pd.Int64Index(np.array([1, 2, 3], dtype="int64"), name="test", fastpath=True) @@ -2555,7 +2555,7 @@ def test_shape_of_invalid_index(): # about this). However, as long as this is not solved in general,this test ensures # that the returned shape is consistent with this underlying array for # compat with matplotlib (see https://github.com/pandas-dev/pandas/issues/27775) - idx = pd.Index([0, 1, 2, 3]) + idx = Index([0, 1, 2, 3]) with tm.assert_produces_warning(FutureWarning): # GH#30588 multi-dimensional indexing deprecated assert idx[:, None].shape == (4, 1) @@ -2567,7 +2567,7 @@ def test_validate_1d_input(): arr = np.arange(8).reshape(2, 2, 2) with pytest.raises(ValueError, match=msg): - pd.Index(arr) + Index(arr) with pytest.raises(ValueError, match=msg): pd.Float64Index(arr.astype(np.float64)) @@ -2580,7 +2580,7 @@ def test_validate_1d_input(): df = pd.DataFrame(arr.reshape(4, 2)) with pytest.raises(ValueError, match=msg): - pd.Index(df) + Index(df) # GH#13601 trying to assign a multi-dimensional array to an index is not # allowed @@ -2622,7 +2622,7 @@ def construct(dtype): if dtype is dtlike_dtypes[-1]: # PeriodArray will try to cast ints to strings return pd.DatetimeIndex(vals).astype(dtype) - return pd.Index(vals, dtype=dtype) + return Index(vals, dtype=dtype) left = construct(ldtype) right = construct(rdtype) diff --git a/pandas/tests/indexes/test_numeric.py b/pandas/tests/indexes/test_numeric.py index 7fa7a571d2571..045816b3c9513 100644 --- a/pandas/tests/indexes/test_numeric.py +++ b/pandas/tests/indexes/test_numeric.py @@ -521,7 +521,7 @@ def test_constructor_coercion_signed_to_unsigned(self, uint_dtype): Index([-1], dtype=uint_dtype) def test_constructor_unwraps_index(self): - idx = pd.Index([1, 2]) + idx = Index([1, 2]) result = pd.Int64Index(idx) expected = np.array([1, 2], dtype="int64") tm.assert_numpy_array_equal(result._data, expected) @@ -613,7 +613,7 @@ def test_intersection(self, index_large): def test_int_float_union_dtype(dtype): # https://github.com/pandas-dev/pandas/issues/26778 # [u]int | float -> float - index = pd.Index([0, 2, 3], dtype=dtype) + index = Index([0, 2, 3], dtype=dtype) other = pd.Float64Index([0.5, 1.5]) expected = pd.Float64Index([0.0, 0.5, 1.5, 2.0, 3.0]) result = index.union(other) @@ -637,7 +637,7 @@ def test_range_float_union_dtype(): @pytest.mark.parametrize( "box", - [list, lambda x: np.array(x, dtype=object), lambda x: pd.Index(x, dtype=object)], + [list, lambda x: np.array(x, dtype=object), lambda x: Index(x, dtype=object)], ) def test_uint_index_does_not_convert_to_float64(box): # https://github.com/pandas-dev/pandas/issues/28279 @@ -667,8 +667,8 @@ def test_uint_index_does_not_convert_to_float64(box): def test_float64_index_equals(): # https://github.com/pandas-dev/pandas/issues/35217 - float_index = pd.Index([1.0, 2, 3]) - string_index = pd.Index(["1", "2", "3"]) + float_index = Index([1.0, 2, 3]) + string_index = Index(["1", "2", "3"]) result = float_index.equals(string_index) assert result is False @@ -679,8 +679,8 @@ def test_float64_index_equals(): def test_float64_index_difference(): # https://github.com/pandas-dev/pandas/issues/35217 - float_index = pd.Index([1.0, 2, 3]) - string_index = pd.Index(["1", "2", "3"]) + float_index = Index([1.0, 2, 3]) + string_index = Index(["1", "2", "3"]) result = float_index.difference(string_index) tm.assert_index_equal(result, float_index) diff --git a/pandas/tests/indexes/timedeltas/test_astype.py b/pandas/tests/indexes/timedeltas/test_astype.py index d9f24b4a35520..d274aa0b06584 100644 --- a/pandas/tests/indexes/timedeltas/test_astype.py +++ b/pandas/tests/indexes/timedeltas/test_astype.py @@ -117,7 +117,7 @@ def test_astype_category(self): def test_astype_array_fallback(self): obj = pd.timedelta_range("1H", periods=2) result = obj.astype(bool) - expected = pd.Index(np.array([True, True])) + expected = Index(np.array([True, True])) tm.assert_index_equal(result, expected) result = obj._data.astype(bool) diff --git a/pandas/tests/indexing/multiindex/test_multiindex.py b/pandas/tests/indexing/multiindex/test_multiindex.py index 2e97dec789c5b..ed1348efb5cba 100644 --- a/pandas/tests/indexing/multiindex/test_multiindex.py +++ b/pandas/tests/indexing/multiindex/test_multiindex.py @@ -70,7 +70,7 @@ def test_nested_tuples_duplicates(self): # GH#30892 dti = pd.to_datetime(["20190101", "20190101", "20190102"]) - idx = pd.Index(["a", "a", "c"]) + idx = Index(["a", "a", "c"]) mi = pd.MultiIndex.from_arrays([dti, idx], names=["index1", "index2"]) df = DataFrame({"c1": [1, 2, 3], "c2": [np.nan, np.nan, np.nan]}, index=mi) diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 6a83c69785c90..df76f3c64947a 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -613,7 +613,7 @@ def test_reindex_items(self): reindexed = mgr.reindex_axis(["g", "c", "a", "d"], axis=0) assert reindexed.nblocks == 2 - tm.assert_index_equal(reindexed.items, pd.Index(["g", "c", "a", "d"])) + tm.assert_index_equal(reindexed.items, Index(["g", "c", "a", "d"])) tm.assert_almost_equal( mgr.iget(6).internal_values(), reindexed.iget(0).internal_values() ) @@ -636,9 +636,7 @@ def test_get_numeric_data(self): mgr.iset(5, np.array([1, 2, 3], dtype=np.object_)) numeric = mgr.get_numeric_data() - tm.assert_index_equal( - numeric.items, pd.Index(["int", "float", "complex", "bool"]) - ) + tm.assert_index_equal(numeric.items, Index(["int", "float", "complex", "bool"])) tm.assert_almost_equal( mgr.iget(mgr.items.get_loc("float")).internal_values(), numeric.iget(numeric.items.get_loc("float")).internal_values(), @@ -652,9 +650,7 @@ def test_get_numeric_data(self): ) numeric2 = mgr.get_numeric_data(copy=True) - tm.assert_index_equal( - numeric.items, pd.Index(["int", "float", "complex", "bool"]) - ) + tm.assert_index_equal(numeric.items, Index(["int", "float", "complex", "bool"])) numeric2.iset( numeric2.items.get_loc("float"), np.array([1000.0, 2000.0, 3000.0]) ) @@ -672,7 +668,7 @@ def test_get_bool_data(self): mgr.iset(6, np.array([True, False, True], dtype=np.object_)) bools = mgr.get_bool_data() - tm.assert_index_equal(bools.items, pd.Index(["bool"])) + tm.assert_index_equal(bools.items, Index(["bool"])) tm.assert_almost_equal( mgr.iget(mgr.items.get_loc("bool")).internal_values(), bools.iget(bools.items.get_loc("bool")).internal_values(), @@ -840,14 +836,12 @@ def assert_reindex_axis_is_ok(mgr, axis, new_labels, fill_value): tm.assert_index_equal(reindexed.axes[axis], new_labels) for ax in range(mgr.ndim): - assert_reindex_axis_is_ok(mgr, ax, pd.Index([]), fill_value) + assert_reindex_axis_is_ok(mgr, ax, Index([]), fill_value) assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax], fill_value) assert_reindex_axis_is_ok(mgr, ax, mgr.axes[ax][[0, 0, 0]], fill_value) + assert_reindex_axis_is_ok(mgr, ax, Index(["foo", "bar", "baz"]), fill_value) assert_reindex_axis_is_ok( - mgr, ax, pd.Index(["foo", "bar", "baz"]), fill_value - ) - assert_reindex_axis_is_ok( - mgr, ax, pd.Index(["foo", mgr.axes[ax][0], "baz"]), fill_value + mgr, ax, Index(["foo", mgr.axes[ax][0], "baz"]), fill_value ) if mgr.shape[ax] >= 3: @@ -872,14 +866,14 @@ def assert_reindex_indexer_is_ok(mgr, axis, new_labels, indexer, fill_value): tm.assert_index_equal(reindexed.axes[axis], new_labels) for ax in range(mgr.ndim): - assert_reindex_indexer_is_ok(mgr, ax, pd.Index([]), [], fill_value) + assert_reindex_indexer_is_ok(mgr, ax, Index([]), [], fill_value) assert_reindex_indexer_is_ok( mgr, ax, mgr.axes[ax], np.arange(mgr.shape[ax]), fill_value ) assert_reindex_indexer_is_ok( mgr, ax, - pd.Index(["foo"] * mgr.shape[ax]), + Index(["foo"] * mgr.shape[ax]), np.arange(mgr.shape[ax]), fill_value, ) @@ -890,22 +884,22 @@ def assert_reindex_indexer_is_ok(mgr, axis, new_labels, indexer, fill_value): mgr, ax, mgr.axes[ax], np.arange(mgr.shape[ax])[::-1], fill_value ) assert_reindex_indexer_is_ok( - mgr, ax, pd.Index(["foo", "bar", "baz"]), [0, 0, 0], fill_value + mgr, ax, Index(["foo", "bar", "baz"]), [0, 0, 0], fill_value ) assert_reindex_indexer_is_ok( - mgr, ax, pd.Index(["foo", "bar", "baz"]), [-1, 0, -1], fill_value + mgr, ax, Index(["foo", "bar", "baz"]), [-1, 0, -1], fill_value ) assert_reindex_indexer_is_ok( mgr, ax, - pd.Index(["foo", mgr.axes[ax][0], "baz"]), + Index(["foo", mgr.axes[ax][0], "baz"]), [-1, -1, -1], fill_value, ) if mgr.shape[ax] >= 3: assert_reindex_indexer_is_ok( - mgr, ax, pd.Index(["foo", "bar", "baz"]), [0, 1, 2], fill_value + mgr, ax, Index(["foo", "bar", "baz"]), [0, 1, 2], fill_value ) @@ -1215,7 +1209,7 @@ def test_validate_ndim(): def test_block_shape(): - idx = pd.Index([0, 1, 2, 3, 4]) + idx = Index([0, 1, 2, 3, 4]) a = Series([1, 2, 3]).reindex(idx) b = Series(pd.Categorical([1, 2, 3])).reindex(idx) diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index 9f3299bcb5e38..c474e67123ef7 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -1167,7 +1167,7 @@ def test_excel_high_surrogate(self, engine): @pytest.mark.parametrize("filename", ["df_empty.xlsx", "df_equals.xlsx"]) def test_header_with_index_col(self, engine, filename): # GH 33476 - idx = pd.Index(["Z"], name="I2") + idx = Index(["Z"], name="I2") cols = pd.MultiIndex.from_tuples( [("A", "B"), ("A", "B.1")], names=["I11", "I12"] ) diff --git a/pandas/tests/io/formats/test_format.py b/pandas/tests/io/formats/test_format.py index c57139e50561d..72b28c71b6511 100644 --- a/pandas/tests/io/formats/test_format.py +++ b/pandas/tests/io/formats/test_format.py @@ -643,7 +643,7 @@ def test_east_asian_unicode_false(self): # index name df = DataFrame( {"a": ["あああああ", "い", "う", "えええ"], "b": ["あ", "いいい", "う", "ええええええ"]}, - index=pd.Index(["あ", "い", "うう", "え"], name="おおおお"), + index=Index(["あ", "い", "うう", "え"], name="おおおお"), ) expected = ( " a b\n" @@ -658,7 +658,7 @@ def test_east_asian_unicode_false(self): # all df = DataFrame( {"あああ": ["あああ", "い", "う", "えええええ"], "いいいいい": ["あ", "いいい", "う", "ええ"]}, - index=pd.Index(["あ", "いいい", "うう", "え"], name="お"), + index=Index(["あ", "いいい", "うう", "え"], name="お"), ) expected = ( " あああ いいいいい\n" @@ -787,7 +787,7 @@ def test_east_asian_unicode_true(self): # index name df = DataFrame( {"a": ["あああああ", "い", "う", "えええ"], "b": ["あ", "いいい", "う", "ええええええ"]}, - index=pd.Index(["あ", "い", "うう", "え"], name="おおおお"), + index=Index(["あ", "い", "うう", "え"], name="おおおお"), ) expected = ( " a b\n" @@ -802,7 +802,7 @@ def test_east_asian_unicode_true(self): # all df = DataFrame( {"あああ": ["あああ", "い", "う", "えええええ"], "いいいいい": ["あ", "いいい", "う", "ええ"]}, - index=pd.Index(["あ", "いいい", "うう", "え"], name="お"), + index=Index(["あ", "いいい", "うう", "え"], name="お"), ) expected = ( " あああ いいいいい\n" diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index ba2805f2f063f..2437ba77532fa 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -1509,7 +1509,7 @@ def test_to_hdf_with_min_itemsize(self, setup_path): def test_to_hdf_errors(self, format, setup_path): data = ["\ud800foo"] - ser = Series(data, index=pd.Index(data)) + ser = Series(data, index=Index(data)) with ensure_clean_path(setup_path) as path: # GH 20835 ser.to_hdf(path, "table", format=format, errors="surrogatepass") @@ -2533,11 +2533,11 @@ def test_store_index_name(self, setup_path): @pytest.mark.parametrize("table_format", ["table", "fixed"]) def test_store_index_name_numpy_str(self, table_format, setup_path): # GH #13492 - idx = pd.Index( + idx = Index( pd.to_datetime([datetime.date(2000, 1, 1), datetime.date(2000, 1, 2)]), name="cols\u05d2", ) - idx1 = pd.Index( + idx1 = Index( pd.to_datetime([datetime.date(2010, 1, 1), datetime.date(2010, 1, 2)]), name="rows\u05d0", ) @@ -4139,7 +4139,7 @@ def test_legacy_table_fixed_format_read_py2(self, datapath, setup_path): expected = DataFrame( [[1, 2, 3, "D"]], columns=["A", "B", "C", "D"], - index=pd.Index(["ABC"], name="INDEX_NAME"), + index=Index(["ABC"], name="INDEX_NAME"), ) tm.assert_frame_equal(expected, result) @@ -4154,7 +4154,7 @@ def test_legacy_table_fixed_format_read_datetime_py2(self, datapath, setup_path) expected = DataFrame( [[pd.Timestamp("2020-02-06T18:00")]], columns=["A"], - index=pd.Index(["date"]), + index=Index(["date"]), ) tm.assert_frame_equal(expected, result) diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index d462917277f99..c1efbb8536d68 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -505,7 +505,7 @@ def test_join_sort(self): # smoke test joined = left.join(right, on="key", sort=False) - tm.assert_index_equal(joined.index, pd.Index(list(range(4)))) + tm.assert_index_equal(joined.index, Index(list(range(4)))) def test_join_mixed_non_unique_index(self): # GH 12814, unorderable types in py3 with a non-unique index @@ -791,15 +791,15 @@ def _join_by_hand(a, b, how="left"): def test_join_inner_multiindex_deterministic_order(): # GH: 36910 - left = pd.DataFrame( + left = DataFrame( data={"e": 5}, index=pd.MultiIndex.from_tuples([(1, 2, 4)], names=("a", "b", "d")), ) - right = pd.DataFrame( + right = DataFrame( data={"f": 6}, index=pd.MultiIndex.from_tuples([(2, 3)], names=("b", "c")) ) result = left.join(right, how="inner") - expected = pd.DataFrame( + expected = DataFrame( {"e": [5], "f": [6]}, index=pd.MultiIndex.from_tuples([(2, 1, 4, 3)], names=("b", "a", "d", "c")), ) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index da7435b9609b2..33048c0e0e2df 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -86,7 +86,7 @@ def _check_expected_dtype(self, obj, label): Check whether obj has expected dtype depending on label considering not-supported dtypes """ - if isinstance(obj, pd.Index): + if isinstance(obj, Index): if label == "bool": assert obj.dtype == "object" else: @@ -102,7 +102,7 @@ def _check_expected_dtype(self, obj, label): def test_dtypes(self): # to confirm test case covers intended dtypes for typ, vals in self.data.items(): - self._check_expected_dtype(pd.Index(vals), typ) + self._check_expected_dtype(Index(vals), typ) self._check_expected_dtype(Series(vals), typ) def test_concatlike_same_dtypes(self): @@ -122,35 +122,35 @@ def test_concatlike_same_dtypes(self): # ----- Index ----- # # index.append - res = pd.Index(vals1).append(pd.Index(vals2)) - exp = pd.Index(exp_data) + res = Index(vals1).append(Index(vals2)) + exp = Index(exp_data) tm.assert_index_equal(res, exp) # 3 elements - res = pd.Index(vals1).append([pd.Index(vals2), pd.Index(vals3)]) - exp = pd.Index(exp_data3) + res = Index(vals1).append([Index(vals2), Index(vals3)]) + exp = Index(exp_data3) tm.assert_index_equal(res, exp) # index.append name mismatch - i1 = pd.Index(vals1, name="x") - i2 = pd.Index(vals2, name="y") + i1 = Index(vals1, name="x") + i2 = Index(vals2, name="y") res = i1.append(i2) - exp = pd.Index(exp_data) + exp = Index(exp_data) tm.assert_index_equal(res, exp) # index.append name match - i1 = pd.Index(vals1, name="x") - i2 = pd.Index(vals2, name="x") + i1 = Index(vals1, name="x") + i2 = Index(vals2, name="x") res = i1.append(i2) - exp = pd.Index(exp_data, name="x") + exp = Index(exp_data, name="x") tm.assert_index_equal(res, exp) # cannot append non-index with pytest.raises(TypeError, match="all inputs must be Index"): - pd.Index(vals1).append(vals2) + Index(vals1).append(vals2) with pytest.raises(TypeError, match="all inputs must be Index"): - pd.Index(vals1).append([pd.Index(vals2), vals3]) + Index(vals1).append([Index(vals2), vals3]) # ----- Series ----- # @@ -253,13 +253,13 @@ def test_concatlike_dtypes_coercion(self): # ----- Index ----- # # index.append - res = pd.Index(vals1).append(pd.Index(vals2)) - exp = pd.Index(exp_data, dtype=exp_index_dtype) + res = Index(vals1).append(Index(vals2)) + exp = Index(exp_data, dtype=exp_index_dtype) tm.assert_index_equal(res, exp) # 3 elements - res = pd.Index(vals1).append([pd.Index(vals2), pd.Index(vals3)]) - exp = pd.Index(exp_data3, dtype=exp_index_dtype) + res = Index(vals1).append([Index(vals2), Index(vals3)]) + exp = Index(exp_data3, dtype=exp_index_dtype) tm.assert_index_equal(res, exp) # ----- Series ----- # @@ -292,7 +292,7 @@ def test_concatlike_common_coerce_to_pandas_object(self): dti = pd.DatetimeIndex(["2011-01-01", "2011-01-02"]) tdi = pd.TimedeltaIndex(["1 days", "2 days"]) - exp = pd.Index( + exp = Index( [ pd.Timestamp("2011-01-01"), pd.Timestamp("2011-01-02"), @@ -364,7 +364,7 @@ def test_concatlike_datetimetz_to_object(self, tz_aware_fixture): dti1 = pd.DatetimeIndex(["2011-01-01", "2011-01-02"], tz=tz) dti2 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"]) - exp = pd.Index( + exp = Index( [ pd.Timestamp("2011-01-01", tz=tz), pd.Timestamp("2011-01-02", tz=tz), @@ -388,7 +388,7 @@ def test_concatlike_datetimetz_to_object(self, tz_aware_fixture): # different tz dti3 = pd.DatetimeIndex(["2012-01-01", "2012-01-02"], tz="US/Pacific") - exp = pd.Index( + exp = Index( [ pd.Timestamp("2011-01-01", tz=tz), pd.Timestamp("2011-01-02", tz=tz), @@ -432,7 +432,7 @@ def test_concatlike_common_period_diff_freq_to_object(self): pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M") pi2 = pd.PeriodIndex(["2012-01-01", "2012-02-01"], freq="D") - exp = pd.Index( + exp = Index( [ pd.Period("2011-01", freq="M"), pd.Period("2011-02", freq="M"), @@ -458,7 +458,7 @@ def test_concatlike_common_period_mixed_dt_to_object(self): # different datetimelike pi1 = pd.PeriodIndex(["2011-01", "2011-02"], freq="M") tdi = pd.TimedeltaIndex(["1 days", "2 days"]) - exp = pd.Index( + exp = Index( [ pd.Period("2011-01", freq="M"), pd.Period("2011-02", freq="M"), @@ -480,7 +480,7 @@ def test_concatlike_common_period_mixed_dt_to_object(self): tm.assert_series_equal(res, Series(exp, index=[0, 1, 0, 1])) # inverse - exp = pd.Index( + exp = Index( [ pd.Timedelta("1 days"), pd.Timedelta("2 days"), @@ -911,9 +911,9 @@ def test_append_preserve_index_name(self): indexes_can_append = [ pd.RangeIndex(3), - pd.Index([4, 5, 6]), - pd.Index([4.5, 5.5, 6.5]), - pd.Index(list("abc")), + Index([4, 5, 6]), + Index([4.5, 5.5, 6.5]), + Index(list("abc")), pd.CategoricalIndex("A B C".split()), pd.CategoricalIndex("D E F".split(), ordered=True), pd.IntervalIndex.from_breaks([7, 8, 9, 10]), @@ -1309,16 +1309,16 @@ def test_concat_ignore_index(self, sort): def test_concat_same_index_names(self, name_in1, name_in2, name_in3, name_out): # GH13475 indices = [ - pd.Index(["a", "b", "c"], name=name_in1), - pd.Index(["b", "c", "d"], name=name_in2), - pd.Index(["c", "d", "e"], name=name_in3), + Index(["a", "b", "c"], name=name_in1), + Index(["b", "c", "d"], name=name_in2), + Index(["c", "d", "e"], name=name_in3), ] frames = [ DataFrame({c: [0, 1, 2]}, index=i) for i, c in zip(indices, ["x", "y", "z"]) ] result = pd.concat(frames, axis=1) - exp_ind = pd.Index(["a", "b", "c", "d", "e"], name=name_out) + exp_ind = Index(["a", "b", "c", "d", "e"], name=name_out) expected = DataFrame( { "x": [0, 1, 2, np.nan, np.nan], @@ -1759,7 +1759,7 @@ def test_concat_series_axis1_names_applied(self): s2 = Series([4, 5, 6]) result = concat([s, s2], axis=1, keys=["a", "b"], names=["A"]) expected = DataFrame( - [[1, 4], [2, 5], [3, 6]], columns=pd.Index(["a", "b"], name="A") + [[1, 4], [2, 5], [3, 6]], columns=Index(["a", "b"], name="A") ) tm.assert_frame_equal(result, expected) @@ -2223,7 +2223,7 @@ def test_concat_empty_series(self): res = pd.concat([s1, s2], axis=1) exp = DataFrame( {"x": [1, 2, 3], "y": [np.nan, np.nan, np.nan]}, - index=pd.Index([0, 1, 2], dtype="O"), + index=Index([0, 1, 2], dtype="O"), ) tm.assert_frame_equal(res, exp) @@ -2241,7 +2241,7 @@ def test_concat_empty_series(self): exp = DataFrame( {"x": [1, 2, 3], 0: [np.nan, np.nan, np.nan]}, columns=["x", 0], - index=pd.Index([0, 1, 2], dtype="O"), + index=Index([0, 1, 2], dtype="O"), ) tm.assert_frame_equal(res, exp) diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 603f81f6fc6d4..92128def4540a 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -243,7 +243,7 @@ def test_pivot_with_non_observable_dropna(self, dropna): result = df.pivot_table(index="A", values="B", dropna=dropna) expected = DataFrame( {"B": [2, 3]}, - index=pd.Index( + index=Index( pd.Categorical.from_codes( [0, 1], categories=["low", "high"], ordered=True ), @@ -268,7 +268,7 @@ def test_pivot_with_non_observable_dropna(self, dropna): result = df.pivot_table(index="A", values="B", dropna=dropna) expected = DataFrame( {"B": [2, 3, 0]}, - index=pd.Index( + index=Index( pd.Categorical.from_codes( [0, 1, 2], categories=["low", "high", "left"], ordered=True ), @@ -617,7 +617,7 @@ def test_pivot_tz_in_values(self): pd.Timestamp("2016-08-25 11:00:00-0700", tz="US/Pacific"), ] ], - index=pd.Index(["aa"], name="uid"), + index=Index(["aa"], name="uid"), columns=pd.DatetimeIndex( [ pd.Timestamp("2016-08-12 00:00:00", tz="US/Pacific"), @@ -691,10 +691,8 @@ def test_pivot_periods_with_margins(self): expected = DataFrame( data=1.0, - index=pd.Index([1, 2, "All"], name="a"), - columns=pd.Index( - [pd.Period("2019Q1"), pd.Period("2019Q2"), "All"], name="b" - ), + index=Index([1, 2, "All"], name="a"), + columns=Index([pd.Period("2019Q1"), pd.Period("2019Q2"), "All"], name="b"), ) result = df.pivot_table(index="a", columns="b", values="x", margins=True) @@ -706,7 +704,7 @@ def test_pivot_periods_with_margins(self): ["baz", "zoo"], np.array(["baz", "zoo"]), Series(["baz", "zoo"]), - pd.Index(["baz", "zoo"]), + Index(["baz", "zoo"]), ], ) @pytest.mark.parametrize("method", [True, False]) @@ -742,7 +740,7 @@ def test_pivot_with_list_like_values(self, values, method): ["bar", "baz"], np.array(["bar", "baz"]), Series(["bar", "baz"]), - pd.Index(["bar", "baz"]), + Index(["bar", "baz"]), ], ) @pytest.mark.parametrize("method", [True, False]) @@ -1696,7 +1694,7 @@ def test_pivot_table_margins_name_with_aggfunc_list(self): margins_name=margins_name, aggfunc=[np.mean, max], ) - ix = pd.Index(["bacon", "cheese", margins_name], dtype="object", name="item") + ix = Index(["bacon", "cheese", margins_name], dtype="object", name="item") tups = [ ("mean", "cost", "M"), ("mean", "cost", "T"), @@ -1752,7 +1750,7 @@ def test_margins_casted_to_float(self, observed): result = pd.pivot_table(df, index="D", margins=True) expected = DataFrame( {"A": [3, 7, 5], "B": [2.5, 6.5, 4.5], "C": [2, 5, 3.5]}, - index=pd.Index(["X", "Y", "All"], name="D"), + index=Index(["X", "Y", "All"], name="D"), ) tm.assert_frame_equal(result, expected) @@ -1806,7 +1804,7 @@ def test_categorical_aggfunc(self, observed): expected_index = pd.CategoricalIndex( ["A", "B", "C"], categories=["A", "B", "C"], ordered=False, name="C1" ) - expected_columns = pd.Index(["a", "b"], name="C2") + expected_columns = Index(["a", "b"], name="C2") expected_data = np.array([[1, 0], [1, 0], [0, 2]], dtype=np.int64) expected = DataFrame( expected_data, index=expected_index, columns=expected_columns @@ -1892,7 +1890,7 @@ def test_pivot_margins_name_unicode(self): table = pd.pivot_table( frame, index=["foo"], aggfunc=len, margins=True, margins_name=greek ) - index = pd.Index([1, 2, 3, greek], dtype="object", name="foo") + index = Index([1, 2, 3, greek], dtype="object", name="foo") expected = DataFrame(index=index) tm.assert_frame_equal(table, expected) @@ -2033,7 +2031,7 @@ def test_pivot_table_aggfunc_scalar_dropna(self, dropna): result = pd.pivot_table(df, columns="A", aggfunc=np.mean, dropna=dropna) data = [[2.5, np.nan], [1, np.nan]] - col = pd.Index(["one", "two"], name="A") + col = Index(["one", "two"], name="A") expected = DataFrame(data, index=["x", "y"], columns=col) if dropna: diff --git a/pandas/tests/series/apply/test_series_apply.py b/pandas/tests/series/apply/test_series_apply.py index 2627e8b8608a9..9096d2a1033e5 100644 --- a/pandas/tests/series/apply/test_series_apply.py +++ b/pandas/tests/series/apply/test_series_apply.py @@ -25,7 +25,7 @@ def test_apply(self, datetime_series): ) # empty series - s = Series(dtype=object, name="foo", index=pd.Index([], name="bar")) + s = Series(dtype=object, name="foo", index=Index([], name="bar")) rs = s.apply(lambda x: x) tm.assert_series_equal(s, rs) diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 92cd1e546b54d..c80a2f7cba9ad 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -155,7 +155,7 @@ def test_constructor_dict_multiindex(self): _d.insert(0, ("z", d["z"])) result = Series(d) expected = Series( - [x[1] for x in _d], index=pd.Index([x[0] for x in _d], tupleize_cols=False) + [x[1] for x in _d], index=Index([x[0] for x in _d], tupleize_cols=False) ) result = result.reindex(index=expected.index) tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 1ca639e85d913..efa2ab0f22442 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -176,7 +176,7 @@ def test_constructor_nan(self, input_arg): "dtype", ["f8", "i8", "M8[ns]", "m8[ns]", "category", "object", "datetime64[ns, UTC]"], ) - @pytest.mark.parametrize("index", [None, pd.Index([])]) + @pytest.mark.parametrize("index", [None, Index([])]) def test_constructor_dtype_only(self, dtype, index): # GH-20865 result = Series(dtype=dtype, index=index) @@ -383,12 +383,12 @@ def test_constructor_categorical_dtype(self): ["a", "b"], dtype=CategoricalDtype(["a", "b", "c"], ordered=True) ) assert is_categorical_dtype(result.dtype) is True - tm.assert_index_equal(result.cat.categories, pd.Index(["a", "b", "c"])) + tm.assert_index_equal(result.cat.categories, Index(["a", "b", "c"])) assert result.cat.ordered result = Series(["a", "b"], dtype=CategoricalDtype(["b", "a"])) assert is_categorical_dtype(result.dtype) - tm.assert_index_equal(result.cat.categories, pd.Index(["b", "a"])) + tm.assert_index_equal(result.cat.categories, Index(["b", "a"])) assert result.cat.ordered is False # GH 19565 - Check broadcasting of scalar with Categorical dtype @@ -546,7 +546,7 @@ def test_series_ctor_plus_datetimeindex(self): def test_constructor_default_index(self): s = Series([0, 1, 2]) - tm.assert_index_equal(s.index, pd.Index(np.arange(3))) + tm.assert_index_equal(s.index, Index(np.arange(3))) @pytest.mark.parametrize( "input", @@ -619,7 +619,7 @@ def test_constructor_copy(self): pd.date_range("20170101", periods=3), pd.timedelta_range("1 day", periods=3), pd.period_range("2012Q1", periods=3, freq="Q"), - pd.Index(list("abc")), + Index(list("abc")), pd.Int64Index([1, 2, 3]), pd.RangeIndex(0, 3), ], @@ -1406,7 +1406,7 @@ def test_constructor_cast_object(self, index): exp = Series(index).astype(object) tm.assert_series_equal(s, exp) - s = Series(pd.Index(index, dtype=object), dtype=object) + s = Series(Index(index, dtype=object), dtype=object) exp = Series(index).astype(object) tm.assert_series_equal(s, exp) diff --git a/pandas/tests/series/test_logical_ops.py b/pandas/tests/series/test_logical_ops.py index 08bb24a01b088..3d53e7ac26338 100644 --- a/pandas/tests/series/test_logical_ops.py +++ b/pandas/tests/series/test_logical_ops.py @@ -4,7 +4,6 @@ import numpy as np import pytest -import pandas as pd from pandas import DataFrame, Index, Series, bdate_range import pandas._testing as tm from pandas.core import ops @@ -161,7 +160,7 @@ def test_logical_ops_bool_dtype_with_ndarray(self): tm.assert_series_equal(result, expected) result = left & np.array(right) tm.assert_series_equal(result, expected) - result = left & pd.Index(right) + result = left & Index(right) tm.assert_series_equal(result, expected) result = left & Series(right) tm.assert_series_equal(result, expected) @@ -171,7 +170,7 @@ def test_logical_ops_bool_dtype_with_ndarray(self): tm.assert_series_equal(result, expected) result = left | np.array(right) tm.assert_series_equal(result, expected) - result = left | pd.Index(right) + result = left | Index(right) tm.assert_series_equal(result, expected) result = left | Series(right) tm.assert_series_equal(result, expected) @@ -181,7 +180,7 @@ def test_logical_ops_bool_dtype_with_ndarray(self): tm.assert_series_equal(result, expected) result = left ^ np.array(right) tm.assert_series_equal(result, expected) - result = left ^ pd.Index(right) + result = left ^ Index(right) tm.assert_series_equal(result, expected) result = left ^ Series(right) tm.assert_series_equal(result, expected) @@ -315,9 +314,9 @@ def test_reversed_logical_op_with_index_returns_series(self, op): @pytest.mark.parametrize( "op, expected", [ - (ops.rand_, pd.Index([False, True])), - (ops.ror_, pd.Index([False, True])), - (ops.rxor, pd.Index([])), + (ops.rand_, Index([False, True])), + (ops.ror_, Index([False, True])), + (ops.rxor, Index([])), ], ) def test_reverse_ops_with_index(self, op, expected): diff --git a/pandas/tests/series/test_repr.py b/pandas/tests/series/test_repr.py index 32e1220f83f40..7325505ce233b 100644 --- a/pandas/tests/series/test_repr.py +++ b/pandas/tests/series/test_repr.py @@ -252,7 +252,7 @@ def __repr__(self) -> str: return self.name + ", " + self.state cat = pd.Categorical([County() for _ in range(61)]) - idx = pd.Index(cat) + idx = Index(cat) ser = idx.to_series() repr(ser) diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 7ee4b86fb4049..13c8987c66977 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -320,7 +320,7 @@ def test_to_datetime_format_weeks(self, cache): def test_to_datetime_parse_tzname_or_tzoffset(self, fmt, dates, expected_dates): # GH 13486 result = pd.to_datetime(dates, format=fmt) - expected = pd.Index(expected_dates) + expected = Index(expected_dates) tm.assert_equal(result, expected) def test_to_datetime_parse_tzname_or_tzoffset_different_tz_to_utc(self): @@ -357,7 +357,7 @@ def test_to_datetime_parse_timezone_malformed(self, offset): def test_to_datetime_parse_timezone_keeps_name(self): # GH 21697 fmt = "%Y-%m-%d %H:%M:%S %z" - arg = pd.Index(["2010-01-01 12:00:00 Z"], name="foo") + arg = Index(["2010-01-01 12:00:00 Z"], name="foo") result = pd.to_datetime(arg, format=fmt) expected = pd.DatetimeIndex(["2010-01-01 12:00:00"], tz="UTC", name="foo") tm.assert_index_equal(result, expected) @@ -613,7 +613,7 @@ def test_to_datetime_array_of_dt64s(self, cache, unit): # numpy is either a python datetime.datetime or datetime.date tm.assert_index_equal( pd.to_datetime(dts_with_oob, errors="ignore", cache=cache), - pd.Index([dt.item() for dt in dts_with_oob]), + Index([dt.item() for dt in dts_with_oob]), ) @pytest.mark.parametrize("cache", [True, False]) @@ -650,7 +650,7 @@ def test_to_datetime_different_offsets(self, cache): ts_string_1 = "March 1, 2018 12:00:00+0400" ts_string_2 = "March 1, 2018 12:00:00+0500" arr = [ts_string_1] * 5 + [ts_string_2] * 5 - expected = pd.Index([parse(x) for x in arr]) + expected = Index([parse(x) for x in arr]) result = pd.to_datetime(arr, cache=cache) tm.assert_index_equal(result, expected) @@ -876,7 +876,7 @@ def test_datetime_invalid_index(self, values, format, infer): res = pd.to_datetime( values, errors="ignore", format=format, infer_datetime_format=infer ) - tm.assert_index_equal(res, pd.Index(values)) + tm.assert_index_equal(res, Index(values)) res = pd.to_datetime( values, errors="coerce", format=format, infer_datetime_format=infer @@ -895,7 +895,7 @@ def test_datetime_invalid_index(self, values, format, infer): @pytest.mark.parametrize("utc", [True, None]) @pytest.mark.parametrize("format", ["%Y%m%d %H:%M:%S", None]) - @pytest.mark.parametrize("constructor", [list, tuple, np.array, pd.Index, deque]) + @pytest.mark.parametrize("constructor", [list, tuple, np.array, Index, deque]) def test_to_datetime_cache(self, utc, format, constructor): date = "20130101 00:00:00" test_dates = [date] * 10 ** 5 @@ -1246,7 +1246,7 @@ def test_unit_rounding(self, cache): @pytest.mark.parametrize("cache", [True, False]) def test_unit_ignore_keeps_name(self, cache): # GH 21697 - expected = pd.Index([15e9] * 2, name="name") + expected = Index([15e9] * 2, name="name") result = pd.to_datetime(expected, errors="ignore", unit="s", cache=cache) tm.assert_index_equal(result, expected)
Fixing use of pd.Index when Index is imported directly
https://api.github.com/repos/pandas-dev/pandas/pulls/37351
2020-10-23T01:00:41Z
2020-10-23T03:16:50Z
2020-10-23T03:16:49Z
2020-10-23T17:05:23Z
TST: fixturize/parametrize test_eval to the bone
diff --git a/pandas/tests/computation/test_eval.py b/pandas/tests/computation/test_eval.py index 5796ea52899d2..4c670e56613ed 100644 --- a/pandas/tests/computation/test_eval.py +++ b/pandas/tests/computation/test_eval.py @@ -2,7 +2,7 @@ from functools import reduce from itertools import product import operator -from typing import Dict, Type +from typing import Dict, List, Type import warnings import numpy as np @@ -65,15 +65,18 @@ def ne_lt_2_6_9(): return "numexpr" -@pytest.fixture -def unary_fns_for_ne(): +def _get_unary_fns_for_ne(): if NUMEXPR_INSTALLED: if NUMEXPR_VERSION >= LooseVersion("2.6.9"): - return _unary_math_ops + return list(_unary_math_ops) else: - return tuple(x for x in _unary_math_ops if x not in ("floor", "ceil")) - else: - pytest.skip("numexpr is not present") + return [x for x in _unary_math_ops if x not in ["floor", "ceil"]] + return [] + + +@pytest.fixture(params=_get_unary_fns_for_ne()) +def unary_fns_for_ne(request): + return request.param def engine_has_neg_frac(engine): @@ -117,81 +120,69 @@ def _is_py3_complex_incompat(result, expected): _good_arith_ops = set(ARITH_OPS_SYMS).difference(SPECIAL_CASE_ARITH_OPS_SYMS) +# TODO: using range(5) here is a kludge +@pytest.fixture(params=list(range(5))) +def lhs(request): + + nan_df1 = DataFrame(rand(10, 5)) + nan_df1[nan_df1 > 0.5] = np.nan + + opts = ( + DataFrame(randn(10, 5)), + Series(randn(5)), + Series([1, 2, np.nan, np.nan, 5]), + nan_df1, + randn(), + ) + return opts[request.param] + + +rhs = lhs +midhs = lhs + + @td.skip_if_no_ne class TestEvalNumexprPandas: + exclude_cmp: List[str] = [] + exclude_bool: List[str] = [] + + engine = "numexpr" + parser = "pandas" + @classmethod def setup_class(cls): import numexpr as ne cls.ne = ne - cls.engine = "numexpr" - cls.parser = "pandas" - @classmethod - def teardown_class(cls): - del cls.engine, cls.parser - if hasattr(cls, "ne"): - del cls.ne - - def setup_data(self): - nan_df1 = DataFrame(rand(10, 5)) - nan_df1[nan_df1 > 0.5] = np.nan - nan_df2 = DataFrame(rand(10, 5)) - nan_df2[nan_df2 > 0.5] = np.nan - - self.pandas_lhses = ( - DataFrame(randn(10, 5)), - Series(randn(5)), - Series([1, 2, np.nan, np.nan, 5]), - nan_df1, - ) - self.pandas_rhses = ( - DataFrame(randn(10, 5)), - Series(randn(5)), - Series([1, 2, np.nan, np.nan, 5]), - nan_df2, - ) - self.scalar_lhses = (randn(),) - self.scalar_rhses = (randn(),) - - self.lhses = self.pandas_lhses + self.scalar_lhses - self.rhses = self.pandas_rhses + self.scalar_rhses - - def setup_ops(self): - self.cmp_ops = expr.CMP_OPS_SYMS - self.cmp2_ops = self.cmp_ops[::-1] - self.bin_ops = expr.BOOL_OPS_SYMS - self.special_case_ops = SPECIAL_CASE_ARITH_OPS_SYMS - self.arith_ops = _good_arith_ops - self.unary_ops = "-", "~", "not " - - def setup_method(self, method): - self.setup_ops() - self.setup_data() - self.current_engines = (engine for engine in ENGINES if engine != self.engine) - - def teardown_method(self, method): - del self.lhses, self.rhses, self.scalar_rhses, self.scalar_lhses - del self.pandas_rhses, self.pandas_lhses, self.current_engines - - @pytest.mark.slow + @property + def current_engines(self): + return (engine for engine in ENGINES if engine != self.engine) + @pytest.mark.parametrize( "cmp1", ["!=", "==", "<=", ">=", "<", ">"], ids=["ne", "eq", "le", "ge", "lt", "gt"], ) @pytest.mark.parametrize("cmp2", [">", "<"], ids=["gt", "lt"]) - def test_complex_cmp_ops(self, cmp1, cmp2): - for lhs, rhs, binop in product(self.lhses, self.rhses, self.bin_ops): - lhs_new = _eval_single_bin(lhs, cmp1, rhs, self.engine) - rhs_new = _eval_single_bin(lhs, cmp2, rhs, self.engine) - expected = _eval_single_bin(lhs_new, binop, rhs_new, self.engine) + @pytest.mark.parametrize("binop", expr.BOOL_OPS_SYMS) + def test_complex_cmp_ops(self, cmp1, cmp2, binop, lhs, rhs): + if binop in self.exclude_bool: + pytest.skip() - ex = f"(lhs {cmp1} rhs) {binop} (lhs {cmp2} rhs)" - result = pd.eval(ex, engine=self.engine, parser=self.parser) - self.check_equal(result, expected) + lhs_new = _eval_single_bin(lhs, cmp1, rhs, self.engine) + rhs_new = _eval_single_bin(lhs, cmp2, rhs, self.engine) + expected = _eval_single_bin(lhs_new, binop, rhs_new, self.engine) + + ex = f"(lhs {cmp1} rhs) {binop} (lhs {cmp2} rhs)" + result = pd.eval(ex, engine=self.engine, parser=self.parser) + self.check_equal(result, expected) + + @pytest.mark.parametrize("cmp_op", expr.CMP_OPS_SYMS) + def test_simple_cmp_ops(self, cmp_op): + if cmp_op in self.exclude_cmp: + pytest.skip() - def test_simple_cmp_ops(self): bool_lhses = ( DataFrame(tm.randbool(size=(10, 5))), Series(tm.randbool((5,))), @@ -202,46 +193,42 @@ def test_simple_cmp_ops(self): Series(tm.randbool((5,))), tm.randbool(), ) - for lhs, rhs, cmp_op in product(bool_lhses, bool_rhses, self.cmp_ops): + for lhs, rhs in product(bool_lhses, bool_rhses): self.check_simple_cmp_op(lhs, cmp_op, rhs) - @pytest.mark.slow - def test_binary_arith_ops(self): - for lhs, op, rhs in product(self.lhses, self.arith_ops, self.rhses): - self.check_binary_arith_op(lhs, op, rhs) + @pytest.mark.parametrize("op", _good_arith_ops) + def test_binary_arith_ops(self, op, lhs, rhs): + self.check_binary_arith_op(lhs, op, rhs) - def test_modulus(self): - for lhs, rhs in product(self.lhses, self.rhses): - self.check_modulus(lhs, "%", rhs) + def test_modulus(self, lhs, rhs): + self.check_modulus(lhs, "%", rhs) - def test_floor_division(self): - for lhs, rhs in product(self.lhses, self.rhses): - self.check_floor_division(lhs, "//", rhs) + def test_floor_division(self, lhs, rhs): + self.check_floor_division(lhs, "//", rhs) @td.skip_if_windows - def test_pow(self): + def test_pow(self, lhs, rhs): # odd failure on win32 platform, so skip - for lhs, rhs in product(self.lhses, self.rhses): - self.check_pow(lhs, "**", rhs) - - @pytest.mark.slow - def test_single_invert_op(self): - for lhs, op, rhs in product(self.lhses, self.cmp_ops, self.rhses): - self.check_single_invert_op(lhs, op, rhs) - - @pytest.mark.slow - def test_compound_invert_op(self): - for lhs, op, rhs in product(self.lhses, self.cmp_ops, self.rhses): - self.check_compound_invert_op(lhs, op, rhs) - - @pytest.mark.slow - def test_chained_cmp_op(self): - mids = self.lhses - cmp_ops = "<", ">" - for lhs, cmp1, mid, cmp2, rhs in product( - self.lhses, cmp_ops, mids, cmp_ops, self.rhses - ): - self.check_chained_cmp_op(lhs, cmp1, mid, cmp2, rhs) + self.check_pow(lhs, "**", rhs) + + @pytest.mark.parametrize("op", expr.CMP_OPS_SYMS) + def test_single_invert_op(self, op, lhs): + if op in self.exclude_cmp: + pytest.skip() + + self.check_single_invert_op(lhs, op) + + @pytest.mark.parametrize("op", expr.CMP_OPS_SYMS) + def test_compound_invert_op(self, op, lhs, rhs): + if op in self.exclude_cmp: + pytest.skip() + + self.check_compound_invert_op(lhs, op, rhs) + + @pytest.mark.parametrize("cmp1", ["<", ">"]) + @pytest.mark.parametrize("cmp2", ["<", ">"]) + def test_chained_cmp_op(self, cmp1, cmp2, lhs, midhs, rhs): + self.check_chained_cmp_op(lhs, cmp1, midhs, cmp2, rhs) def check_equal(self, result, expected): if isinstance(result, DataFrame): @@ -388,21 +375,20 @@ def check_pow(self, lhs, arith1, rhs): ) tm.assert_almost_equal(result, expected) - def check_single_invert_op(self, lhs, cmp1, rhs): + def check_single_invert_op(self, elem, cmp1): # simple - for el in (lhs, rhs): - try: - elb = el.astype(bool) - except AttributeError: - elb = np.array([bool(el)]) - expected = ~elb - result = pd.eval("~elb", engine=self.engine, parser=self.parser) - tm.assert_almost_equal(expected, result) - - for engine in self.current_engines: - tm.assert_almost_equal( - result, pd.eval("~elb", engine=engine, parser=self.parser) - ) + try: + elb = elem.astype(bool) + except AttributeError: + elb = np.array([bool(elem)]) + expected = ~elb + result = pd.eval("~elb", engine=self.engine, parser=self.parser) + tm.assert_almost_equal(expected, result) + + for engine in self.current_engines: + tm.assert_almost_equal( + result, pd.eval("~elb", engine=engine, parser=self.parser) + ) def check_compound_invert_op(self, lhs, cmp1, rhs): skip_these = ["in", "not in"] @@ -764,22 +750,18 @@ def test_disallow_python_keywords(self): @td.skip_if_no_ne class TestEvalNumexprPython(TestEvalNumexprPandas): + exclude_cmp = ["in", "not in"] + exclude_bool = ["and", "or"] + + engine = "numexpr" + parser = "python" + @classmethod def setup_class(cls): super().setup_class() import numexpr as ne cls.ne = ne - cls.engine = "numexpr" - cls.parser = "python" - - def setup_ops(self): - self.cmp_ops = [op for op in expr.CMP_OPS_SYMS if op not in ("in", "not in")] - self.cmp2_ops = self.cmp_ops[::-1] - self.bin_ops = [op for op in expr.BOOL_OPS_SYMS if op not in ("and", "or")] - self.special_case_ops = SPECIAL_CASE_ARITH_OPS_SYMS - self.arith_ops = _good_arith_ops - self.unary_ops = "+", "-", "~" def check_chained_cmp_op(self, lhs, cmp1, mid, cmp2, rhs): ex1 = f"lhs {cmp1} mid {cmp2} rhs" @@ -789,11 +771,8 @@ def check_chained_cmp_op(self, lhs, cmp1, mid, cmp2, rhs): class TestEvalPythonPython(TestEvalNumexprPython): - @classmethod - def setup_class(cls): - super().setup_class() - cls.engine = "python" - cls.parser = "python" + engine = "python" + parser = "python" def check_modulus(self, lhs, arith1, rhs): ex = f"lhs {arith1} rhs" @@ -818,11 +797,8 @@ def check_alignment(self, result, nlhs, ghs, op): class TestEvalPythonPandas(TestEvalPythonPython): - @classmethod - def setup_class(cls): - super().setup_class() - cls.engine = "python" - cls.parser = "pandas" + engine = "python" + parser = "pandas" def check_chained_cmp_op(self, lhs, cmp1, mid, cmp2, rhs): TestEvalNumexprPandas.check_chained_cmp_op(self, lhs, cmp1, mid, cmp2, rhs) @@ -871,8 +847,8 @@ def should_warn(*args): class TestAlignment: - index_types = "i", "u", "dt" - lhs_index_types = index_types + ("s",) # 'p' + index_types = ["i", "u", "dt"] + lhs_index_types = index_types + ["s"] # 'p' def test_align_nested_unary_op(self, engine, parser): s = "df * ~2" @@ -880,65 +856,73 @@ def test_align_nested_unary_op(self, engine, parser): res = pd.eval(s, engine=engine, parser=parser) tm.assert_frame_equal(res, df * ~2) - def test_basic_frame_alignment(self, engine, parser): - args = product(self.lhs_index_types, self.index_types, self.index_types) + @pytest.mark.parametrize("lr_idx_type", lhs_index_types) + @pytest.mark.parametrize("rr_idx_type", index_types) + @pytest.mark.parametrize("c_idx_type", index_types) + def test_basic_frame_alignment( + self, engine, parser, lr_idx_type, rr_idx_type, c_idx_type + ): with warnings.catch_warnings(record=True): warnings.simplefilter("always", RuntimeWarning) - for lr_idx_type, rr_idx_type, c_idx_type in args: - df = tm.makeCustomDataframe( - 10, 10, data_gen_f=f, r_idx_type=lr_idx_type, c_idx_type=c_idx_type - ) - df2 = tm.makeCustomDataframe( - 20, 10, data_gen_f=f, r_idx_type=rr_idx_type, c_idx_type=c_idx_type - ) - # only warns if not monotonic and not sortable - if should_warn(df.index, df2.index): - with tm.assert_produces_warning(RuntimeWarning): - res = pd.eval("df + df2", engine=engine, parser=parser) - else: - res = pd.eval("df + df2", engine=engine, parser=parser) - tm.assert_frame_equal(res, df + df2) - def test_frame_comparison(self, engine, parser): - args = product(self.lhs_index_types, repeat=2) - for r_idx_type, c_idx_type in args: df = tm.makeCustomDataframe( - 10, 10, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type + 10, 10, data_gen_f=f, r_idx_type=lr_idx_type, c_idx_type=c_idx_type + ) + df2 = tm.makeCustomDataframe( + 20, 10, data_gen_f=f, r_idx_type=rr_idx_type, c_idx_type=c_idx_type ) - res = pd.eval("df < 2", engine=engine, parser=parser) - tm.assert_frame_equal(res, df < 2) + # only warns if not monotonic and not sortable + if should_warn(df.index, df2.index): + with tm.assert_produces_warning(RuntimeWarning): + res = pd.eval("df + df2", engine=engine, parser=parser) + else: + res = pd.eval("df + df2", engine=engine, parser=parser) + tm.assert_frame_equal(res, df + df2) + + @pytest.mark.parametrize("r_idx_type", lhs_index_types) + @pytest.mark.parametrize("c_idx_type", lhs_index_types) + def test_frame_comparison(self, engine, parser, r_idx_type, c_idx_type): + df = tm.makeCustomDataframe( + 10, 10, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type + ) + res = pd.eval("df < 2", engine=engine, parser=parser) + tm.assert_frame_equal(res, df < 2) - df3 = DataFrame(randn(*df.shape), index=df.index, columns=df.columns) - res = pd.eval("df < df3", engine=engine, parser=parser) - tm.assert_frame_equal(res, df < df3) + df3 = DataFrame(randn(*df.shape), index=df.index, columns=df.columns) + res = pd.eval("df < df3", engine=engine, parser=parser) + tm.assert_frame_equal(res, df < df3) - @pytest.mark.slow - def test_medium_complex_frame_alignment(self, engine, parser): - args = product( - self.lhs_index_types, self.index_types, self.index_types, self.index_types - ) + @pytest.mark.parametrize("r1", lhs_index_types) + @pytest.mark.parametrize("c1", index_types) + @pytest.mark.parametrize("r2", index_types) + @pytest.mark.parametrize("c2", index_types) + def test_medium_complex_frame_alignment(self, engine, parser, r1, c1, r2, c2): with warnings.catch_warnings(record=True): warnings.simplefilter("always", RuntimeWarning) - for r1, c1, r2, c2 in args: - df = tm.makeCustomDataframe( - 3, 2, data_gen_f=f, r_idx_type=r1, c_idx_type=c1 - ) - df2 = tm.makeCustomDataframe( - 4, 2, data_gen_f=f, r_idx_type=r2, c_idx_type=c2 - ) - df3 = tm.makeCustomDataframe( - 5, 2, data_gen_f=f, r_idx_type=r2, c_idx_type=c2 - ) - if should_warn(df.index, df2.index, df3.index): - with tm.assert_produces_warning(RuntimeWarning): - res = pd.eval("df + df2 + df3", engine=engine, parser=parser) - else: + df = tm.makeCustomDataframe( + 3, 2, data_gen_f=f, r_idx_type=r1, c_idx_type=c1 + ) + df2 = tm.makeCustomDataframe( + 4, 2, data_gen_f=f, r_idx_type=r2, c_idx_type=c2 + ) + df3 = tm.makeCustomDataframe( + 5, 2, data_gen_f=f, r_idx_type=r2, c_idx_type=c2 + ) + if should_warn(df.index, df2.index, df3.index): + with tm.assert_produces_warning(RuntimeWarning): res = pd.eval("df + df2 + df3", engine=engine, parser=parser) - tm.assert_frame_equal(res, df + df2 + df3) - - def test_basic_frame_series_alignment(self, engine, parser): + else: + res = pd.eval("df + df2 + df3", engine=engine, parser=parser) + tm.assert_frame_equal(res, df + df2 + df3) + + @pytest.mark.parametrize("index_name", ["index", "columns"]) + @pytest.mark.parametrize("c_idx_type", index_types) + @pytest.mark.parametrize("r_idx_type", lhs_index_types) + def test_basic_frame_series_alignment( + self, engine, parser, index_name, r_idx_type, c_idx_type + ): def testit(r_idx_type, c_idx_type, index_name): df = tm.makeCustomDataframe( 10, 10, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type @@ -958,13 +942,13 @@ def testit(r_idx_type, c_idx_type, index_name): expected = df + s tm.assert_frame_equal(res, expected) - args = product(self.lhs_index_types, self.index_types, ("index", "columns")) with warnings.catch_warnings(record=True): warnings.simplefilter("always", RuntimeWarning) - for r_idx_type, c_idx_type, index_name in args: - testit(r_idx_type, c_idx_type, index_name) - def test_basic_series_frame_alignment(self, engine, parser): + testit(r_idx_type, c_idx_type, index_name) + + @pytest.mark.parametrize("index_name", ["index", "columns"]) + def test_basic_series_frame_alignment(self, engine, parser, index_name): def testit(r_idx_type, c_idx_type, index_name): df = tm.makeCustomDataframe( 10, 7, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type @@ -984,101 +968,104 @@ def testit(r_idx_type, c_idx_type, index_name): tm.assert_frame_equal(res, expected) # only test dt with dt, otherwise weird joins result - args = product(["i", "u", "s"], ["i", "u", "s"], ("index", "columns")) + args = product(["i", "u", "s"], ["i", "u", "s"]) with warnings.catch_warnings(record=True): # avoid warning about comparing strings and ints warnings.simplefilter("ignore", RuntimeWarning) - for r_idx_type, c_idx_type, index_name in args: + for r_idx_type, c_idx_type in args: testit(r_idx_type, c_idx_type, index_name) # dt with dt - args = product(["dt"], ["dt"], ("index", "columns")) + args = product(["dt"], ["dt"]) with warnings.catch_warnings(record=True): # avoid warning about comparing strings and ints warnings.simplefilter("ignore", RuntimeWarning) - for r_idx_type, c_idx_type, index_name in args: + for r_idx_type, c_idx_type in args: testit(r_idx_type, c_idx_type, index_name) - def test_series_frame_commutativity(self, engine, parser): - args = product( - self.lhs_index_types, self.index_types, ("+", "*"), ("index", "columns") - ) + @pytest.mark.parametrize("c_idx_type", index_types) + @pytest.mark.parametrize("r_idx_type", lhs_index_types) + @pytest.mark.parametrize("index_name", ["index", "columns"]) + @pytest.mark.parametrize("op", ["+", "*"]) + def test_series_frame_commutativity( + self, engine, parser, index_name, op, r_idx_type, c_idx_type + ): with warnings.catch_warnings(record=True): warnings.simplefilter("always", RuntimeWarning) - for r_idx_type, c_idx_type, op, index_name in args: - df = tm.makeCustomDataframe( - 10, 10, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type - ) - index = getattr(df, index_name) - s = Series(np.random.randn(5), index[:5]) - - lhs = f"s {op} df" - rhs = f"df {op} s" - if should_warn(df.index, s.index): - with tm.assert_produces_warning(RuntimeWarning): - a = pd.eval(lhs, engine=engine, parser=parser) - with tm.assert_produces_warning(RuntimeWarning): - b = pd.eval(rhs, engine=engine, parser=parser) - else: - a = pd.eval(lhs, engine=engine, parser=parser) - b = pd.eval(rhs, engine=engine, parser=parser) - if r_idx_type != "dt" and c_idx_type != "dt": - if engine == "numexpr": - tm.assert_frame_equal(a, b) + df = tm.makeCustomDataframe( + 10, 10, data_gen_f=f, r_idx_type=r_idx_type, c_idx_type=c_idx_type + ) + index = getattr(df, index_name) + s = Series(np.random.randn(5), index[:5]) - @pytest.mark.slow - def test_complex_series_frame_alignment(self, engine, parser): + lhs = f"s {op} df" + rhs = f"df {op} s" + if should_warn(df.index, s.index): + with tm.assert_produces_warning(RuntimeWarning): + a = pd.eval(lhs, engine=engine, parser=parser) + with tm.assert_produces_warning(RuntimeWarning): + b = pd.eval(rhs, engine=engine, parser=parser) + else: + a = pd.eval(lhs, engine=engine, parser=parser) + b = pd.eval(rhs, engine=engine, parser=parser) + + if r_idx_type != "dt" and c_idx_type != "dt": + if engine == "numexpr": + tm.assert_frame_equal(a, b) + + @pytest.mark.parametrize("r1", lhs_index_types) + @pytest.mark.parametrize("c1", index_types) + @pytest.mark.parametrize("r2", index_types) + @pytest.mark.parametrize("c2", index_types) + def test_complex_series_frame_alignment(self, engine, parser, r1, c1, r2, c2): import random - args = product( - self.lhs_index_types, self.index_types, self.index_types, self.index_types - ) n = 3 m1 = 5 m2 = 2 * m1 with warnings.catch_warnings(record=True): warnings.simplefilter("always", RuntimeWarning) - for r1, r2, c1, c2 in args: - index_name = random.choice(["index", "columns"]) - obj_name = random.choice(["df", "df2"]) - df = tm.makeCustomDataframe( - m1, n, data_gen_f=f, r_idx_type=r1, c_idx_type=c1 - ) - df2 = tm.makeCustomDataframe( - m2, n, data_gen_f=f, r_idx_type=r2, c_idx_type=c2 - ) - index = getattr(locals().get(obj_name), index_name) - ser = Series(np.random.randn(n), index[:n]) - - if r2 == "dt" or c2 == "dt": - if engine == "numexpr": - expected2 = df2.add(ser) - else: - expected2 = df2 + ser + index_name = random.choice(["index", "columns"]) + obj_name = random.choice(["df", "df2"]) + + df = tm.makeCustomDataframe( + m1, n, data_gen_f=f, r_idx_type=r1, c_idx_type=c1 + ) + df2 = tm.makeCustomDataframe( + m2, n, data_gen_f=f, r_idx_type=r2, c_idx_type=c2 + ) + index = getattr(locals().get(obj_name), index_name) + ser = Series(np.random.randn(n), index[:n]) + + if r2 == "dt" or c2 == "dt": + if engine == "numexpr": + expected2 = df2.add(ser) else: expected2 = df2 + ser + else: + expected2 = df2 + ser - if r1 == "dt" or c1 == "dt": - if engine == "numexpr": - expected = expected2.add(df) - else: - expected = expected2 + df + if r1 == "dt" or c1 == "dt": + if engine == "numexpr": + expected = expected2.add(df) else: expected = expected2 + df + else: + expected = expected2 + df - if should_warn(df2.index, ser.index, df.index): - with tm.assert_produces_warning(RuntimeWarning): - res = pd.eval("df2 + ser + df", engine=engine, parser=parser) - else: + if should_warn(df2.index, ser.index, df.index): + with tm.assert_produces_warning(RuntimeWarning): res = pd.eval("df2 + ser + df", engine=engine, parser=parser) - assert res.shape == expected.shape - tm.assert_frame_equal(res, expected) + else: + res = pd.eval("df2 + ser + df", engine=engine, parser=parser) + assert res.shape == expected.shape + tm.assert_frame_equal(res, expected) def test_performance_warning_for_poor_alignment(self, engine, parser): df = DataFrame(randn(1000, 10)) @@ -1131,15 +1118,18 @@ def test_performance_warning_for_poor_alignment(self, engine, parser): @td.skip_if_no_ne class TestOperationsNumExprPandas: - @classmethod - def setup_class(cls): - cls.engine = "numexpr" - cls.parser = "pandas" - cls.arith_ops = expr.ARITH_OPS_SYMS + expr.CMP_OPS_SYMS + exclude_arith: List[str] = [] + + engine = "numexpr" + parser = "pandas" @classmethod - def teardown_class(cls): - del cls.engine, cls.parser + def setup_class(cls): + cls.arith_ops = [ + op + for op in expr.ARITH_OPS_SYMS + expr.CMP_OPS_SYMS + if op not in cls.exclude_arith + ] def eval(self, *args, **kwargs): kwargs["engine"] = self.engine @@ -1176,21 +1166,23 @@ def test_simple_arith_ops(self): ) assert y == expec - def test_simple_bool_ops(self): - for op, lhs, rhs in product(expr.BOOL_OPS_SYMS, (True, False), (True, False)): - ex = f"{lhs} {op} {rhs}" - res = self.eval(ex) - exp = eval(ex) - assert res == exp - - def test_bool_ops_with_constants(self): - for op, lhs, rhs in product( - expr.BOOL_OPS_SYMS, ("True", "False"), ("True", "False") - ): - ex = f"{lhs} {op} {rhs}" - res = self.eval(ex) - exp = eval(ex) - assert res == exp + @pytest.mark.parametrize("rhs", [True, False]) + @pytest.mark.parametrize("lhs", [True, False]) + @pytest.mark.parametrize("op", expr.BOOL_OPS_SYMS) + def test_simple_bool_ops(self, rhs, lhs, op): + ex = f"{lhs} {op} {rhs}" + res = self.eval(ex) + exp = eval(ex) + assert res == exp + + @pytest.mark.parametrize("rhs", [True, False]) + @pytest.mark.parametrize("lhs", [True, False]) + @pytest.mark.parametrize("op", expr.BOOL_OPS_SYMS) + def test_bool_ops_with_constants(self, rhs, lhs, op): + ex = f"{lhs} {op} {rhs}" + res = self.eval(ex) + exp = eval(ex) + assert res == exp def test_4d_ndarray_fails(self): x = randn(3, 4, 5, 6) @@ -1630,16 +1622,10 @@ def test_simple_in_ops(self): @td.skip_if_no_ne class TestOperationsNumExprPython(TestOperationsNumExprPandas): - @classmethod - def setup_class(cls): - super().setup_class() - cls.engine = "numexpr" - cls.parser = "python" - cls.arith_ops = [ - op - for op in expr.ARITH_OPS_SYMS + expr.CMP_OPS_SYMS - if op not in ("in", "not in") - ] + exclude_arith: List[str] = ["in", "not in"] + + engine = "numexpr" + parser = "python" def test_check_many_exprs(self): a = 1 # noqa @@ -1695,66 +1681,51 @@ def test_fails_pipe(self): with pytest.raises(NotImplementedError, match=msg): pd.eval(ex, parser=self.parser, engine=self.engine) - def test_bool_ops_with_constants(self): - for op, lhs, rhs in product( - expr.BOOL_OPS_SYMS, ("True", "False"), ("True", "False") - ): - ex = f"{lhs} {op} {rhs}" - if op in ("and", "or"): - msg = "'BoolOp' nodes are not implemented" - with pytest.raises(NotImplementedError, match=msg): - self.eval(ex) - else: - res = self.eval(ex) - exp = eval(ex) - assert res == exp - - def test_simple_bool_ops(self): - for op, lhs, rhs in product(expr.BOOL_OPS_SYMS, (True, False), (True, False)): - ex = f"lhs {op} rhs" - if op in ("and", "or"): - msg = "'BoolOp' nodes are not implemented" - with pytest.raises(NotImplementedError, match=msg): - pd.eval(ex, engine=self.engine, parser=self.parser) - else: - res = pd.eval(ex, engine=self.engine, parser=self.parser) - exp = eval(ex) - assert res == exp + @pytest.mark.parametrize("rhs", [True, False]) + @pytest.mark.parametrize("lhs", [True, False]) + @pytest.mark.parametrize("op", expr.BOOL_OPS_SYMS) + def test_bool_ops_with_constants(self, lhs, rhs, op): + ex = f"{lhs} {op} {rhs}" + if op in ("and", "or"): + msg = "'BoolOp' nodes are not implemented" + with pytest.raises(NotImplementedError, match=msg): + self.eval(ex) + else: + res = self.eval(ex) + exp = eval(ex) + assert res == exp + + @pytest.mark.parametrize("rhs", [True, False]) + @pytest.mark.parametrize("lhs", [True, False]) + @pytest.mark.parametrize("op", expr.BOOL_OPS_SYMS) + def test_simple_bool_ops(self, lhs, rhs, op): + ex = f"lhs {op} rhs" + if op in ("and", "or"): + msg = "'BoolOp' nodes are not implemented" + with pytest.raises(NotImplementedError, match=msg): + pd.eval(ex, engine=self.engine, parser=self.parser) + else: + res = pd.eval(ex, engine=self.engine, parser=self.parser) + exp = eval(ex) + assert res == exp class TestOperationsPythonPython(TestOperationsNumExprPython): - @classmethod - def setup_class(cls): - super().setup_class() - cls.engine = cls.parser = "python" - cls.arith_ops = [ - op - for op in expr.ARITH_OPS_SYMS + expr.CMP_OPS_SYMS - if op not in ("in", "not in") - ] + engine = "python" + parser = "python" class TestOperationsPythonPandas(TestOperationsNumExprPandas): - @classmethod - def setup_class(cls): - super().setup_class() - cls.engine = "python" - cls.parser = "pandas" - cls.arith_ops = expr.ARITH_OPS_SYMS + expr.CMP_OPS_SYMS + exclude_arith: List[str] = [] + + engine = "python" + parser = "pandas" @td.skip_if_no_ne class TestMathPythonPython: - @classmethod - def setup_class(cls): - cls.engine = "python" - cls.parser = "pandas" - cls.unary_fns = _unary_math_ops - cls.binary_fns = _binary_math_ops - - @classmethod - def teardown_class(cls): - del cls.engine, cls.parser + engine = "python" + parser = "pandas" def eval(self, *args, **kwargs): kwargs["engine"] = self.engine @@ -1766,30 +1737,32 @@ def test_unary_functions(self, unary_fns_for_ne): df = DataFrame({"a": np.random.randn(10)}) a = df.a - for fn in unary_fns_for_ne: - expr = f"{fn}(a)" - got = self.eval(expr) - with np.errstate(all="ignore"): - expect = getattr(np, fn)(a) - tm.assert_series_equal(got, expect, check_names=False) + fn = unary_fns_for_ne - def test_floor_and_ceil_functions_raise_error(self, ne_lt_2_6_9, unary_fns_for_ne): - for fn in ("floor", "ceil"): - msg = f'"{fn}" is not a supported function' - with pytest.raises(ValueError, match=msg): - expr = f"{fn}(100)" - self.eval(expr) + expr = f"{fn}(a)" + got = self.eval(expr) + with np.errstate(all="ignore"): + expect = getattr(np, fn)(a) + tm.assert_series_equal(got, expect, check_names=False) + + @pytest.mark.parametrize("fn", ["floor", "ceil"]) + def test_floor_and_ceil_functions_raise_error(self, ne_lt_2_6_9, fn): + msg = f'"{fn}" is not a supported function' + with pytest.raises(ValueError, match=msg): + expr = f"{fn}(100)" + self.eval(expr) - def test_binary_functions(self): + @pytest.mark.parametrize("fn", _binary_math_ops) + def test_binary_functions(self, fn): df = DataFrame({"a": np.random.randn(10), "b": np.random.randn(10)}) a = df.a b = df.b - for fn in self.binary_fns: - expr = f"{fn}(a, b)" - got = self.eval(expr) - with np.errstate(all="ignore"): - expect = getattr(np, fn)(a, b) - tm.assert_almost_equal(got, expect, check_names=False) + + expr = f"{fn}(a, b)" + got = self.eval(expr) + with np.errstate(all="ignore"): + expect = getattr(np, fn)(a, b) + tm.assert_almost_equal(got, expect, check_names=False) def test_df_use_case(self): df = DataFrame({"a": np.random.randn(10), "b": np.random.randn(10)}) @@ -1851,27 +1824,18 @@ def test_keyword_arg(self): class TestMathPythonPandas(TestMathPythonPython): - @classmethod - def setup_class(cls): - super().setup_class() - cls.engine = "python" - cls.parser = "pandas" + engine = "python" + parser = "pandas" class TestMathNumExprPandas(TestMathPythonPython): - @classmethod - def setup_class(cls): - super().setup_class() - cls.engine = "numexpr" - cls.parser = "pandas" + engine = "numexpr" + parser = "pandas" class TestMathNumExprPython(TestMathPythonPython): - @classmethod - def setup_class(cls): - super().setup_class() - cls.engine = "numexpr" - cls.parser = "python" + engine = "numexpr" + parser = "python" _var_s = randn(10) @@ -1925,10 +1889,10 @@ def test_invalid_parser(): @pytest.mark.parametrize("parser", _parsers) def test_disallowed_nodes(engine, parser): VisitorClass = _parsers[parser] - uns_ops = VisitorClass.unsupported_nodes inst = VisitorClass("x + 1", engine, parser) - for ops in uns_ops: + for ops in VisitorClass.unsupported_nodes: + msg = "nodes are not implemented" with pytest.raises(NotImplementedError, match=msg): getattr(inst, ops)() @@ -1947,17 +1911,16 @@ def test_name_error_exprs(engine, parser): pd.eval(e, engine=engine, parser=parser) -def test_invalid_local_variable_reference(engine, parser): +@pytest.mark.parametrize("express", ["a + @b", "@a + b", "@a + @b"]) +def test_invalid_local_variable_reference(engine, parser, express): a, b = 1, 2 # noqa - exprs = "a + @b", "@a + b", "@a + @b" - for _expr in exprs: - if parser != "pandas": - with pytest.raises(SyntaxError, match="The '@' prefix is only"): - pd.eval(_expr, engine=engine, parser=parser) - else: - with pytest.raises(SyntaxError, match="The '@' prefix is not"): - pd.eval(_expr, engine=engine, parser=parser) + if parser != "pandas": + with pytest.raises(SyntaxError, match="The '@' prefix is only"): + pd.eval(express, engine=engine, parser=parser) + else: + with pytest.raises(SyntaxError, match="The '@' prefix is not"): + pd.eval(express, engine=engine, parser=parser) def test_numexpr_builtin_raises(engine, parser): @@ -2068,10 +2031,9 @@ def test_negate_lt_eq_le(engine, parser): class TestValidate: - def test_validate_bool_args(self): - invalid_values = [1, "True", [1, 2, 3], 5.0] + @pytest.mark.parametrize("value", [1, "True", [1, 2, 3], 5.0]) + def test_validate_bool_args(self, value): - for value in invalid_values: - msg = 'For argument "inplace" expected type bool, received type' - with pytest.raises(ValueError, match=msg): - pd.eval("2+2", inplace=value) + msg = 'For argument "inplace" expected type bool, received type' + with pytest.raises(ValueError, match=msg): + pd.eval("2+2", inplace=value)
Might help us track down the failing test there.
https://api.github.com/repos/pandas-dev/pandas/pulls/37349
2020-10-22T21:19:39Z
2020-10-22T23:30:07Z
2020-10-22T23:30:07Z
2020-10-22T23:50:18Z
TST/REF: collect tests by method
diff --git a/pandas/conftest.py b/pandas/conftest.py index 5a4bc397ab792..515d20e8c5781 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -34,7 +34,7 @@ import pandas.util._test_decorators as td import pandas as pd -from pandas import DataFrame +from pandas import DataFrame, Series import pandas._testing as tm from pandas.core import ops from pandas.core.indexes.api import Index, MultiIndex @@ -529,6 +529,23 @@ def series_with_simple_index(index): return _create_series(index) +@pytest.fixture +def series_with_multilevel_index(): + """ + Fixture with a Series with a 2-level MultiIndex. + """ + arrays = [ + ["bar", "bar", "baz", "baz", "qux", "qux", "foo", "foo"], + ["one", "two", "one", "two", "one", "two", "one", "two"], + ] + tuples = zip(*arrays) + index = MultiIndex.from_tuples(tuples) + data = np.random.randn(8) + ser = Series(data, index=index) + ser[3] = np.NaN + return ser + + _narrow_dtypes = [ np.float16, np.float32, diff --git a/pandas/tests/frame/methods/test_count.py b/pandas/tests/frame/methods/test_count.py index 6d4ce3fa0dd4e..d738c7139093c 100644 --- a/pandas/tests/frame/methods/test_count.py +++ b/pandas/tests/frame/methods/test_count.py @@ -6,6 +6,24 @@ class TestDataFrameCount: + def test_count_multiindex(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + + frame = frame.copy() + frame.index.names = ["a", "b"] + + result = frame.count(level="b") + expected = frame.count(level=1) + tm.assert_frame_equal(result, expected, check_names=False) + + result = frame.count(level="a") + expected = frame.count(level=0) + tm.assert_frame_equal(result, expected, check_names=False) + + msg = "Level x not found" + with pytest.raises(KeyError, match=msg): + frame.count(level="x") + def test_count(self): # corner case frame = DataFrame() diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index b88ef0e6691cb..ca4eeaf9ac807 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -1,8 +1,11 @@ from datetime import datetime +from itertools import product import numpy as np import pytest +from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype + import pandas as pd from pandas import ( DataFrame, @@ -301,6 +304,194 @@ def test_reset_index_range(self): ) tm.assert_frame_equal(result, expected) + def test_reset_index_multiindex_columns(self): + levels = [["A", ""], ["B", "b"]] + df = DataFrame([[0, 2], [1, 3]], columns=MultiIndex.from_tuples(levels)) + result = df[["B"]].rename_axis("A").reset_index() + tm.assert_frame_equal(result, df) + + # GH#16120: already existing column + msg = r"cannot insert \('A', ''\), already exists" + with pytest.raises(ValueError, match=msg): + df.rename_axis("A").reset_index() + + # GH#16164: multiindex (tuple) full key + result = df.set_index([("A", "")]).reset_index() + tm.assert_frame_equal(result, df) + + # with additional (unnamed) index level + idx_col = DataFrame( + [[0], [1]], columns=MultiIndex.from_tuples([("level_0", "")]) + ) + expected = pd.concat([idx_col, df[[("B", "b"), ("A", "")]]], axis=1) + result = df.set_index([("B", "b")], append=True).reset_index() + tm.assert_frame_equal(result, expected) + + # with index name which is a too long tuple... + msg = "Item must have length equal to number of levels." + with pytest.raises(ValueError, match=msg): + df.rename_axis([("C", "c", "i")]).reset_index() + + # or too short... + levels = [["A", "a", ""], ["B", "b", "i"]] + df2 = DataFrame([[0, 2], [1, 3]], columns=MultiIndex.from_tuples(levels)) + idx_col = DataFrame( + [[0], [1]], columns=MultiIndex.from_tuples([("C", "c", "ii")]) + ) + expected = pd.concat([idx_col, df2], axis=1) + result = df2.rename_axis([("C", "c")]).reset_index(col_fill="ii") + tm.assert_frame_equal(result, expected) + + # ... which is incompatible with col_fill=None + with pytest.raises( + ValueError, + match=( + "col_fill=None is incompatible with " + r"incomplete column name \('C', 'c'\)" + ), + ): + df2.rename_axis([("C", "c")]).reset_index(col_fill=None) + + # with col_level != 0 + result = df2.rename_axis([("c", "ii")]).reset_index(col_level=1, col_fill="C") + tm.assert_frame_equal(result, expected) + + def test_reset_index_datetime(self, tz_naive_fixture): + # GH#3950 + tz = tz_naive_fixture + idx1 = pd.date_range("1/1/2011", periods=5, freq="D", tz=tz, name="idx1") + idx2 = Index(range(5), name="idx2", dtype="int64") + idx = MultiIndex.from_arrays([idx1, idx2]) + df = DataFrame( + {"a": np.arange(5, dtype="int64"), "b": ["A", "B", "C", "D", "E"]}, + index=idx, + ) + + expected = DataFrame( + { + "idx1": [ + datetime(2011, 1, 1), + datetime(2011, 1, 2), + datetime(2011, 1, 3), + datetime(2011, 1, 4), + datetime(2011, 1, 5), + ], + "idx2": np.arange(5, dtype="int64"), + "a": np.arange(5, dtype="int64"), + "b": ["A", "B", "C", "D", "E"], + }, + columns=["idx1", "idx2", "a", "b"], + ) + expected["idx1"] = expected["idx1"].apply(lambda d: Timestamp(d, tz=tz)) + + tm.assert_frame_equal(df.reset_index(), expected) + + idx3 = pd.date_range( + "1/1/2012", periods=5, freq="MS", tz="Europe/Paris", name="idx3" + ) + idx = MultiIndex.from_arrays([idx1, idx2, idx3]) + df = DataFrame( + {"a": np.arange(5, dtype="int64"), "b": ["A", "B", "C", "D", "E"]}, + index=idx, + ) + + expected = DataFrame( + { + "idx1": [ + datetime(2011, 1, 1), + datetime(2011, 1, 2), + datetime(2011, 1, 3), + datetime(2011, 1, 4), + datetime(2011, 1, 5), + ], + "idx2": np.arange(5, dtype="int64"), + "idx3": [ + datetime(2012, 1, 1), + datetime(2012, 2, 1), + datetime(2012, 3, 1), + datetime(2012, 4, 1), + datetime(2012, 5, 1), + ], + "a": np.arange(5, dtype="int64"), + "b": ["A", "B", "C", "D", "E"], + }, + columns=["idx1", "idx2", "idx3", "a", "b"], + ) + expected["idx1"] = expected["idx1"].apply(lambda d: Timestamp(d, tz=tz)) + expected["idx3"] = expected["idx3"].apply( + lambda d: Timestamp(d, tz="Europe/Paris") + ) + tm.assert_frame_equal(df.reset_index(), expected) + + # GH#7793 + idx = MultiIndex.from_product( + [["a", "b"], pd.date_range("20130101", periods=3, tz=tz)] + ) + df = DataFrame( + np.arange(6, dtype="int64").reshape(6, 1), columns=["a"], index=idx + ) + + expected = DataFrame( + { + "level_0": "a a a b b b".split(), + "level_1": [ + datetime(2013, 1, 1), + datetime(2013, 1, 2), + datetime(2013, 1, 3), + ] + * 2, + "a": np.arange(6, dtype="int64"), + }, + columns=["level_0", "level_1", "a"], + ) + expected["level_1"] = expected["level_1"].apply( + lambda d: Timestamp(d, freq="D", tz=tz) + ) + result = df.reset_index() + tm.assert_frame_equal(result, expected) + + def test_reset_index_period(self): + # GH#7746 + idx = MultiIndex.from_product( + [pd.period_range("20130101", periods=3, freq="M"), list("abc")], + names=["month", "feature"], + ) + + df = DataFrame( + np.arange(9, dtype="int64").reshape(-1, 1), index=idx, columns=["a"] + ) + expected = DataFrame( + { + "month": ( + [pd.Period("2013-01", freq="M")] * 3 + + [pd.Period("2013-02", freq="M")] * 3 + + [pd.Period("2013-03", freq="M")] * 3 + ), + "feature": ["a", "b", "c"] * 3, + "a": np.arange(9, dtype="int64"), + }, + columns=["month", "feature", "a"], + ) + result = df.reset_index() + tm.assert_frame_equal(result, expected) + + def test_reset_index_delevel_infer_dtype(self): + tuples = list(product(["foo", "bar"], [10, 20], [1.0, 1.1])) + index = MultiIndex.from_tuples(tuples, names=["prm0", "prm1", "prm2"]) + df = DataFrame(np.random.randn(8, 3), columns=["A", "B", "C"], index=index) + deleveled = df.reset_index() + assert is_integer_dtype(deleveled["prm1"]) + assert is_float_dtype(deleveled["prm2"]) + + def test_reset_index_with_drop( + self, multiindex_year_month_day_dataframe_random_data + ): + ymd = multiindex_year_month_day_dataframe_random_data + + deleveled = ymd.reset_index(drop=True) + assert len(deleveled.columns) == len(ymd.columns) + assert deleveled.index.name == ymd.index.name + @pytest.mark.parametrize( "array, dtype", diff --git a/pandas/tests/frame/methods/test_set_index.py b/pandas/tests/frame/methods/test_set_index.py index 8927ab7c5ef79..29cd3c2d535d9 100644 --- a/pandas/tests/frame/methods/test_set_index.py +++ b/pandas/tests/frame/methods/test_set_index.py @@ -17,6 +17,17 @@ class TestSetIndex: + def test_set_index_multiindex(self): + # segfault in GH#3308 + d = {"t1": [2, 2.5, 3], "t2": [4, 5, 6]} + df = DataFrame(d) + tuples = [(0, 1), (0, 2), (1, 2)] + df["tuples"] = tuples + + index = MultiIndex.from_tuples(df["tuples"]) + # it works! + df.set_index(index) + def test_set_index_empty_column(self): # GH#1971 df = DataFrame( diff --git a/pandas/tests/frame/methods/test_sort_index.py b/pandas/tests/frame/methods/test_sort_index.py index 58260f3613b5e..50d643cf83d7f 100644 --- a/pandas/tests/frame/methods/test_sort_index.py +++ b/pandas/tests/frame/methods/test_sort_index.py @@ -2,7 +2,15 @@ import pytest import pandas as pd -from pandas import CategoricalDtype, DataFrame, Index, IntervalIndex, MultiIndex, Series +from pandas import ( + CategoricalDtype, + DataFrame, + Index, + IntervalIndex, + MultiIndex, + Series, + Timestamp, +) import pandas._testing as tm @@ -668,6 +676,66 @@ def test_sort_index_preserve_levels(self, multiindex_dataframe_random_data): result = frame.sort_index() assert result.index.names == frame.index.names + @pytest.mark.parametrize( + "gen,extra", + [ + ([1.0, 3.0, 2.0, 5.0], 4.0), + ([1, 3, 2, 5], 4), + ( + [ + Timestamp("20130101"), + Timestamp("20130103"), + Timestamp("20130102"), + Timestamp("20130105"), + ], + Timestamp("20130104"), + ), + (["1one", "3one", "2one", "5one"], "4one"), + ], + ) + def test_sort_index_multilevel_repr_8017(self, gen, extra): + + np.random.seed(0) + data = np.random.randn(3, 4) + + columns = MultiIndex.from_tuples([("red", i) for i in gen]) + df = DataFrame(data, index=list("def"), columns=columns) + df2 = pd.concat( + [ + df, + DataFrame( + "world", + index=list("def"), + columns=MultiIndex.from_tuples([("red", extra)]), + ), + ], + axis=1, + ) + + # check that the repr is good + # make sure that we have a correct sparsified repr + # e.g. only 1 header of read + assert str(df2).splitlines()[0].split() == ["red"] + + # GH 8017 + # sorting fails after columns added + + # construct single-dtype then sort + result = df.copy().sort_index(axis=1) + expected = df.iloc[:, [0, 2, 1, 3]] + tm.assert_frame_equal(result, expected) + + result = df2.sort_index(axis=1) + expected = df2.iloc[:, [0, 2, 1, 4, 3]] + tm.assert_frame_equal(result, expected) + + # setitem then sort + result = df.copy() + result[("red", extra)] = "world" + + result = result.sort_index(axis=1) + tm.assert_frame_equal(result, expected) + class TestDataFrameSortIndexKey: def test_sort_multi_index_key(self): diff --git a/pandas/tests/frame/methods/test_swaplevel.py b/pandas/tests/frame/methods/test_swaplevel.py new file mode 100644 index 0000000000000..5511ac7d6b1b2 --- /dev/null +++ b/pandas/tests/frame/methods/test_swaplevel.py @@ -0,0 +1,36 @@ +import pytest + +from pandas import DataFrame +import pandas._testing as tm + + +class TestSwaplevel: + def test_swaplevel(self, multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + + swapped = frame["A"].swaplevel() + swapped2 = frame["A"].swaplevel(0) + swapped3 = frame["A"].swaplevel(0, 1) + swapped4 = frame["A"].swaplevel("first", "second") + assert not swapped.index.equals(frame.index) + tm.assert_series_equal(swapped, swapped2) + tm.assert_series_equal(swapped, swapped3) + tm.assert_series_equal(swapped, swapped4) + + back = swapped.swaplevel() + back2 = swapped.swaplevel(0) + back3 = swapped.swaplevel(0, 1) + back4 = swapped.swaplevel("second", "first") + assert back.index.equals(frame.index) + tm.assert_series_equal(back, back2) + tm.assert_series_equal(back, back3) + tm.assert_series_equal(back, back4) + + ft = frame.T + swapped = ft.swaplevel("first", "second", axis=1) + exp = frame.swaplevel("first", "second").T + tm.assert_frame_equal(swapped, exp) + + msg = "Can only swap levels on a hierarchical axis." + with pytest.raises(TypeError, match=msg): + DataFrame(range(3)).swaplevel() diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index acc87defb568c..25795c242528c 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -1561,6 +1561,19 @@ def test_constructor_from_dict_tuples(self, data_dict, keys, orient): tm.assert_index_equal(result, expected) + def test_frame_dict_constructor_empty_series(self): + s1 = Series( + [1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (2, 2), (2, 4)]) + ) + s2 = Series( + [1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (3, 2), (3, 4)]) + ) + s3 = Series(dtype=object) + + # it works! + DataFrame({"foo": s1, "bar": s2, "baz": s3}) + DataFrame.from_dict({"foo": s1, "baz": s3, "bar": s2}) + def test_constructor_Series_named(self): a = Series([1, 2, 3], index=["a", "b", "c"], name="x") df = DataFrame(a) diff --git a/pandas/tests/frame/test_repr_info.py b/pandas/tests/frame/test_repr_info.py index 641331d73ff7a..16d223048e374 100644 --- a/pandas/tests/frame/test_repr_info.py +++ b/pandas/tests/frame/test_repr_info.py @@ -8,6 +8,7 @@ from pandas import ( Categorical, DataFrame, + MultiIndex, PeriodIndex, Series, date_range, @@ -20,6 +21,66 @@ class TestDataFrameReprInfoEtc: + def test_assign_index_sequences(self): + # GH#2200 + df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}).set_index( + ["a", "b"] + ) + index = list(df.index) + index[0] = ("faz", "boo") + df.index = index + repr(df) + + # this travels an improper code path + index[0] = ["faz", "boo"] + df.index = index + repr(df) + + def test_multiindex_na_repr(self): + # only an issue with long columns + df3 = DataFrame( + { + "A" * 30: {("A", "A0006000", "nuit"): "A0006000"}, + "B" * 30: {("A", "A0006000", "nuit"): np.nan}, + "C" * 30: {("A", "A0006000", "nuit"): np.nan}, + "D" * 30: {("A", "A0006000", "nuit"): np.nan}, + "E" * 30: {("A", "A0006000", "nuit"): "A"}, + "F" * 30: {("A", "A0006000", "nuit"): np.nan}, + } + ) + + idf = df3.set_index(["A" * 30, "C" * 30]) + repr(idf) + + def test_repr_name_coincide(self): + index = MultiIndex.from_tuples( + [("a", 0, "foo"), ("b", 1, "bar")], names=["a", "b", "c"] + ) + + df = DataFrame({"value": [0, 1]}, index=index) + + lines = repr(df).split("\n") + assert lines[2].startswith("a 0 foo") + + def test_repr_to_string( + self, + multiindex_year_month_day_dataframe_random_data, + multiindex_dataframe_random_data, + ): + ymd = multiindex_year_month_day_dataframe_random_data + frame = multiindex_dataframe_random_data + + repr(frame) + repr(ymd) + repr(frame.T) + repr(ymd.T) + + buf = StringIO() + frame.to_string(buf=buf) + ymd.to_string(buf=buf) + frame.T.to_string(buf=buf) + ymd.T.to_string(buf=buf) + def test_repr_empty(self): # empty repr(DataFrame()) diff --git a/pandas/tests/indexes/multi/test_get_set.py b/pandas/tests/indexes/multi/test_get_set.py index b9132f429905d..6f79878fd3ab1 100644 --- a/pandas/tests/indexes/multi/test_get_set.py +++ b/pandas/tests/indexes/multi/test_get_set.py @@ -27,6 +27,15 @@ def test_get_level_number_integer(idx): idx._get_level_number("fourth") +def test_get_level_number_out_of_bounds(multiindex_dataframe_random_data): + frame = multiindex_dataframe_random_data + + with pytest.raises(IndexError, match="Too many levels"): + frame.index._get_level_number(2) + with pytest.raises(IndexError, match="not a valid level number"): + frame.index._get_level_number(-3) + + def test_set_name_methods(idx, index_names): # so long as these are synonyms, we don't need to test set_names assert idx.rename == idx.set_names diff --git a/pandas/tests/series/methods/test_count.py b/pandas/tests/series/methods/test_count.py index 3c5957706b144..df1babbee8e18 100644 --- a/pandas/tests/series/methods/test_count.py +++ b/pandas/tests/series/methods/test_count.py @@ -7,6 +7,24 @@ class TestSeriesCount: + def test_count_multiindex(self, series_with_multilevel_index): + ser = series_with_multilevel_index + + series = ser.copy() + series.index.names = ["a", "b"] + + result = series.count(level="b") + expect = ser.count(level=1).rename_axis("b") + tm.assert_series_equal(result, expect) + + result = series.count(level="a") + expect = ser.count(level=0).rename_axis("a") + tm.assert_series_equal(result, expect) + + msg = "Level x not found" + with pytest.raises(KeyError, match=msg): + series.count("x") + def test_count_level_without_multiindex(self): ser = Series(range(3)) diff --git a/pandas/tests/series/methods/test_reset_index.py b/pandas/tests/series/methods/test_reset_index.py index 1474bb95f4af2..13d6a3b1447a1 100644 --- a/pandas/tests/series/methods/test_reset_index.py +++ b/pandas/tests/series/methods/test_reset_index.py @@ -111,6 +111,18 @@ def test_reset_index_drop_errors(self): with pytest.raises(KeyError, match="not found"): s.reset_index("wrong", drop=True) + def test_reset_index_with_drop(self, series_with_multilevel_index): + ser = series_with_multilevel_index + + deleveled = ser.reset_index() + assert isinstance(deleveled, DataFrame) + assert len(deleveled.columns) == len(ser.index.levels) + 1 + assert deleveled.index.name == ser.index.name + + deleveled = ser.reset_index(drop=True) + assert isinstance(deleveled, Series) + assert deleveled.index.name == ser.index.name + @pytest.mark.parametrize( "array, dtype", diff --git a/pandas/tests/test_multilevel.py b/pandas/tests/test_multilevel.py index f3d1f949c1475..8b8e49d914905 100644 --- a/pandas/tests/test_multilevel.py +++ b/pandas/tests/test_multilevel.py @@ -1,15 +1,8 @@ -import datetime -from io import StringIO -from itertools import product - import numpy as np -from numpy.random import randn import pytest -from pandas.core.dtypes.common import is_float_dtype, is_integer_dtype - import pandas as pd -from pandas import DataFrame, Index, MultiIndex, Series, Timestamp +from pandas import DataFrame, MultiIndex, Series import pandas._testing as tm AGG_FUNCTIONS = [ @@ -27,22 +20,7 @@ ] -class Base: - def setup_method(self, method): - - # create test series object - arrays = [ - ["bar", "bar", "baz", "baz", "qux", "qux", "foo", "foo"], - ["one", "two", "one", "two", "one", "two", "one", "two"], - ] - tuples = zip(*arrays) - index = MultiIndex.from_tuples(tuples) - s = Series(randn(8), index=index) - s[3] = np.NaN - self.series = s - - -class TestMultiLevel(Base): +class TestMultiLevel: def test_append(self, multiindex_dataframe_random_data): frame = multiindex_dataframe_random_data @@ -168,61 +146,6 @@ def test_reindex_preserve_levels( chunk = ymdT.loc[:, new_index] assert chunk.columns is new_index - def test_repr_to_string( - self, - multiindex_year_month_day_dataframe_random_data, - multiindex_dataframe_random_data, - ): - ymd = multiindex_year_month_day_dataframe_random_data - frame = multiindex_dataframe_random_data - - repr(frame) - repr(ymd) - repr(frame.T) - repr(ymd.T) - - buf = StringIO() - frame.to_string(buf=buf) - ymd.to_string(buf=buf) - frame.T.to_string(buf=buf) - ymd.T.to_string(buf=buf) - - def test_repr_name_coincide(self): - index = MultiIndex.from_tuples( - [("a", 0, "foo"), ("b", 1, "bar")], names=["a", "b", "c"] - ) - - df = DataFrame({"value": [0, 1]}, index=index) - - lines = repr(df).split("\n") - assert lines[2].startswith("a 0 foo") - - def test_delevel_infer_dtype(self): - tuples = list(product(["foo", "bar"], [10, 20], [1.0, 1.1])) - index = MultiIndex.from_tuples(tuples, names=["prm0", "prm1", "prm2"]) - df = DataFrame(np.random.randn(8, 3), columns=["A", "B", "C"], index=index) - deleveled = df.reset_index() - assert is_integer_dtype(deleveled["prm1"]) - assert is_float_dtype(deleveled["prm2"]) - - def test_reset_index_with_drop( - self, multiindex_year_month_day_dataframe_random_data - ): - ymd = multiindex_year_month_day_dataframe_random_data - - deleveled = ymd.reset_index(drop=True) - assert len(deleveled.columns) == len(ymd.columns) - assert deleveled.index.name == ymd.index.name - - deleveled = self.series.reset_index() - assert isinstance(deleveled, DataFrame) - assert len(deleveled.columns) == len(self.series.index.levels) + 1 - assert deleveled.index.name == self.series.index.name - - deleveled = self.series.reset_index(drop=True) - assert isinstance(deleveled, Series) - assert deleveled.index.name == self.series.index.name - def test_count_level_series(self): index = MultiIndex( levels=[["foo", "bar", "baz"], ["one", "two", "three", "four"]], @@ -243,14 +166,6 @@ def test_count_level_series(self): result.astype("f8"), expected.reindex(result.index).fillna(0) ) - def test_get_level_number_out_of_bounds(self, multiindex_dataframe_random_data): - frame = multiindex_dataframe_random_data - - with pytest.raises(IndexError, match="Too many levels"): - frame.index._get_level_number(2) - with pytest.raises(IndexError, match="not a valid level number"): - frame.index._get_level_number(-3) - def test_unused_level_raises(self): # GH 20410 mi = MultiIndex( @@ -319,36 +234,6 @@ def test_join(self, multiindex_dataframe_random_data): # TODO what should join do with names ? tm.assert_frame_equal(joined, expected, check_names=False) - def test_swaplevel(self, multiindex_dataframe_random_data): - frame = multiindex_dataframe_random_data - - swapped = frame["A"].swaplevel() - swapped2 = frame["A"].swaplevel(0) - swapped3 = frame["A"].swaplevel(0, 1) - swapped4 = frame["A"].swaplevel("first", "second") - assert not swapped.index.equals(frame.index) - tm.assert_series_equal(swapped, swapped2) - tm.assert_series_equal(swapped, swapped3) - tm.assert_series_equal(swapped, swapped4) - - back = swapped.swaplevel() - back2 = swapped.swaplevel(0) - back3 = swapped.swaplevel(0, 1) - back4 = swapped.swaplevel("second", "first") - assert back.index.equals(frame.index) - tm.assert_series_equal(back, back2) - tm.assert_series_equal(back, back3) - tm.assert_series_equal(back, back4) - - ft = frame.T - swapped = ft.swaplevel("first", "second", axis=1) - exp = frame.swaplevel("first", "second").T - tm.assert_frame_equal(swapped, exp) - - msg = "Can only swap levels on a hierarchical axis." - with pytest.raises(TypeError, match=msg): - DataFrame(range(3)).swaplevel() - def test_insert_index(self, multiindex_year_month_day_dataframe_random_data): ymd = multiindex_year_month_day_dataframe_random_data @@ -377,47 +262,20 @@ def test_alignment(self): exp = x.reindex(exp_index) - y.reindex(exp_index) tm.assert_series_equal(res, exp) - def test_count(self, multiindex_dataframe_random_data): - frame = multiindex_dataframe_random_data - - frame = frame.copy() - frame.index.names = ["a", "b"] - - result = frame.count(level="b") - expect = frame.count(level=1) - tm.assert_frame_equal(result, expect, check_names=False) - - result = frame.count(level="a") - expect = frame.count(level=0) - tm.assert_frame_equal(result, expect, check_names=False) - - series = self.series.copy() - series.index.names = ["a", "b"] - - result = series.count(level="b") - expect = self.series.count(level=1).rename_axis("b") - tm.assert_series_equal(result, expect) - - result = series.count(level="a") - expect = self.series.count(level=0).rename_axis("a") - tm.assert_series_equal(result, expect) - - msg = "Level x not found" - with pytest.raises(KeyError, match=msg): - series.count("x") - with pytest.raises(KeyError, match=msg): - frame.count(level="x") - @pytest.mark.parametrize("op", AGG_FUNCTIONS) @pytest.mark.parametrize("level", [0, 1]) @pytest.mark.parametrize("skipna", [True, False]) @pytest.mark.parametrize("sort", [True, False]) - def test_series_group_min_max(self, op, level, skipna, sort): + def test_series_group_min_max( + self, op, level, skipna, sort, series_with_multilevel_index + ): # GH 17537 - grouped = self.series.groupby(level=level, sort=sort) + ser = series_with_multilevel_index + + grouped = ser.groupby(level=level, sort=sort) # skipna=True leftside = grouped.agg(lambda x: getattr(x, op)(skipna=skipna)) - rightside = getattr(self.series, op)(level=level, skipna=skipna) + rightside = getattr(ser, op)(level=level, skipna=skipna) if sort: rightside = rightside.sort_index(level=level) tm.assert_series_equal(leftside, rightside) @@ -636,19 +494,6 @@ def test_join_segfault(self): for how in ["left", "right", "outer"]: df1.join(df2, how=how) - def test_frame_dict_constructor_empty_series(self): - s1 = Series( - [1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (2, 2), (2, 4)]) - ) - s2 = Series( - [1, 2, 3, 4], index=MultiIndex.from_tuples([(1, 2), (1, 3), (3, 2), (3, 4)]) - ) - s3 = Series(dtype=object) - - # it works! - DataFrame({"foo": s1, "bar": s2, "baz": s3}) - DataFrame.from_dict({"foo": s1, "baz": s3, "bar": s2}) - @pytest.mark.parametrize("d", [4, "d"]) def test_empty_frame_groupby_dtypes_consistency(self, d): # GH 20888 @@ -663,37 +508,6 @@ def test_empty_frame_groupby_dtypes_consistency(self, d): tm.assert_index_equal(result, expected) - def test_multiindex_na_repr(self): - # only an issue with long columns - df3 = DataFrame( - { - "A" * 30: {("A", "A0006000", "nuit"): "A0006000"}, - "B" * 30: {("A", "A0006000", "nuit"): np.nan}, - "C" * 30: {("A", "A0006000", "nuit"): np.nan}, - "D" * 30: {("A", "A0006000", "nuit"): np.nan}, - "E" * 30: {("A", "A0006000", "nuit"): "A"}, - "F" * 30: {("A", "A0006000", "nuit"): np.nan}, - } - ) - - idf = df3.set_index(["A" * 30, "C" * 30]) - repr(idf) - - def test_assign_index_sequences(self): - # #2200 - df = DataFrame({"a": [1, 2, 3], "b": [4, 5, 6], "c": [7, 8, 9]}).set_index( - ["a", "b"] - ) - index = list(df.index) - index[0] = ("faz", "boo") - df.index = index - repr(df) - - # this travels an improper code path - index[0] = ["faz", "boo"] - df.index = index - repr(df) - def test_duplicate_groupby_issues(self): idx_tp = [ ("600809", "20061231"), @@ -731,186 +545,6 @@ def test_duplicate_mi(self): result = df.loc[("foo", "bar")] tm.assert_frame_equal(result, expected) - def test_multiindex_set_index(self): - # segfault in #3308 - d = {"t1": [2, 2.5, 3], "t2": [4, 5, 6]} - df = DataFrame(d) - tuples = [(0, 1), (0, 2), (1, 2)] - df["tuples"] = tuples - - index = MultiIndex.from_tuples(df["tuples"]) - # it works! - df.set_index(index) - - def test_reset_index_datetime(self, tz_naive_fixture): - # GH 3950 - tz = tz_naive_fixture - idx1 = pd.date_range("1/1/2011", periods=5, freq="D", tz=tz, name="idx1") - idx2 = Index(range(5), name="idx2", dtype="int64") - idx = MultiIndex.from_arrays([idx1, idx2]) - df = DataFrame( - {"a": np.arange(5, dtype="int64"), "b": ["A", "B", "C", "D", "E"]}, - index=idx, - ) - - expected = DataFrame( - { - "idx1": [ - datetime.datetime(2011, 1, 1), - datetime.datetime(2011, 1, 2), - datetime.datetime(2011, 1, 3), - datetime.datetime(2011, 1, 4), - datetime.datetime(2011, 1, 5), - ], - "idx2": np.arange(5, dtype="int64"), - "a": np.arange(5, dtype="int64"), - "b": ["A", "B", "C", "D", "E"], - }, - columns=["idx1", "idx2", "a", "b"], - ) - expected["idx1"] = expected["idx1"].apply(lambda d: Timestamp(d, tz=tz)) - - tm.assert_frame_equal(df.reset_index(), expected) - - idx3 = pd.date_range( - "1/1/2012", periods=5, freq="MS", tz="Europe/Paris", name="idx3" - ) - idx = MultiIndex.from_arrays([idx1, idx2, idx3]) - df = DataFrame( - {"a": np.arange(5, dtype="int64"), "b": ["A", "B", "C", "D", "E"]}, - index=idx, - ) - - expected = DataFrame( - { - "idx1": [ - datetime.datetime(2011, 1, 1), - datetime.datetime(2011, 1, 2), - datetime.datetime(2011, 1, 3), - datetime.datetime(2011, 1, 4), - datetime.datetime(2011, 1, 5), - ], - "idx2": np.arange(5, dtype="int64"), - "idx3": [ - datetime.datetime(2012, 1, 1), - datetime.datetime(2012, 2, 1), - datetime.datetime(2012, 3, 1), - datetime.datetime(2012, 4, 1), - datetime.datetime(2012, 5, 1), - ], - "a": np.arange(5, dtype="int64"), - "b": ["A", "B", "C", "D", "E"], - }, - columns=["idx1", "idx2", "idx3", "a", "b"], - ) - expected["idx1"] = expected["idx1"].apply(lambda d: Timestamp(d, tz=tz)) - expected["idx3"] = expected["idx3"].apply( - lambda d: Timestamp(d, tz="Europe/Paris") - ) - tm.assert_frame_equal(df.reset_index(), expected) - - # GH 7793 - idx = MultiIndex.from_product( - [["a", "b"], pd.date_range("20130101", periods=3, tz=tz)] - ) - df = DataFrame( - np.arange(6, dtype="int64").reshape(6, 1), columns=["a"], index=idx - ) - - expected = DataFrame( - { - "level_0": "a a a b b b".split(), - "level_1": [ - datetime.datetime(2013, 1, 1), - datetime.datetime(2013, 1, 2), - datetime.datetime(2013, 1, 3), - ] - * 2, - "a": np.arange(6, dtype="int64"), - }, - columns=["level_0", "level_1", "a"], - ) - expected["level_1"] = expected["level_1"].apply( - lambda d: Timestamp(d, freq="D", tz=tz) - ) - tm.assert_frame_equal(df.reset_index(), expected) - - def test_reset_index_period(self): - # GH 7746 - idx = MultiIndex.from_product( - [pd.period_range("20130101", periods=3, freq="M"), list("abc")], - names=["month", "feature"], - ) - - df = DataFrame( - np.arange(9, dtype="int64").reshape(-1, 1), index=idx, columns=["a"] - ) - expected = DataFrame( - { - "month": ( - [pd.Period("2013-01", freq="M")] * 3 - + [pd.Period("2013-02", freq="M")] * 3 - + [pd.Period("2013-03", freq="M")] * 3 - ), - "feature": ["a", "b", "c"] * 3, - "a": np.arange(9, dtype="int64"), - }, - columns=["month", "feature", "a"], - ) - tm.assert_frame_equal(df.reset_index(), expected) - - def test_reset_index_multiindex_columns(self): - levels = [["A", ""], ["B", "b"]] - df = DataFrame([[0, 2], [1, 3]], columns=MultiIndex.from_tuples(levels)) - result = df[["B"]].rename_axis("A").reset_index() - tm.assert_frame_equal(result, df) - - # gh-16120: already existing column - msg = r"cannot insert \('A', ''\), already exists" - with pytest.raises(ValueError, match=msg): - df.rename_axis("A").reset_index() - - # gh-16164: multiindex (tuple) full key - result = df.set_index([("A", "")]).reset_index() - tm.assert_frame_equal(result, df) - - # with additional (unnamed) index level - idx_col = DataFrame( - [[0], [1]], columns=MultiIndex.from_tuples([("level_0", "")]) - ) - expected = pd.concat([idx_col, df[[("B", "b"), ("A", "")]]], axis=1) - result = df.set_index([("B", "b")], append=True).reset_index() - tm.assert_frame_equal(result, expected) - - # with index name which is a too long tuple... - msg = "Item must have length equal to number of levels." - with pytest.raises(ValueError, match=msg): - df.rename_axis([("C", "c", "i")]).reset_index() - - # or too short... - levels = [["A", "a", ""], ["B", "b", "i"]] - df2 = DataFrame([[0, 2], [1, 3]], columns=MultiIndex.from_tuples(levels)) - idx_col = DataFrame( - [[0], [1]], columns=MultiIndex.from_tuples([("C", "c", "ii")]) - ) - expected = pd.concat([idx_col, df2], axis=1) - result = df2.rename_axis([("C", "c")]).reset_index(col_fill="ii") - tm.assert_frame_equal(result, expected) - - # ... which is incompatible with col_fill=None - with pytest.raises( - ValueError, - match=( - "col_fill=None is incompatible with " - r"incomplete column name \('C', 'c'\)" - ), - ): - df2.rename_axis([("C", "c")]).reset_index(col_fill=None) - - # with col_level != 0 - result = df2.rename_axis([("c", "ii")]).reset_index(col_level=1, col_fill="C") - tm.assert_frame_equal(result, expected) - def test_subsets_multiindex_dtype(self): # GH 20757 data = [["x", 1]] @@ -921,69 +555,9 @@ def test_subsets_multiindex_dtype(self): tm.assert_series_equal(result, expected) -class TestSorted(Base): +class TestSorted: """ everything you wanted to test about sorting """ - @pytest.mark.parametrize( - "gen,extra", - [ - ([1.0, 3.0, 2.0, 5.0], 4.0), - ([1, 3, 2, 5], 4), - ( - [ - Timestamp("20130101"), - Timestamp("20130103"), - Timestamp("20130102"), - Timestamp("20130105"), - ], - Timestamp("20130104"), - ), - (["1one", "3one", "2one", "5one"], "4one"), - ], - ) - def test_sorting_repr_8017(self, gen, extra): - - np.random.seed(0) - data = np.random.randn(3, 4) - - columns = MultiIndex.from_tuples([("red", i) for i in gen]) - df = DataFrame(data, index=list("def"), columns=columns) - df2 = pd.concat( - [ - df, - DataFrame( - "world", - index=list("def"), - columns=MultiIndex.from_tuples([("red", extra)]), - ), - ], - axis=1, - ) - - # check that the repr is good - # make sure that we have a correct sparsified repr - # e.g. only 1 header of read - assert str(df2).splitlines()[0].split() == ["red"] - - # GH 8017 - # sorting fails after columns added - - # construct single-dtype then sort - result = df.copy().sort_index(axis=1) - expected = df.iloc[:, [0, 2, 1, 3]] - tm.assert_frame_equal(result, expected) - - result = df2.sort_index(axis=1) - expected = df2.iloc[:, [0, 2, 1, 4, 3]] - tm.assert_frame_equal(result, expected) - - # setitem then sort - result = df.copy() - result[("red", extra)] = "world" - - result = result.sort_index(axis=1) - tm.assert_frame_equal(result, expected) - def test_sort_non_lexsorted(self): # degenerate case where we sort but don't # have a satisfying result :<
https://api.github.com/repos/pandas-dev/pandas/pulls/37342
2020-10-22T16:32:45Z
2020-10-22T22:11:21Z
2020-10-22T22:11:21Z
2020-10-22T22:18:51Z
TYP: is_dtype_compat
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index a5e8edca80873..ff014ac249fc3 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -235,20 +235,23 @@ def _shallow_copy(self, values=None, name: Label = no_default): return super()._shallow_copy(values=values, name=name) - def _is_dtype_compat(self, other) -> bool: + def _is_dtype_compat(self, other) -> Categorical: """ *this is an internal non-public method* provide a comparison between the dtype of self and other (coercing if needed) + Returns + ------- + Categorical + Raises ------ TypeError if the dtypes are not compatible """ if is_categorical_dtype(other): - if isinstance(other, CategoricalIndex): - other = other._values + other = extract_array(other) if not other.is_dtype_equal(self): raise TypeError( "categories must match existing categories when appending" @@ -263,6 +266,7 @@ def _is_dtype_compat(self, other) -> bool: raise TypeError( "cannot append a non-category item to a CategoricalIndex" ) + other = other._values return other
Broken off from #37224
https://api.github.com/repos/pandas-dev/pandas/pulls/37340
2020-10-22T15:32:20Z
2020-10-23T15:37:15Z
2020-10-23T15:37:15Z
2020-10-23T15:37:31Z
TST: parametrize slow test
diff --git a/pandas/tests/indexing/multiindex/test_indexing_slow.py b/pandas/tests/indexing/multiindex/test_indexing_slow.py index d8e56661b7d61..efe1e0f0d75b5 100644 --- a/pandas/tests/indexing/multiindex/test_indexing_slow.py +++ b/pandas/tests/indexing/multiindex/test_indexing_slow.py @@ -7,17 +7,46 @@ from pandas import DataFrame, Series import pandas._testing as tm +m = 50 +n = 1000 +cols = ["jim", "joe", "jolie", "joline", "jolia"] + +vals = [ + np.random.randint(0, 10, n), + np.random.choice(list("abcdefghij"), n), + np.random.choice(pd.date_range("20141009", periods=10).tolist(), n), + np.random.choice(list("ZYXWVUTSRQ"), n), + np.random.randn(n), +] +vals = list(map(tuple, zip(*vals))) + +# bunch of keys for testing +keys = [ + np.random.randint(0, 11, m), + np.random.choice(list("abcdefghijk"), m), + np.random.choice(pd.date_range("20141009", periods=11).tolist(), m), + np.random.choice(list("ZYXWVUTSRQP"), m), +] +keys = list(map(tuple, zip(*keys))) +keys += list(map(lambda t: t[:-1], vals[:: n // m])) + + +# covers both unique index and non-unique index +df = DataFrame(vals, columns=cols) +a = pd.concat([df, df]) +b = df.drop_duplicates(subset=cols[:-1]) + -@pytest.mark.slow @pytest.mark.filterwarnings("ignore::pandas.errors.PerformanceWarning") -def test_multiindex_get_loc(): # GH7724, GH2646 +@pytest.mark.parametrize("lexsort_depth", list(range(5))) +@pytest.mark.parametrize("key", keys) +@pytest.mark.parametrize("frame", [a, b]) +def test_multiindex_get_loc(lexsort_depth, key, frame): + # GH7724, GH2646 with warnings.catch_warnings(record=True): # test indexing into a multi-index before & past the lexsort depth - from numpy.random import choice, randint, randn - - cols = ["jim", "joe", "jolie", "joline", "jolia"] def validate(mi, df, key): mask = np.ones(len(df)).astype("bool") @@ -51,38 +80,11 @@ def validate(mi, df, key): else: # multi hit tm.assert_frame_equal(mi.loc[key[: i + 1]], right) - def loop(mi, df, keys): - for key in keys: - validate(mi, df, key) - - n, m = 1000, 50 - - vals = [ - randint(0, 10, n), - choice(list("abcdefghij"), n), - choice(pd.date_range("20141009", periods=10).tolist(), n), - choice(list("ZYXWVUTSRQ"), n), - randn(n), - ] - vals = list(map(tuple, zip(*vals))) - - # bunch of keys for testing - keys = [ - randint(0, 11, m), - choice(list("abcdefghijk"), m), - choice(pd.date_range("20141009", periods=11).tolist(), m), - choice(list("ZYXWVUTSRQP"), m), - ] - keys = list(map(tuple, zip(*keys))) - keys += list(map(lambda t: t[:-1], vals[:: n // m])) - - # covers both unique index and non-unique index - df = DataFrame(vals, columns=cols) - a, b = pd.concat([df, df]), df.drop_duplicates(subset=cols[:-1]) - - for frame in a, b: - for i in range(5): # lexsort depth - df = frame.copy() if i == 0 else frame.sort_values(by=cols[:i]) - mi = df.set_index(cols[:-1]) - assert not mi.index.lexsort_depth < i - loop(mi, df, keys) + if lexsort_depth == 0: + df = frame.copy() + else: + df = frame.sort_values(by=cols[:lexsort_depth]) + + mi = df.set_index(cols[:-1]) + assert not mi.index.lexsort_depth < lexsort_depth + validate(mi, df, key)
https://api.github.com/repos/pandas-dev/pandas/pulls/37339
2020-10-22T15:21:28Z
2020-10-22T23:47:08Z
2020-10-22T23:47:07Z
2020-10-22T23:48:29Z
REF: extract dialect validation
diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index 538c15b707761..20c0297448494 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -794,10 +794,8 @@ def __init__(self, f, engine=None, **kwds): _validate_skipfooter(kwds) - if kwds.get("dialect") is not None: - dialect = kwds["dialect"] - if dialect in csv.list_dialects(): - dialect = csv.get_dialect(dialect) + dialect = _extract_dialect(kwds) + if dialect is not None: kwds = _merge_with_dialect_properties(dialect, kwds) if kwds.get("header", "infer") == "infer": @@ -3739,6 +3737,50 @@ def _refine_defaults_read( return kwds +def _extract_dialect(kwds: Dict[str, Any]) -> Optional[csv.Dialect]: + """ + Extract concrete csv dialect instance. + + Returns + ------- + csv.Dialect or None + """ + if kwds.get("dialect") is None: + return None + + dialect = kwds["dialect"] + if dialect in csv.list_dialects(): + dialect = csv.get_dialect(dialect) + + _validate_dialect(dialect) + + return dialect + + +MANDATORY_DIALECT_ATTRS = ( + "delimiter", + "doublequote", + "escapechar", + "skipinitialspace", + "quotechar", + "quoting", +) + + +def _validate_dialect(dialect: csv.Dialect) -> None: + """ + Validate csv dialect instance. + + Raises + ------ + ValueError + If incorrect dialect is provided. + """ + for param in MANDATORY_DIALECT_ATTRS: + if not hasattr(dialect, param): + raise ValueError(f"Invalid dialect {dialect} provided") + + def _merge_with_dialect_properties( dialect: csv.Dialect, defaults: Dict[str, Any], @@ -3757,30 +3799,11 @@ def _merge_with_dialect_properties( ------- kwds : dict Updated keyword arguments, merged with dialect parameters. - - Raises - ------ - ValueError - If incorrect dialect is provided. """ kwds = defaults.copy() - # Any valid dialect should have these attributes. - # If any are missing, we will raise automatically. - mandatory_dialect_attrs = ( - "delimiter", - "doublequote", - "escapechar", - "skipinitialspace", - "quotechar", - "quoting", - ) - - for param in mandatory_dialect_attrs: - try: - dialect_val = getattr(dialect, param) - except AttributeError as err: - raise ValueError(f"Invalid dialect {dialect} provided") from err + for param in MANDATORY_DIALECT_ATTRS: + dialect_val = getattr(dialect, param) parser_default = _parser_defaults[param] provided = kwds.get(param, parser_default)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Following https://github.com/pandas-dev/pandas/pull/36852, I extracted validation of dialect into a separate function.
https://api.github.com/repos/pandas-dev/pandas/pulls/37332
2020-10-22T07:36:10Z
2020-10-23T00:08:28Z
2020-10-23T00:08:28Z
2020-11-06T15:38:43Z
DOC: Remove confusing description from `core.DataFrame.iterrows`
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5729d632a64ec..8d5d900cc343f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -971,9 +971,6 @@ def iterrows(self) -> Iterable[Tuple[Label, Series]]: data : Series The data of the row as a Series. - it : generator - A generator that iterates over the rows of the frame. - See Also -------- DataFrame.itertuples : Iterate over DataFrame rows as namedtuples of the values.
Current [`core.DataFrame.iterrows`](https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iterrows.html) is as follows ![image](https://user-images.githubusercontent.com/5734732/96833205-00176c00-147b-11eb-8dc3-6371b2718e76.png) However, `core.DataFrame.iterrows` actually returns an iterator which yields `(index, data)`, not `(index, data, it)`. This PRs remove such confusing description like [https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.iteritems.html?highlight=yields] - [ ] closes #xxxx (no issues found) - [ ] tests 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/37331
2020-10-22T06:36:01Z
2020-10-24T07:31:01Z
2020-10-24T07:31:01Z
2020-10-24T07:31:13Z
BUG: IntervalIndex.take without fill_value
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index d10cb28a3f588..f0e8327e5bce4 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -432,7 +432,7 @@ Strings Interval ^^^^^^^^ - +- Bug in :meth:`IntervalIndex.take` with negative indices and ``fill_value=None`` (:issue:`37330`) - - diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index 726ca0ce4d776..2ac00fa803473 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -51,12 +51,17 @@ def take( indices: Sequence[int], allow_fill: bool = False, fill_value: Any = None, + axis: int = 0, ) -> _T: if allow_fill: fill_value = self._validate_fill_value(fill_value) new_data = take( - self._ndarray, indices, allow_fill=allow_fill, fill_value=fill_value + self._ndarray, + indices, + allow_fill=allow_fill, + fill_value=fill_value, + axis=axis, ) return self._from_backing_data(new_data) diff --git a/pandas/core/arrays/interval.py b/pandas/core/arrays/interval.py index 09488b9576212..161cf3bf3a677 100644 --- a/pandas/core/arrays/interval.py +++ b/pandas/core/arrays/interval.py @@ -544,7 +544,9 @@ def __eq__(self, other): if is_interval_dtype(other_dtype): if self.closed != other.categories.closed: return np.zeros(len(self), dtype=bool) - other = other.categories.take(other.codes) + other = other.categories.take( + other.codes, allow_fill=True, fill_value=other.categories._na_value + ) # interval-like -> need same closed and matching endpoints if is_interval_dtype(other_dtype): diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 7f1c56d46fb90..08e79b45c4d27 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -714,7 +714,7 @@ def value_counts( # lab is a Categorical with categories an IntervalIndex lab = cut(Series(val), bins, include_lowest=True) lev = lab.cat.categories - lab = lev.take(lab.cat.codes) + lab = lev.take(lab.cat.codes, allow_fill=True, fill_value=lev._na_value) llab = lambda lab, inc: lab[inc]._multiindex.codes[-1] if is_interval_dtype(lab.dtype): diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 20a17c27fe282..48dcdfb3ecfff 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -769,7 +769,7 @@ def _assert_take_fillable( values, indices, allow_fill=allow_fill, fill_value=na_value ) else: - taken = values.take(indices) + taken = algos.take(values, indices, allow_fill=False, fill_value=na_value) return taken _index_shared_docs[ diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 7f0dc2426eba7..597b32e176170 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -909,13 +909,6 @@ def insert(self, loc, item): result = IntervalArray.from_arrays(new_left, new_right, closed=self.closed) return self._shallow_copy(result) - @Appender(_index_shared_docs["take"] % _index_doc_kwargs) - def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs): - result = self._data.take( - indices, axis=axis, allow_fill=allow_fill, fill_value=fill_value, **kwargs - ) - return self._shallow_copy(result) - # -------------------------------------------------------------------- # Rendering Methods # __repr__ associated methods are based on MultiIndex diff --git a/pandas/tests/indexes/categorical/test_astype.py b/pandas/tests/indexes/categorical/test_astype.py index a4a0cb1978325..44c4bcc951194 100644 --- a/pandas/tests/indexes/categorical/test_astype.py +++ b/pandas/tests/indexes/categorical/test_astype.py @@ -25,7 +25,7 @@ def test_astype(self): ) result = ci.astype("interval") - expected = ii.take([0, 1, -1]) + expected = ii.take([0, 1, -1], allow_fill=True, fill_value=np.nan) tm.assert_index_equal(result, expected) result = IntervalIndex(result.values) diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index b20026b20e1d7..9e248f0613893 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -407,6 +407,17 @@ def test_take_invalid_kwargs(self): with pytest.raises(ValueError, match=msg): idx.take(indices, mode="clip") + def test_take_minus1_without_fill(self, index): + # -1 does not get treated as NA unless allow_fill=True is passed + if len(index) == 0: + # Test is not applicable + return + + result = index.take([0, 0, -1]) + + expected = index.take([0, 0, len(index) - 1]) + tm.assert_index_equal(result, expected) + def test_repeat(self): rep = 2 i = self.create_index()
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry `IntervalIndex.take([0, 1, -1])` without explicitly passing fill_value should not fill the -1 as NA. Fixing this allows us to use the base class `take` for `IntervalIndex.take` (the original motivation)
https://api.github.com/repos/pandas-dev/pandas/pulls/37330
2020-10-22T02:56:01Z
2020-10-31T18:56:21Z
2020-10-31T18:56:21Z
2021-01-04T06:19:44Z
#31793 Add support for subtracting datetime from Timestamp
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 241c005c400cd..1c1415255bf89 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -715,6 +715,7 @@ Timezones ^^^^^^^^^ - Bug in :func:`to_datetime` with ``infer_datetime_format=True`` failing to parse zero UTC offset (``Z``) correctly (:issue:`41047`) - Bug in :meth:`Series.dt.tz_convert` resetting index in a :class:`Series` with :class:`CategoricalIndex` (:issue:`43080`) +- Bug in ``Timestamp`` and ``DatetimeIndex`` incorrectly raising a ``TypeError`` when subtracting two timezone-aware objects with mismatched timezones (:issue:`31793`) - Numeric diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 307b6f2949881..304ac9405c5e1 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -342,10 +342,10 @@ cdef class _Timestamp(ABCTimestamp): else: self = type(other)(self) - # validate tz's - if not tz_compare(self.tzinfo, other.tzinfo): - raise TypeError("Timestamp subtraction must have the " - "same timezones or no timezones") + if (self.tzinfo is None) ^ (other.tzinfo is None): + raise TypeError( + "Cannot subtract tz-naive and tz-aware datetime-like objects." + ) # scalar Timestamp/datetime - Timestamp/datetime -> yields a # Timedelta diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index b3a1a4d342355..647698f472978 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -728,12 +728,11 @@ def _sub_datetime_arraylike(self, other): assert is_datetime64_dtype(other) other = type(self)(other) - if not self._has_same_tz(other): - # require tz compat - raise TypeError( - f"{type(self).__name__} subtraction must have the same " - "timezones or no timezones" - ) + try: + self._assert_tzawareness_compat(other) + except TypeError as error: + new_message = str(error).replace("compare", "subtract") + raise type(error)(new_message) from error self_i8 = self.asi8 other_i8 = other.asi8 @@ -779,11 +778,11 @@ def _sub_datetimelike_scalar(self, other): if other is NaT: # type: ignore[comparison-overlap] return self - NaT - if not self._has_same_tz(other): - # require tz compat - raise TypeError( - "Timestamp subtraction must have the same timezones or no timezones" - ) + try: + self._assert_tzawareness_compat(other) + except TypeError as error: + new_message = str(error).replace("compare", "subtract") + raise type(error)(new_message) from error i8 = self.asi8 result = checked_add_with_arr(i8, -other.value, arr_mask=self._isnan) diff --git a/pandas/tests/arithmetic/test_datetime64.py b/pandas/tests/arithmetic/test_datetime64.py index 8194f47541e4c..6ddf63c03e4f1 100644 --- a/pandas/tests/arithmetic/test_datetime64.py +++ b/pandas/tests/arithmetic/test_datetime64.py @@ -837,6 +837,61 @@ def test_dt64arr_sub_timedeltalike_scalar( rng -= two_hours tm.assert_equal(rng, expected) + def test_dt64_array_sub_dt_with_different_timezone(self, box_with_array): + t1 = date_range("20130101", periods=3).tz_localize("US/Eastern") + t1 = tm.box_expected(t1, box_with_array) + t2 = Timestamp("20130101").tz_localize("CET") + tnaive = Timestamp(20130101) + + result = t1 - t2 + expected = TimedeltaIndex( + ["0 days 06:00:00", "1 days 06:00:00", "2 days 06:00:00"] + ) + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) + + result = t2 - t1 + expected = TimedeltaIndex( + ["-1 days +18:00:00", "-2 days +18:00:00", "-3 days +18:00:00"] + ) + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) + + msg = "Cannot subtract tz-naive and tz-aware datetime-like objects" + with pytest.raises(TypeError, match=msg): + t1 - tnaive + + with pytest.raises(TypeError, match=msg): + tnaive - t1 + + def test_dt64_array_sub_dt64_array_with_different_timezone(self, box_with_array): + t1 = date_range("20130101", periods=3).tz_localize("US/Eastern") + t1 = tm.box_expected(t1, box_with_array) + t2 = date_range("20130101", periods=3).tz_localize("CET") + t2 = tm.box_expected(t2, box_with_array) + tnaive = date_range("20130101", periods=3) + + result = t1 - t2 + expected = TimedeltaIndex( + ["0 days 06:00:00", "0 days 06:00:00", "0 days 06:00:00"] + ) + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) + + result = t2 - t1 + expected = TimedeltaIndex( + ["-1 days +18:00:00", "-1 days +18:00:00", "-1 days +18:00:00"] + ) + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) + + msg = "Cannot subtract tz-naive and tz-aware datetime-like objects" + with pytest.raises(TypeError, match=msg): + t1 - tnaive + + with pytest.raises(TypeError, match=msg): + tnaive - t1 + def test_dt64arr_add_sub_td64_nat(self, box_with_array, tz_naive_fixture): # GH#23320 special handling for timedelta64("NaT") tz = tz_naive_fixture @@ -979,7 +1034,7 @@ def test_dt64arr_aware_sub_dt64ndarray_raises( dt64vals = dti.values dtarr = tm.box_expected(dti, box_with_array) - msg = "subtraction must have the same timezones or" + msg = "Cannot subtract tz-naive and tz-aware datetime" with pytest.raises(TypeError, match=msg): dtarr - dt64vals with pytest.raises(TypeError, match=msg): @@ -2099,7 +2154,6 @@ def test_sub_dti_dti(self): dti = date_range("20130101", periods=3) dti_tz = date_range("20130101", periods=3).tz_localize("US/Eastern") - dti_tz2 = date_range("20130101", periods=3).tz_localize("UTC") expected = TimedeltaIndex([0, 0, 0]) result = dti - dti @@ -2107,16 +2161,13 @@ def test_sub_dti_dti(self): result = dti_tz - dti_tz tm.assert_index_equal(result, expected) - msg = "DatetimeArray subtraction must have the same timezones or" + msg = "Cannot subtract tz-naive and tz-aware datetime-like objects" with pytest.raises(TypeError, match=msg): dti_tz - dti with pytest.raises(TypeError, match=msg): dti - dti_tz - with pytest.raises(TypeError, match=msg): - dti_tz - dti_tz2 - # isub dti -= dti tm.assert_index_equal(dti, expected) diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index 64da7cc968c19..543531889531a 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -357,13 +357,15 @@ def test_subtraction_ops(self): expected = DatetimeIndex(["20121231", NaT, "20121230"], name="foo") tm.assert_index_equal(result, expected) - def test_subtraction_ops_with_tz(self): + def test_subtraction_ops_with_tz(self, box_with_array): # check that dt/dti subtraction ops with tz are validated dti = pd.date_range("20130101", periods=3) + dti = tm.box_expected(dti, box_with_array) ts = Timestamp("20130101") dt = ts.to_pydatetime() dti_tz = pd.date_range("20130101", periods=3).tz_localize("US/Eastern") + dti_tz = tm.box_expected(dti_tz, box_with_array) ts_tz = Timestamp("20130101").tz_localize("US/Eastern") ts_tz2 = Timestamp("20130101").tz_localize("CET") dt_tz = ts_tz.to_pydatetime() @@ -387,51 +389,49 @@ def _check(result, expected): _check(result, expected) # tz mismatches - msg = "Timestamp subtraction must have the same timezones or no timezones" + msg = "Cannot subtract tz-naive and tz-aware datetime-like objects." with pytest.raises(TypeError, match=msg): dt_tz - ts msg = "can't subtract offset-naive and offset-aware datetimes" with pytest.raises(TypeError, match=msg): dt_tz - dt - msg = "Timestamp subtraction must have the same timezones or no timezones" - with pytest.raises(TypeError, match=msg): - dt_tz - ts_tz2 msg = "can't subtract offset-naive and offset-aware datetimes" with pytest.raises(TypeError, match=msg): dt - dt_tz - msg = "Timestamp subtraction must have the same timezones or no timezones" + msg = "Cannot subtract tz-naive and tz-aware datetime-like objects." with pytest.raises(TypeError, match=msg): ts - dt_tz with pytest.raises(TypeError, match=msg): ts_tz2 - ts with pytest.raises(TypeError, match=msg): ts_tz2 - dt - with pytest.raises(TypeError, match=msg): - ts_tz - ts_tz2 + msg = "Cannot subtract tz-naive and tz-aware" # with dti with pytest.raises(TypeError, match=msg): dti - ts_tz with pytest.raises(TypeError, match=msg): dti_tz - ts - with pytest.raises(TypeError, match=msg): - dti_tz - ts_tz2 result = dti_tz - dt_tz expected = TimedeltaIndex(["0 days", "1 days", "2 days"]) - tm.assert_index_equal(result, expected) + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) result = dt_tz - dti_tz expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"]) - tm.assert_index_equal(result, expected) + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) result = dti_tz - ts_tz expected = TimedeltaIndex(["0 days", "1 days", "2 days"]) - tm.assert_index_equal(result, expected) + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) result = ts_tz - dti_tz expected = TimedeltaIndex(["0 days", "-1 days", "-2 days"]) - tm.assert_index_equal(result, expected) + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) result = td - td expected = Timedelta("0 days") @@ -439,7 +439,8 @@ def _check(result, expected): result = dti_tz - td expected = DatetimeIndex(["20121231", "20130101", "20130102"], tz="US/Eastern") - tm.assert_index_equal(result, expected) + expected = tm.box_expected(expected, box_with_array) + tm.assert_equal(result, expected) def test_dti_tdi_numeric_ops(self): # These are normally union/diff set-like ops diff --git a/pandas/tests/scalar/timestamp/test_arithmetic.py b/pandas/tests/scalar/timestamp/test_arithmetic.py index 1a8fd2a8199a2..e0c18a7055a4e 100644 --- a/pandas/tests/scalar/timestamp/test_arithmetic.py +++ b/pandas/tests/scalar/timestamp/test_arithmetic.py @@ -1,6 +1,7 @@ from datetime import ( datetime, timedelta, + timezone, ) import numpy as np @@ -99,7 +100,7 @@ def test_rsub_dtscalars(self, tz_naive_fixture): if tz_naive_fixture is None: assert other.to_datetime64() - ts == td else: - msg = "subtraction must have" + msg = "Cannot subtract tz-naive and tz-aware datetime-like objects" with pytest.raises(TypeError, match=msg): other.to_datetime64() - ts @@ -109,6 +110,47 @@ def test_timestamp_sub_datetime(self): assert (ts - dt).days == 1 assert (dt - ts).days == -1 + def test_subtract_tzaware_datetime(self): + t1 = Timestamp("2020-10-22T22:00:00+00:00") + t2 = datetime(2020, 10, 22, 22, tzinfo=timezone.utc) + + result = t1 - t2 + + assert isinstance(result, Timedelta) + assert result == Timedelta("0 days") + + def test_subtract_timestamp_from_different_timezone(self): + t1 = Timestamp("20130101").tz_localize("US/Eastern") + t2 = Timestamp("20130101").tz_localize("CET") + + result = t1 - t2 + + assert isinstance(result, Timedelta) + assert result == Timedelta("0 days 06:00:00") + + def test_subtracting_involving_datetime_with_different_tz(self): + t1 = datetime(2013, 1, 1, tzinfo=timezone(timedelta(hours=-5))) + t2 = Timestamp("20130101").tz_localize("CET") + + result = t1 - t2 + + assert isinstance(result, Timedelta) + assert result == Timedelta("0 days 06:00:00") + + result = t2 - t1 + assert isinstance(result, Timedelta) + assert result == Timedelta("-1 days +18:00:00") + + def test_subtracting_different_timezones(self, tz_aware_fixture): + t_raw = Timestamp("20130101") + t_UTC = t_raw.tz_localize("UTC") + t_diff = t_UTC.tz_convert(tz_aware_fixture) + Timedelta("0 days 05:00:00") + + result = t_diff - t_UTC + + assert isinstance(result, Timedelta) + assert result == Timedelta("0 days 05:00:00") + def test_addition_subtraction_types(self): # Assert on the types resulting from Timestamp +/- various date/time # objects
- [x] closes #31793 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Based on the discussion in the attached issue, i've made the following changes: 1. add support for subtracting when the two items have different timezones 2. raise an error if one (but not both) timezone is naive The root cause of 31793 was that the tzinfo objects were from different libraries -- `Timestamp` makes a `pytz.UTC` whereas a datetime object might just have `datetime.timezone.utc`. These objects are not necessarily equal, even if they represent the same timezone. In addition, this change *adds* support for time-deltas where the timezone of each date is not the same. This follows the behaviour of `datetime` more closely. I reference the [python `datetime` module documentation](https://docs.python.org/3/library/datetime.html) which defines when a datetime is naive: when its `tzinfo` is `None` or a call to `item.tzinfo.utcoffset(item)` returns `None`.
https://api.github.com/repos/pandas-dev/pandas/pulls/37329
2020-10-22T02:48:06Z
2021-12-28T18:00:56Z
2021-12-28T18:00:55Z
2021-12-28T20:22:36Z
Backport PR #37288 on branch 1.1.x (Regression in offsets caused offsets to be no longer hashable)
diff --git a/doc/source/whatsnew/v1.1.4.rst b/doc/source/whatsnew/v1.1.4.rst index 8a9281ba7de99..f641e7ba4c6f7 100644 --- a/doc/source/whatsnew/v1.1.4.rst +++ b/doc/source/whatsnew/v1.1.4.rst @@ -21,6 +21,7 @@ Fixed regressions - Fixed regression in :meth:`Series.astype` converting ``None`` to ``"nan"`` when casting to string (:issue:`36904`) - Fixed regression in :class:`RollingGroupby` causing a segmentation fault with Index of dtype object (:issue:`36727`) - Fixed regression in :class:`PeriodDtype` comparing both equal and unequal to its string representation (:issue:`37265`) +- Fixed regression in certain offsets (:meth:`pd.offsets.Day() <pandas.tseries.offsets.Day>` and below) no longer being hashable (:issue:`37267`) .. --------------------------------------------------------------------------- diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index a85dfc36b97fa..54c08da5269f4 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -785,6 +785,11 @@ cdef class Tick(SingleConstructorOffset): def is_anchored(self) -> bool: return False + # This is identical to BaseOffset.__hash__, but has to be redefined here + # for Python 3, because we've redefined __eq__. + def __hash__(self) -> int: + return hash(self._params) + # -------------------------------------------------------------------- # Comparison and Arithmetic Methods diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index e235d503cfd14..a720d813dbd8f 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -685,6 +685,11 @@ def test_isAnchored_deprecated(self, offset_types): expected = off.is_anchored() assert result == expected + def test_offsets_hashable(self, offset_types): + # GH: 37267 + off = self._get_offset(offset_types) + assert hash(off) is not None + class TestDateOffset(Base): def setup_method(self, method):
Backport PR #37288: Regression in offsets caused offsets to be no longer hashable
https://api.github.com/repos/pandas-dev/pandas/pulls/37326
2020-10-22T00:08:47Z
2020-10-22T07:37:37Z
2020-10-22T07:37:37Z
2020-10-22T07:37:38Z
TST/REF: method-specific files for lookup, get_value, set_value
diff --git a/pandas/tests/frame/indexing/test_get_value.py b/pandas/tests/frame/indexing/test_get_value.py new file mode 100644 index 0000000000000..9a2ec975f1e31 --- /dev/null +++ b/pandas/tests/frame/indexing/test_get_value.py @@ -0,0 +1,19 @@ +import pytest + +from pandas import DataFrame, MultiIndex + + +class TestGetValue: + def test_get_set_value_no_partial_indexing(self): + # partial w/ MultiIndex raise exception + index = MultiIndex.from_tuples([(0, 1), (0, 2), (1, 1), (1, 2)]) + df = DataFrame(index=index, columns=range(4)) + with pytest.raises(KeyError, match=r"^0$"): + df._get_value(0, 1) + + def test_get_value(self, float_frame): + for idx in float_frame.index: + for col in float_frame.columns: + result = float_frame._get_value(idx, col) + expected = float_frame[col][idx] + assert result == expected diff --git a/pandas/tests/frame/indexing/test_indexing.py b/pandas/tests/frame/indexing/test_indexing.py index 0dee818613edb..1d5b0936103ee 100644 --- a/pandas/tests/frame/indexing/test_indexing.py +++ b/pandas/tests/frame/indexing/test_indexing.py @@ -6,7 +6,7 @@ from pandas._libs import iNaT -from pandas.core.dtypes.common import is_float_dtype, is_integer +from pandas.core.dtypes.common import is_integer import pandas as pd from pandas import ( @@ -1327,120 +1327,6 @@ def test_getitem_list_duplicates(self): expected = df.iloc[:, 2:] tm.assert_frame_equal(result, expected) - def test_get_value(self, float_frame): - for idx in float_frame.index: - for col in float_frame.columns: - result = float_frame._get_value(idx, col) - expected = float_frame[col][idx] - assert result == expected - - def test_lookup_float(self, float_frame): - df = float_frame - rows = list(df.index) * len(df.columns) - cols = list(df.columns) * len(df.index) - with tm.assert_produces_warning(FutureWarning): - result = df.lookup(rows, cols) - - expected = np.array([df.loc[r, c] for r, c in zip(rows, cols)]) - tm.assert_numpy_array_equal(result, expected) - - def test_lookup_mixed(self, float_string_frame): - df = float_string_frame - rows = list(df.index) * len(df.columns) - cols = list(df.columns) * len(df.index) - with tm.assert_produces_warning(FutureWarning): - result = df.lookup(rows, cols) - - expected = np.array( - [df.loc[r, c] for r, c in zip(rows, cols)], dtype=np.object_ - ) - tm.assert_almost_equal(result, expected) - - def test_lookup_bool(self): - df = DataFrame( - { - "label": ["a", "b", "a", "c"], - "mask_a": [True, True, False, True], - "mask_b": [True, False, False, False], - "mask_c": [False, True, False, True], - } - ) - with tm.assert_produces_warning(FutureWarning): - df["mask"] = df.lookup(df.index, "mask_" + df["label"]) - - exp_mask = np.array( - [df.loc[r, c] for r, c in zip(df.index, "mask_" + df["label"])] - ) - - tm.assert_series_equal(df["mask"], Series(exp_mask, name="mask")) - assert df["mask"].dtype == np.bool_ - - def test_lookup_raises(self, float_frame): - with pytest.raises(KeyError, match="'One or more row labels was not found'"): - with tm.assert_produces_warning(FutureWarning): - float_frame.lookup(["xyz"], ["A"]) - - with pytest.raises(KeyError, match="'One or more column labels was not found'"): - with tm.assert_produces_warning(FutureWarning): - float_frame.lookup([float_frame.index[0]], ["xyz"]) - - with pytest.raises(ValueError, match="same size"): - with tm.assert_produces_warning(FutureWarning): - float_frame.lookup(["a", "b", "c"], ["a"]) - - def test_lookup_requires_unique_axes(self): - # GH#33041 raise with a helpful error message - df = DataFrame(np.random.randn(6).reshape(3, 2), columns=["A", "A"]) - - rows = [0, 1] - cols = ["A", "A"] - - # homogeneous-dtype case - with pytest.raises(ValueError, match="requires unique index and columns"): - with tm.assert_produces_warning(FutureWarning): - df.lookup(rows, cols) - with pytest.raises(ValueError, match="requires unique index and columns"): - with tm.assert_produces_warning(FutureWarning): - df.T.lookup(cols, rows) - - # heterogeneous dtype - df["B"] = 0 - with pytest.raises(ValueError, match="requires unique index and columns"): - with tm.assert_produces_warning(FutureWarning): - df.lookup(rows, cols) - - def test_set_value(self, float_frame): - for idx in float_frame.index: - for col in float_frame.columns: - float_frame._set_value(idx, col, 1) - assert float_frame[col][idx] == 1 - - def test_set_value_resize(self, float_frame): - - res = float_frame._set_value("foobar", "B", 0) - assert res is None - assert float_frame.index[-1] == "foobar" - assert float_frame._get_value("foobar", "B") == 0 - - float_frame.loc["foobar", "qux"] = 0 - assert float_frame._get_value("foobar", "qux") == 0 - - res = float_frame.copy() - res._set_value("foobar", "baz", "sam") - assert res["baz"].dtype == np.object_ - - res = float_frame.copy() - res._set_value("foobar", "baz", True) - assert res["baz"].dtype == np.object_ - - res = float_frame.copy() - res._set_value("foobar", "baz", 5) - assert is_float_dtype(res["baz"]) - assert isna(res["baz"].drop(["foobar"])).all() - msg = "could not convert string to float: 'sam'" - with pytest.raises(ValueError, match=msg): - res._set_value("foobar", "baz", "sam") - def test_reindex_with_multi_index(self): # https://github.com/pandas-dev/pandas/issues/29896 # tests for reindexing a multi-indexed DataFrame with a new MultiIndex @@ -1542,13 +1428,6 @@ def test_set_value_with_index_dtype_change(self): assert list(df.index) == list(df_orig.index) + ["C"] assert list(df.columns) == list(df_orig.columns) + ["D"] - def test_get_set_value_no_partial_indexing(self): - # partial w/ MultiIndex raise exception - index = MultiIndex.from_tuples([(0, 1), (0, 2), (1, 1), (1, 2)]) - df = DataFrame(index=index, columns=range(4)) - with pytest.raises(KeyError, match=r"^0$"): - df._get_value(0, 1) - # TODO: rename? remove? def test_single_element_ix_dont_upcast(self, float_frame): float_frame["E"] = 1 @@ -2251,12 +2130,3 @@ def test_object_casting_indexing_wraps_datetimelike(): assert blk.dtype == "m8[ns]" # we got the right block val = blk.iget((0, 0)) assert isinstance(val, pd.Timedelta) - - -def test_lookup_deprecated(): - # GH18262 - df = DataFrame( - {"col": ["A", "A", "B", "B"], "A": [80, 23, np.nan, 22], "B": [80, 55, 76, 67]} - ) - with tm.assert_produces_warning(FutureWarning): - df.lookup(df.index, df["col"]) diff --git a/pandas/tests/frame/indexing/test_lookup.py b/pandas/tests/frame/indexing/test_lookup.py new file mode 100644 index 0000000000000..21d732695fba4 --- /dev/null +++ b/pandas/tests/frame/indexing/test_lookup.py @@ -0,0 +1,91 @@ +import numpy as np +import pytest + +from pandas import DataFrame, Series +import pandas._testing as tm + + +class TestLookup: + def test_lookup_float(self, float_frame): + df = float_frame + rows = list(df.index) * len(df.columns) + cols = list(df.columns) * len(df.index) + with tm.assert_produces_warning(FutureWarning): + result = df.lookup(rows, cols) + + expected = np.array([df.loc[r, c] for r, c in zip(rows, cols)]) + tm.assert_numpy_array_equal(result, expected) + + def test_lookup_mixed(self, float_string_frame): + df = float_string_frame + rows = list(df.index) * len(df.columns) + cols = list(df.columns) * len(df.index) + with tm.assert_produces_warning(FutureWarning): + result = df.lookup(rows, cols) + + expected = np.array( + [df.loc[r, c] for r, c in zip(rows, cols)], dtype=np.object_ + ) + tm.assert_almost_equal(result, expected) + + def test_lookup_bool(self): + df = DataFrame( + { + "label": ["a", "b", "a", "c"], + "mask_a": [True, True, False, True], + "mask_b": [True, False, False, False], + "mask_c": [False, True, False, True], + } + ) + with tm.assert_produces_warning(FutureWarning): + df["mask"] = df.lookup(df.index, "mask_" + df["label"]) + + exp_mask = np.array( + [df.loc[r, c] for r, c in zip(df.index, "mask_" + df["label"])] + ) + + tm.assert_series_equal(df["mask"], Series(exp_mask, name="mask")) + assert df["mask"].dtype == np.bool_ + + def test_lookup_raises(self, float_frame): + with pytest.raises(KeyError, match="'One or more row labels was not found'"): + with tm.assert_produces_warning(FutureWarning): + float_frame.lookup(["xyz"], ["A"]) + + with pytest.raises(KeyError, match="'One or more column labels was not found'"): + with tm.assert_produces_warning(FutureWarning): + float_frame.lookup([float_frame.index[0]], ["xyz"]) + + with pytest.raises(ValueError, match="same size"): + with tm.assert_produces_warning(FutureWarning): + float_frame.lookup(["a", "b", "c"], ["a"]) + + def test_lookup_requires_unique_axes(self): + # GH#33041 raise with a helpful error message + df = DataFrame(np.random.randn(6).reshape(3, 2), columns=["A", "A"]) + + rows = [0, 1] + cols = ["A", "A"] + + # homogeneous-dtype case + with pytest.raises(ValueError, match="requires unique index and columns"): + with tm.assert_produces_warning(FutureWarning): + df.lookup(rows, cols) + with pytest.raises(ValueError, match="requires unique index and columns"): + with tm.assert_produces_warning(FutureWarning): + df.T.lookup(cols, rows) + + # heterogeneous dtype + df["B"] = 0 + with pytest.raises(ValueError, match="requires unique index and columns"): + with tm.assert_produces_warning(FutureWarning): + df.lookup(rows, cols) + + +def test_lookup_deprecated(): + # GH#18262 + df = DataFrame( + {"col": ["A", "A", "B", "B"], "A": [80, 23, np.nan, 22], "B": [80, 55, 76, 67]} + ) + with tm.assert_produces_warning(FutureWarning): + df.lookup(df.index, df["col"]) diff --git a/pandas/tests/frame/indexing/test_set_value.py b/pandas/tests/frame/indexing/test_set_value.py new file mode 100644 index 0000000000000..484e2d544197e --- /dev/null +++ b/pandas/tests/frame/indexing/test_set_value.py @@ -0,0 +1,40 @@ +import numpy as np +import pytest + +from pandas.core.dtypes.common import is_float_dtype + +from pandas import isna + + +class TestSetValue: + def test_set_value(self, float_frame): + for idx in float_frame.index: + for col in float_frame.columns: + float_frame._set_value(idx, col, 1) + assert float_frame[col][idx] == 1 + + def test_set_value_resize(self, float_frame): + + res = float_frame._set_value("foobar", "B", 0) + assert res is None + assert float_frame.index[-1] == "foobar" + assert float_frame._get_value("foobar", "B") == 0 + + float_frame.loc["foobar", "qux"] = 0 + assert float_frame._get_value("foobar", "qux") == 0 + + res = float_frame.copy() + res._set_value("foobar", "baz", "sam") + assert res["baz"].dtype == np.object_ + + res = float_frame.copy() + res._set_value("foobar", "baz", True) + assert res["baz"].dtype == np.object_ + + res = float_frame.copy() + res._set_value("foobar", "baz", 5) + assert is_float_dtype(res["baz"]) + assert isna(res["baz"].drop(["foobar"])).all() + msg = "could not convert string to float: 'sam'" + with pytest.raises(ValueError, match=msg): + res._set_value("foobar", "baz", "sam") diff --git a/pandas/tests/series/indexing/test_datetime.py b/pandas/tests/series/indexing/test_datetime.py index 392f352711210..6aee8b3ab34fa 100644 --- a/pandas/tests/series/indexing/test_datetime.py +++ b/pandas/tests/series/indexing/test_datetime.py @@ -65,21 +65,6 @@ def test_dti_reset_index_round_trip(): assert df.reset_index()["Date"][0] == stamp -def test_series_set_value(): - # #1561 - - dates = [datetime(2001, 1, 1), datetime(2001, 1, 2)] - index = DatetimeIndex(dates) - - s = Series(dtype=object) - s._set_value(dates[0], 1.0) - s._set_value(dates[1], np.nan) - - expected = Series([1.0, np.nan], index=index) - - tm.assert_series_equal(s, expected) - - @pytest.mark.slow def test_slice_locs_indexerror(): times = [datetime(2000, 1, 1) + timedelta(minutes=i * 10) for i in range(100000)] diff --git a/pandas/tests/series/indexing/test_set_value.py b/pandas/tests/series/indexing/test_set_value.py new file mode 100644 index 0000000000000..ea09646de71c1 --- /dev/null +++ b/pandas/tests/series/indexing/test_set_value.py @@ -0,0 +1,21 @@ +from datetime import datetime + +import numpy as np + +from pandas import DatetimeIndex, Series +import pandas._testing as tm + + +def test_series_set_value(): + # GH#1561 + + dates = [datetime(2001, 1, 1), datetime(2001, 1, 2)] + index = DatetimeIndex(dates) + + s = Series(dtype=object) + s._set_value(dates[0], 1.0) + s._set_value(dates[1], np.nan) + + expected = Series([1.0, np.nan], index=index) + + tm.assert_series_equal(s, expected)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37325
2020-10-21T23:07:54Z
2020-10-22T00:12:19Z
2020-10-22T00:12:19Z
2020-10-22T01:12:04Z
TST/REF: collect _libs tests
diff --git a/pandas/tests/groupby/test_bin_groupby.py b/pandas/tests/groupby/test_bin_groupby.py index f20eed4575e91..aff9911961b25 100644 --- a/pandas/tests/groupby/test_bin_groupby.py +++ b/pandas/tests/groupby/test_bin_groupby.py @@ -1,12 +1,10 @@ import numpy as np import pytest -from pandas._libs import groupby, lib, reduction as libreduction - -from pandas.core.dtypes.common import ensure_int64 +from pandas._libs import lib, reduction as libreduction import pandas as pd -from pandas import Series, isna +from pandas import Series import pandas._testing as tm @@ -103,36 +101,5 @@ def test_generate_bins(binner, closed, expected): tm.assert_numpy_array_equal(result, expected) -def test_group_ohlc(): - def _check(dtype): - obj = np.array(np.random.randn(20), dtype=dtype) - - bins = np.array([6, 12, 20]) - out = np.zeros((3, 4), dtype) - counts = np.zeros(len(out), dtype=np.int64) - labels = ensure_int64(np.repeat(np.arange(3), np.diff(np.r_[0, bins]))) - - func = getattr(groupby, f"group_ohlc_{dtype}") - func(out, counts, obj[:, None], labels) - - def _ohlc(group): - if isna(group).all(): - return np.repeat(np.nan, 4) - return [group[0], group.max(), group.min(), group[-1]] - - expected = np.array([_ohlc(obj[:6]), _ohlc(obj[6:12]), _ohlc(obj[12:])]) - - tm.assert_almost_equal(out, expected) - tm.assert_numpy_array_equal(counts, np.array([6, 6, 8], dtype=np.int64)) - - obj[:6] = np.nan - func(out, counts, obj[:, None], labels) - expected[0] = np.nan - tm.assert_almost_equal(out, expected) - - _check("float32") - _check("float64") - - class TestMoments: pass diff --git a/pandas/tests/groupby/test_libgroupby.py b/pandas/tests/groupby/test_libgroupby.py new file mode 100644 index 0000000000000..28b740355f351 --- /dev/null +++ b/pandas/tests/groupby/test_libgroupby.py @@ -0,0 +1,237 @@ +import numpy as np + +from pandas._libs import groupby as libgroupby +from pandas._libs.groupby import ( + group_cumprod_float64, + group_cumsum, + group_var_float32, + group_var_float64, +) + +from pandas.core.dtypes.common import ensure_int64 + +from pandas import isna +import pandas._testing as tm + + +class GroupVarTestMixin: + def test_group_var_generic_1d(self): + prng = np.random.RandomState(1234) + + out = (np.nan * np.ones((5, 1))).astype(self.dtype) + counts = np.zeros(5, dtype="int64") + values = 10 * prng.rand(15, 1).astype(self.dtype) + labels = np.tile(np.arange(5), (3,)).astype("int64") + + expected_out = ( + np.squeeze(values).reshape((5, 3), order="F").std(axis=1, ddof=1) ** 2 + )[:, np.newaxis] + expected_counts = counts + 3 + + self.algo(out, counts, values, labels) + assert np.allclose(out, expected_out, self.rtol) + tm.assert_numpy_array_equal(counts, expected_counts) + + def test_group_var_generic_1d_flat_labels(self): + prng = np.random.RandomState(1234) + + out = (np.nan * np.ones((1, 1))).astype(self.dtype) + counts = np.zeros(1, dtype="int64") + values = 10 * prng.rand(5, 1).astype(self.dtype) + labels = np.zeros(5, dtype="int64") + + expected_out = np.array([[values.std(ddof=1) ** 2]]) + expected_counts = counts + 5 + + self.algo(out, counts, values, labels) + + assert np.allclose(out, expected_out, self.rtol) + tm.assert_numpy_array_equal(counts, expected_counts) + + def test_group_var_generic_2d_all_finite(self): + prng = np.random.RandomState(1234) + + out = (np.nan * np.ones((5, 2))).astype(self.dtype) + counts = np.zeros(5, dtype="int64") + values = 10 * prng.rand(10, 2).astype(self.dtype) + labels = np.tile(np.arange(5), (2,)).astype("int64") + + expected_out = np.std(values.reshape(2, 5, 2), ddof=1, axis=0) ** 2 + expected_counts = counts + 2 + + self.algo(out, counts, values, labels) + assert np.allclose(out, expected_out, self.rtol) + tm.assert_numpy_array_equal(counts, expected_counts) + + def test_group_var_generic_2d_some_nan(self): + prng = np.random.RandomState(1234) + + out = (np.nan * np.ones((5, 2))).astype(self.dtype) + counts = np.zeros(5, dtype="int64") + values = 10 * prng.rand(10, 2).astype(self.dtype) + values[:, 1] = np.nan + labels = np.tile(np.arange(5), (2,)).astype("int64") + + expected_out = np.vstack( + [ + values[:, 0].reshape(5, 2, order="F").std(ddof=1, axis=1) ** 2, + np.nan * np.ones(5), + ] + ).T.astype(self.dtype) + expected_counts = counts + 2 + + self.algo(out, counts, values, labels) + tm.assert_almost_equal(out, expected_out, rtol=0.5e-06) + tm.assert_numpy_array_equal(counts, expected_counts) + + def test_group_var_constant(self): + # Regression test from GH 10448. + + out = np.array([[np.nan]], dtype=self.dtype) + counts = np.array([0], dtype="int64") + values = 0.832845131556193 * np.ones((3, 1), dtype=self.dtype) + labels = np.zeros(3, dtype="int64") + + self.algo(out, counts, values, labels) + + assert counts[0] == 3 + assert out[0, 0] >= 0 + tm.assert_almost_equal(out[0, 0], 0.0) + + +class TestGroupVarFloat64(GroupVarTestMixin): + __test__ = True + + algo = staticmethod(group_var_float64) + dtype = np.float64 + rtol = 1e-5 + + def test_group_var_large_inputs(self): + prng = np.random.RandomState(1234) + + out = np.array([[np.nan]], dtype=self.dtype) + counts = np.array([0], dtype="int64") + values = (prng.rand(10 ** 6) + 10 ** 12).astype(self.dtype) + values.shape = (10 ** 6, 1) + labels = np.zeros(10 ** 6, dtype="int64") + + self.algo(out, counts, values, labels) + + assert counts[0] == 10 ** 6 + tm.assert_almost_equal(out[0, 0], 1.0 / 12, rtol=0.5e-3) + + +class TestGroupVarFloat32(GroupVarTestMixin): + __test__ = True + + algo = staticmethod(group_var_float32) + dtype = np.float32 + rtol = 1e-2 + + +def test_group_ohlc(): + def _check(dtype): + obj = np.array(np.random.randn(20), dtype=dtype) + + bins = np.array([6, 12, 20]) + out = np.zeros((3, 4), dtype) + counts = np.zeros(len(out), dtype=np.int64) + labels = ensure_int64(np.repeat(np.arange(3), np.diff(np.r_[0, bins]))) + + func = getattr(libgroupby, f"group_ohlc_{dtype}") + func(out, counts, obj[:, None], labels) + + def _ohlc(group): + if isna(group).all(): + return np.repeat(np.nan, 4) + return [group[0], group.max(), group.min(), group[-1]] + + expected = np.array([_ohlc(obj[:6]), _ohlc(obj[6:12]), _ohlc(obj[12:])]) + + tm.assert_almost_equal(out, expected) + tm.assert_numpy_array_equal(counts, np.array([6, 6, 8], dtype=np.int64)) + + obj[:6] = np.nan + func(out, counts, obj[:, None], labels) + expected[0] = np.nan + tm.assert_almost_equal(out, expected) + + _check("float32") + _check("float64") + + +def _check_cython_group_transform_cumulative(pd_op, np_op, dtype): + """ + Check a group transform that executes a cumulative function. + + Parameters + ---------- + pd_op : callable + The pandas cumulative function. + np_op : callable + The analogous one in NumPy. + dtype : type + The specified dtype of the data. + """ + is_datetimelike = False + + data = np.array([[1], [2], [3], [4]], dtype=dtype) + ans = np.zeros_like(data) + + labels = np.array([0, 0, 0, 0], dtype=np.int64) + ngroups = 1 + pd_op(ans, data, labels, ngroups, is_datetimelike) + + tm.assert_numpy_array_equal(np_op(data), ans[:, 0], check_dtype=False) + + +def test_cython_group_transform_cumsum(any_real_dtype): + # see gh-4095 + dtype = np.dtype(any_real_dtype).type + pd_op, np_op = group_cumsum, np.cumsum + _check_cython_group_transform_cumulative(pd_op, np_op, dtype) + + +def test_cython_group_transform_cumprod(): + # see gh-4095 + dtype = np.float64 + pd_op, np_op = group_cumprod_float64, np.cumproduct + _check_cython_group_transform_cumulative(pd_op, np_op, dtype) + + +def test_cython_group_transform_algos(): + # see gh-4095 + is_datetimelike = False + + # with nans + labels = np.array([0, 0, 0, 0, 0], dtype=np.int64) + ngroups = 1 + + data = np.array([[1], [2], [3], [np.nan], [4]], dtype="float64") + actual = np.zeros_like(data) + actual.fill(np.nan) + group_cumprod_float64(actual, data, labels, ngroups, is_datetimelike) + expected = np.array([1, 2, 6, np.nan, 24], dtype="float64") + tm.assert_numpy_array_equal(actual[:, 0], expected) + + actual = np.zeros_like(data) + actual.fill(np.nan) + group_cumsum(actual, data, labels, ngroups, is_datetimelike) + expected = np.array([1, 3, 6, np.nan, 10], dtype="float64") + tm.assert_numpy_array_equal(actual[:, 0], expected) + + # timedelta + is_datetimelike = True + data = np.array([np.timedelta64(1, "ns")] * 5, dtype="m8[ns]")[:, None] + actual = np.zeros_like(data, dtype="int64") + group_cumsum(actual, data.view("int64"), labels, ngroups, is_datetimelike) + expected = np.array( + [ + np.timedelta64(1, "ns"), + np.timedelta64(2, "ns"), + np.timedelta64(3, "ns"), + np.timedelta64(4, "ns"), + np.timedelta64(5, "ns"), + ] + ) + tm.assert_numpy_array_equal(actual[:, 0].view("m8[ns]"), expected) diff --git a/pandas/tests/groupby/transform/test_transform.py b/pandas/tests/groupby/transform/test_transform.py index 946e60d17e0bb..cd3c2771db8a4 100644 --- a/pandas/tests/groupby/transform/test_transform.py +++ b/pandas/tests/groupby/transform/test_transform.py @@ -4,8 +4,6 @@ import numpy as np import pytest -from pandas._libs.groupby import group_cumprod_float64, group_cumsum - from pandas.core.dtypes.common import ensure_platform_int, is_timedelta64_dtype import pandas as pd @@ -515,83 +513,6 @@ def f(group): tm.assert_frame_equal(res, result.loc[key]) -def _check_cython_group_transform_cumulative(pd_op, np_op, dtype): - """ - Check a group transform that executes a cumulative function. - - Parameters - ---------- - pd_op : callable - The pandas cumulative function. - np_op : callable - The analogous one in NumPy. - dtype : type - The specified dtype of the data. - """ - is_datetimelike = False - - data = np.array([[1], [2], [3], [4]], dtype=dtype) - ans = np.zeros_like(data) - - labels = np.array([0, 0, 0, 0], dtype=np.int64) - ngroups = 1 - pd_op(ans, data, labels, ngroups, is_datetimelike) - - tm.assert_numpy_array_equal(np_op(data), ans[:, 0], check_dtype=False) - - -def test_cython_group_transform_cumsum(any_real_dtype): - # see gh-4095 - dtype = np.dtype(any_real_dtype).type - pd_op, np_op = group_cumsum, np.cumsum - _check_cython_group_transform_cumulative(pd_op, np_op, dtype) - - -def test_cython_group_transform_cumprod(): - # see gh-4095 - dtype = np.float64 - pd_op, np_op = group_cumprod_float64, np.cumproduct - _check_cython_group_transform_cumulative(pd_op, np_op, dtype) - - -def test_cython_group_transform_algos(): - # see gh-4095 - is_datetimelike = False - - # with nans - labels = np.array([0, 0, 0, 0, 0], dtype=np.int64) - ngroups = 1 - - data = np.array([[1], [2], [3], [np.nan], [4]], dtype="float64") - actual = np.zeros_like(data) - actual.fill(np.nan) - group_cumprod_float64(actual, data, labels, ngroups, is_datetimelike) - expected = np.array([1, 2, 6, np.nan, 24], dtype="float64") - tm.assert_numpy_array_equal(actual[:, 0], expected) - - actual = np.zeros_like(data) - actual.fill(np.nan) - group_cumsum(actual, data, labels, ngroups, is_datetimelike) - expected = np.array([1, 3, 6, np.nan, 10], dtype="float64") - tm.assert_numpy_array_equal(actual[:, 0], expected) - - # timedelta - is_datetimelike = True - data = np.array([np.timedelta64(1, "ns")] * 5, dtype="m8[ns]")[:, None] - actual = np.zeros_like(data, dtype="int64") - group_cumsum(actual, data.view("int64"), labels, ngroups, is_datetimelike) - expected = np.array( - [ - np.timedelta64(1, "ns"), - np.timedelta64(2, "ns"), - np.timedelta64(3, "ns"), - np.timedelta64(4, "ns"), - np.timedelta64(5, "ns"), - ] - ) - tm.assert_numpy_array_equal(actual[:, 0].view("m8[ns]"), expected) - - @pytest.mark.parametrize( "op, args, targop", [ diff --git a/pandas/tests/libs/__init__.py b/pandas/tests/libs/__init__.py new file mode 100644 index 0000000000000..e69de29bb2d1d diff --git a/pandas/tests/test_join.py b/pandas/tests/libs/test_join.py similarity index 68% rename from pandas/tests/test_join.py rename to pandas/tests/libs/test_join.py index 03198ec3289dd..95d6dcbaf3baf 100644 --- a/pandas/tests/test_join.py +++ b/pandas/tests/libs/test_join.py @@ -2,8 +2,8 @@ import pytest from pandas._libs import join as libjoin +from pandas._libs.join import inner_join, left_outer_join -from pandas import Categorical, DataFrame, Index, merge import pandas._testing as tm @@ -42,6 +42,98 @@ def test_outer_join_indexer(self, dtype): exp = np.array([-1, -1, -1], dtype=np.int64) tm.assert_numpy_array_equal(rindexer, exp) + def test_cython_left_outer_join(self): + left = np.array([0, 1, 2, 1, 2, 0, 0, 1, 2, 3, 3], dtype=np.int64) + right = np.array([1, 1, 0, 4, 2, 2, 1], dtype=np.int64) + max_group = 5 + + ls, rs = left_outer_join(left, right, max_group) + + exp_ls = left.argsort(kind="mergesort") + exp_rs = right.argsort(kind="mergesort") + + exp_li = np.array([0, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 8, 8, 9, 10]) + exp_ri = np.array( + [0, 0, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5, 4, 5, 4, 5, -1, -1] + ) + + exp_ls = exp_ls.take(exp_li) + exp_ls[exp_li == -1] = -1 + + exp_rs = exp_rs.take(exp_ri) + exp_rs[exp_ri == -1] = -1 + + tm.assert_numpy_array_equal(ls, exp_ls, check_dtype=False) + tm.assert_numpy_array_equal(rs, exp_rs, check_dtype=False) + + def test_cython_right_outer_join(self): + left = np.array([0, 1, 2, 1, 2, 0, 0, 1, 2, 3, 3], dtype=np.int64) + right = np.array([1, 1, 0, 4, 2, 2, 1], dtype=np.int64) + max_group = 5 + + rs, ls = left_outer_join(right, left, max_group) + + exp_ls = left.argsort(kind="mergesort") + exp_rs = right.argsort(kind="mergesort") + + # 0 1 1 1 + exp_li = np.array( + [ + 0, + 1, + 2, + 3, + 4, + 5, + 3, + 4, + 5, + 3, + 4, + 5, + # 2 2 4 + 6, + 7, + 8, + 6, + 7, + 8, + -1, + ] + ) + exp_ri = np.array([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6]) + + exp_ls = exp_ls.take(exp_li) + exp_ls[exp_li == -1] = -1 + + exp_rs = exp_rs.take(exp_ri) + exp_rs[exp_ri == -1] = -1 + + tm.assert_numpy_array_equal(ls, exp_ls, check_dtype=False) + tm.assert_numpy_array_equal(rs, exp_rs, check_dtype=False) + + def test_cython_inner_join(self): + left = np.array([0, 1, 2, 1, 2, 0, 0, 1, 2, 3, 3], dtype=np.int64) + right = np.array([1, 1, 0, 4, 2, 2, 1, 4], dtype=np.int64) + max_group = 5 + + ls, rs = inner_join(left, right, max_group) + + exp_ls = left.argsort(kind="mergesort") + exp_rs = right.argsort(kind="mergesort") + + exp_li = np.array([0, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 8, 8]) + exp_ri = np.array([0, 0, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5, 4, 5, 4, 5]) + + exp_ls = exp_ls.take(exp_li) + exp_ls[exp_li == -1] = -1 + + exp_rs = exp_rs.take(exp_ri) + exp_rs[exp_ri == -1] = -1 + + tm.assert_numpy_array_equal(ls, exp_ls, check_dtype=False) + tm.assert_numpy_array_equal(rs, exp_rs, check_dtype=False) + def test_left_join_indexer_unique(): a = np.array([1, 2, 3, 4, 5], dtype=np.int64) @@ -243,10 +335,10 @@ def test_left_join_indexer(): def test_left_join_indexer2(): - idx = Index([1, 1, 2, 5]) - idx2 = Index([1, 2, 5, 7, 9]) + idx = np.array([1, 1, 2, 5], dtype=np.int64) + idx2 = np.array([1, 2, 5, 7, 9], dtype=np.int64) - res, lidx, ridx = libjoin.left_join_indexer(idx2.values, idx.values) + res, lidx, ridx = libjoin.left_join_indexer(idx2, idx) exp_res = np.array([1, 1, 2, 5, 7, 9], dtype=np.int64) tm.assert_almost_equal(res, exp_res) @@ -259,10 +351,10 @@ def test_left_join_indexer2(): def test_outer_join_indexer2(): - idx = Index([1, 1, 2, 5]) - idx2 = Index([1, 2, 5, 7, 9]) + idx = np.array([1, 1, 2, 5], dtype=np.int64) + idx2 = np.array([1, 2, 5, 7, 9], dtype=np.int64) - res, lidx, ridx = libjoin.outer_join_indexer(idx2.values, idx.values) + res, lidx, ridx = libjoin.outer_join_indexer(idx2, idx) exp_res = np.array([1, 1, 2, 5, 7, 9], dtype=np.int64) tm.assert_almost_equal(res, exp_res) @@ -275,10 +367,10 @@ def test_outer_join_indexer2(): def test_inner_join_indexer2(): - idx = Index([1, 1, 2, 5]) - idx2 = Index([1, 2, 5, 7, 9]) + idx = np.array([1, 1, 2, 5], dtype=np.int64) + idx2 = np.array([1, 2, 5, 7, 9], dtype=np.int64) - res, lidx, ridx = libjoin.inner_join_indexer(idx2.values, idx.values) + res, lidx, ridx = libjoin.inner_join_indexer(idx2, idx) exp_res = np.array([1, 1, 2, 5], dtype=np.int64) tm.assert_almost_equal(res, exp_res) @@ -288,59 +380,3 @@ def test_inner_join_indexer2(): exp_ridx = np.array([0, 1, 2, 3], dtype=np.int64) tm.assert_almost_equal(ridx, exp_ridx) - - -def test_merge_join_categorical_multiindex(): - # From issue 16627 - a = { - "Cat1": Categorical(["a", "b", "a", "c", "a", "b"], ["a", "b", "c"]), - "Int1": [0, 1, 0, 1, 0, 0], - } - a = DataFrame(a) - - b = { - "Cat": Categorical(["a", "b", "c", "a", "b", "c"], ["a", "b", "c"]), - "Int": [0, 0, 0, 1, 1, 1], - "Factor": [1.1, 1.2, 1.3, 1.4, 1.5, 1.6], - } - b = DataFrame(b).set_index(["Cat", "Int"])["Factor"] - - expected = merge( - a, - b.reset_index(), - left_on=["Cat1", "Int1"], - right_on=["Cat", "Int"], - how="left", - ) - result = a.join(b, on=["Cat1", "Int1"]) - expected = expected.drop(["Cat", "Int"], axis=1) - tm.assert_frame_equal(expected, result) - - # Same test, but with ordered categorical - a = { - "Cat1": Categorical( - ["a", "b", "a", "c", "a", "b"], ["b", "a", "c"], ordered=True - ), - "Int1": [0, 1, 0, 1, 0, 0], - } - a = DataFrame(a) - - b = { - "Cat": Categorical( - ["a", "b", "c", "a", "b", "c"], ["b", "a", "c"], ordered=True - ), - "Int": [0, 0, 0, 1, 1, 1], - "Factor": [1.1, 1.2, 1.3, 1.4, 1.5, 1.6], - } - b = DataFrame(b).set_index(["Cat", "Int"])["Factor"] - - expected = merge( - a, - b.reset_index(), - left_on=["Cat1", "Int1"], - right_on=["Cat", "Int"], - how="left", - ) - result = a.join(b, on=["Cat1", "Int1"]) - expected = expected.drop(["Cat", "Int"], axis=1) - tm.assert_frame_equal(expected, result) diff --git a/pandas/tests/test_lib.py b/pandas/tests/libs/test_lib.py similarity index 100% rename from pandas/tests/test_lib.py rename to pandas/tests/libs/test_lib.py diff --git a/pandas/tests/reshape/merge/test_join.py b/pandas/tests/reshape/merge/test_join.py index 8108cd14b872a..af1e95313f365 100644 --- a/pandas/tests/reshape/merge/test_join.py +++ b/pandas/tests/reshape/merge/test_join.py @@ -2,8 +2,6 @@ from numpy.random import randn import pytest -from pandas._libs.join import inner_join, left_outer_join - import pandas as pd from pandas import DataFrame, Index, MultiIndex, Series, concat, merge import pandas._testing as tm @@ -43,96 +41,6 @@ def setup_method(self, method): {"MergedA": data["A"], "MergedD": data["D"]}, index=data["C"] ) - def test_cython_left_outer_join(self): - left = a_([0, 1, 2, 1, 2, 0, 0, 1, 2, 3, 3], dtype=np.int64) - right = a_([1, 1, 0, 4, 2, 2, 1], dtype=np.int64) - max_group = 5 - - ls, rs = left_outer_join(left, right, max_group) - - exp_ls = left.argsort(kind="mergesort") - exp_rs = right.argsort(kind="mergesort") - - exp_li = a_([0, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 8, 8, 9, 10]) - exp_ri = a_([0, 0, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5, 4, 5, 4, 5, -1, -1]) - - exp_ls = exp_ls.take(exp_li) - exp_ls[exp_li == -1] = -1 - - exp_rs = exp_rs.take(exp_ri) - exp_rs[exp_ri == -1] = -1 - - tm.assert_numpy_array_equal(ls, exp_ls, check_dtype=False) - tm.assert_numpy_array_equal(rs, exp_rs, check_dtype=False) - - def test_cython_right_outer_join(self): - left = a_([0, 1, 2, 1, 2, 0, 0, 1, 2, 3, 3], dtype=np.int64) - right = a_([1, 1, 0, 4, 2, 2, 1], dtype=np.int64) - max_group = 5 - - rs, ls = left_outer_join(right, left, max_group) - - exp_ls = left.argsort(kind="mergesort") - exp_rs = right.argsort(kind="mergesort") - - # 0 1 1 1 - exp_li = a_( - [ - 0, - 1, - 2, - 3, - 4, - 5, - 3, - 4, - 5, - 3, - 4, - 5, - # 2 2 4 - 6, - 7, - 8, - 6, - 7, - 8, - -1, - ] - ) - exp_ri = a_([0, 0, 0, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6]) - - exp_ls = exp_ls.take(exp_li) - exp_ls[exp_li == -1] = -1 - - exp_rs = exp_rs.take(exp_ri) - exp_rs[exp_ri == -1] = -1 - - tm.assert_numpy_array_equal(ls, exp_ls, check_dtype=False) - tm.assert_numpy_array_equal(rs, exp_rs, check_dtype=False) - - def test_cython_inner_join(self): - left = a_([0, 1, 2, 1, 2, 0, 0, 1, 2, 3, 3], dtype=np.int64) - right = a_([1, 1, 0, 4, 2, 2, 1, 4], dtype=np.int64) - max_group = 5 - - ls, rs = inner_join(left, right, max_group) - - exp_ls = left.argsort(kind="mergesort") - exp_rs = right.argsort(kind="mergesort") - - exp_li = a_([0, 1, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 8, 8]) - exp_ri = a_([0, 0, 0, 1, 2, 3, 1, 2, 3, 1, 2, 3, 4, 5, 4, 5, 4, 5]) - - exp_ls = exp_ls.take(exp_li) - exp_ls[exp_li == -1] = -1 - - exp_rs = exp_rs.take(exp_ri) - exp_rs[exp_ri == -1] = -1 - - tm.assert_numpy_array_equal(ls, exp_ls, check_dtype=False) - tm.assert_numpy_array_equal(rs, exp_rs, check_dtype=False) - def test_left_outer_join(self): joined_key2 = merge(self.df, self.df2, on="key2") _check_join(self.df, self.df2, joined_key2, ["key2"], how="left") diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 7d701d26185f1..c4c9b0e516192 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -2227,3 +2227,59 @@ def test_categorical_non_unique_monotonic(n_categories): index=left_index, ) tm.assert_frame_equal(expected, result) + + +def test_merge_join_categorical_multiindex(): + # From issue 16627 + a = { + "Cat1": Categorical(["a", "b", "a", "c", "a", "b"], ["a", "b", "c"]), + "Int1": [0, 1, 0, 1, 0, 0], + } + a = DataFrame(a) + + b = { + "Cat": Categorical(["a", "b", "c", "a", "b", "c"], ["a", "b", "c"]), + "Int": [0, 0, 0, 1, 1, 1], + "Factor": [1.1, 1.2, 1.3, 1.4, 1.5, 1.6], + } + b = DataFrame(b).set_index(["Cat", "Int"])["Factor"] + + expected = merge( + a, + b.reset_index(), + left_on=["Cat1", "Int1"], + right_on=["Cat", "Int"], + how="left", + ) + expected = expected.drop(["Cat", "Int"], axis=1) + result = a.join(b, on=["Cat1", "Int1"]) + tm.assert_frame_equal(expected, result) + + # Same test, but with ordered categorical + a = { + "Cat1": Categorical( + ["a", "b", "a", "c", "a", "b"], ["b", "a", "c"], ordered=True + ), + "Int1": [0, 1, 0, 1, 0, 0], + } + a = DataFrame(a) + + b = { + "Cat": Categorical( + ["a", "b", "c", "a", "b", "c"], ["b", "a", "c"], ordered=True + ), + "Int": [0, 0, 0, 1, 1, 1], + "Factor": [1.1, 1.2, 1.3, 1.4, 1.5, 1.6], + } + b = DataFrame(b).set_index(["Cat", "Int"])["Factor"] + + expected = merge( + a, + b.reset_index(), + left_on=["Cat1", "Int1"], + right_on=["Cat", "Int"], + how="left", + ) + expected = expected.drop(["Cat", "Int"], axis=1) + result = a.join(b, on=["Cat1", "Int1"]) + tm.assert_frame_equal(expected, result) diff --git a/pandas/tests/test_algos.py b/pandas/tests/test_algos.py index 3a1279c481a1d..ee8e2385fe698 100644 --- a/pandas/tests/test_algos.py +++ b/pandas/tests/test_algos.py @@ -3,11 +3,9 @@ import struct import numpy as np -from numpy.random import RandomState import pytest from pandas._libs import algos as libalgos, hashtable as ht -from pandas._libs.groupby import group_var_float32, group_var_float64 from pandas.compat import IS64 from pandas.compat.numpy import np_array_datetime64_compat import pandas.util._test_decorators as td @@ -1409,122 +1407,6 @@ def test_unique_tuples(self, arr, unique): tm.assert_numpy_array_equal(result, expected) -class GroupVarTestMixin: - def test_group_var_generic_1d(self): - prng = RandomState(1234) - - out = (np.nan * np.ones((5, 1))).astype(self.dtype) - counts = np.zeros(5, dtype="int64") - values = 10 * prng.rand(15, 1).astype(self.dtype) - labels = np.tile(np.arange(5), (3,)).astype("int64") - - expected_out = ( - np.squeeze(values).reshape((5, 3), order="F").std(axis=1, ddof=1) ** 2 - )[:, np.newaxis] - expected_counts = counts + 3 - - self.algo(out, counts, values, labels) - assert np.allclose(out, expected_out, self.rtol) - tm.assert_numpy_array_equal(counts, expected_counts) - - def test_group_var_generic_1d_flat_labels(self): - prng = RandomState(1234) - - out = (np.nan * np.ones((1, 1))).astype(self.dtype) - counts = np.zeros(1, dtype="int64") - values = 10 * prng.rand(5, 1).astype(self.dtype) - labels = np.zeros(5, dtype="int64") - - expected_out = np.array([[values.std(ddof=1) ** 2]]) - expected_counts = counts + 5 - - self.algo(out, counts, values, labels) - - assert np.allclose(out, expected_out, self.rtol) - tm.assert_numpy_array_equal(counts, expected_counts) - - def test_group_var_generic_2d_all_finite(self): - prng = RandomState(1234) - - out = (np.nan * np.ones((5, 2))).astype(self.dtype) - counts = np.zeros(5, dtype="int64") - values = 10 * prng.rand(10, 2).astype(self.dtype) - labels = np.tile(np.arange(5), (2,)).astype("int64") - - expected_out = np.std(values.reshape(2, 5, 2), ddof=1, axis=0) ** 2 - expected_counts = counts + 2 - - self.algo(out, counts, values, labels) - assert np.allclose(out, expected_out, self.rtol) - tm.assert_numpy_array_equal(counts, expected_counts) - - def test_group_var_generic_2d_some_nan(self): - prng = RandomState(1234) - - out = (np.nan * np.ones((5, 2))).astype(self.dtype) - counts = np.zeros(5, dtype="int64") - values = 10 * prng.rand(10, 2).astype(self.dtype) - values[:, 1] = np.nan - labels = np.tile(np.arange(5), (2,)).astype("int64") - - expected_out = np.vstack( - [ - values[:, 0].reshape(5, 2, order="F").std(ddof=1, axis=1) ** 2, - np.nan * np.ones(5), - ] - ).T.astype(self.dtype) - expected_counts = counts + 2 - - self.algo(out, counts, values, labels) - tm.assert_almost_equal(out, expected_out, rtol=0.5e-06) - tm.assert_numpy_array_equal(counts, expected_counts) - - def test_group_var_constant(self): - # Regression test from GH 10448. - - out = np.array([[np.nan]], dtype=self.dtype) - counts = np.array([0], dtype="int64") - values = 0.832845131556193 * np.ones((3, 1), dtype=self.dtype) - labels = np.zeros(3, dtype="int64") - - self.algo(out, counts, values, labels) - - assert counts[0] == 3 - assert out[0, 0] >= 0 - tm.assert_almost_equal(out[0, 0], 0.0) - - -class TestGroupVarFloat64(GroupVarTestMixin): - __test__ = True - - algo = staticmethod(group_var_float64) - dtype = np.float64 - rtol = 1e-5 - - def test_group_var_large_inputs(self): - - prng = RandomState(1234) - - out = np.array([[np.nan]], dtype=self.dtype) - counts = np.array([0], dtype="int64") - values = (prng.rand(10 ** 6) + 10 ** 12).astype(self.dtype) - values.shape = (10 ** 6, 1) - labels = np.zeros(10 ** 6, dtype="int64") - - self.algo(out, counts, values, labels) - - assert counts[0] == 10 ** 6 - tm.assert_almost_equal(out[0, 0], 1.0 / 12, rtol=0.5e-3) - - -class TestGroupVarFloat32(GroupVarTestMixin): - __test__ = True - - algo = staticmethod(group_var_float32) - dtype = np.float32 - rtol = 1e-2 - - class TestHashTable: def test_string_hashtable_set_item_signature(self): # GH#30419 fix typing in StringHashTable.set_item to prevent segfault
https://api.github.com/repos/pandas-dev/pandas/pulls/37324
2020-10-21T23:03:25Z
2020-10-22T22:13:36Z
2020-10-22T22:13:36Z
2020-10-22T22:16:39Z
DOC: Add protocol value '5' to pickle #37316
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index d658d799f1fb8..eeaf23fdc06f5 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2780,7 +2780,7 @@ def to_pickle( protocol : int Int which indicates which protocol should be used by the pickler, default HIGHEST_PROTOCOL (see [1]_ paragraph 12.1.2). The possible - values are 0, 1, 2, 3, 4. A negative value for the protocol + values are 0, 1, 2, 3, 4, 5. A negative value for the protocol parameter is equivalent to setting its value to HIGHEST_PROTOCOL. .. [1] https://docs.python.org/3/library/pickle.html.
- [X] closes #37316
https://api.github.com/repos/pandas-dev/pandas/pulls/37322
2020-10-21T22:18:57Z
2020-10-22T00:11:03Z
2020-10-22T00:11:03Z
2020-10-22T16:04:19Z
BUG: Index._id
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 6b71e455782e3..3b28361399fba 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -220,7 +220,7 @@ def _outer_indexer(self, left, right): _typ = "index" _data: Union[ExtensionArray, np.ndarray] - _id: _Identity + _id: Optional[_Identity] = None _name: Label = None # MultiIndex.levels previously allowed setting the index name. We # don't allow this anymore, and raise if it happens rather than @@ -541,10 +541,14 @@ def is_(self, other) -> bool: -------- Index.identical : Works like ``Index.is_`` but also checks metadata. """ - try: - return self._id is other._id - except AttributeError: + if self is other: + return True + elif not hasattr(other, "_id"): return False + elif com.any_none(self._id, other._id): + return False + else: + return self._id is other._id def _reset_identity(self) -> None: """
Fixes #37213.
https://api.github.com/repos/pandas-dev/pandas/pulls/37321
2020-10-21T20:16:12Z
2020-10-22T23:31:02Z
2020-10-22T23:31:02Z
2020-10-24T08:05:43Z
ENH: enable Series.info()
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 71903d10a6983..5becbf0a87472 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -217,6 +217,7 @@ Other enhancements - Added "Juneteenth National Independence Day" to ``USFederalHolidayCalendar``. See also `Other API changes`_. - :meth:`.Rolling.var`, :meth:`.Expanding.var`, :meth:`.Rolling.std`, :meth:`.Expanding.std` now support `Numba <http://numba.pydata.org/>`_ execution with the ``engine`` keyword (:issue:`44461`) +- :meth:`Series.info` has been added, for compatibility with :meth:`DataFrame.info` (:issue:`5167`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 8c85c4e961d99..8ebdb3b890d77 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -206,6 +206,7 @@ format as fmt, ) from pandas.io.formats.info import ( + INFO_DOCSTRING, DataFrameInfo, frame_sub_kwargs, ) @@ -3138,7 +3139,7 @@ def to_xml( return xml_formatter.write_output() # ---------------------------------------------------------------------- - @doc(DataFrameInfo.render, **frame_sub_kwargs) + @doc(INFO_DOCSTRING, **frame_sub_kwargs) def info( self, verbose: bool | None = None, diff --git a/pandas/core/series.py b/pandas/core/series.py index ffa31b4f66211..b3133ee1275a1 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -139,6 +139,11 @@ from pandas.core.tools.datetimes import to_datetime import pandas.io.formats.format as fmt +from pandas.io.formats.info import ( + INFO_DOCSTRING, + SeriesInfo, + series_sub_kwargs, +) import pandas.plotting if TYPE_CHECKING: @@ -4914,6 +4919,22 @@ def replace( method=method, ) + @doc(INFO_DOCSTRING, **series_sub_kwargs) + def info( + self, + verbose: bool | None = None, + buf: IO[str] | None = None, + max_cols: int | None = None, + memory_usage: bool | str | None = None, + show_counts: bool = True, + ) -> None: + return SeriesInfo(self, memory_usage).render( + buf=buf, + max_cols=max_cols, + verbose=verbose, + show_counts=show_counts, + ) + def _replace_single(self, to_replace, method: str, inplace: bool, limit): """ Replaces values in a Series using the fill method specified when no diff --git a/pandas/io/formats/info.py b/pandas/io/formats/info.py index 9340d020cd6ce..4a9310c6dccf8 100644 --- a/pandas/io/formats/info.py +++ b/pandas/io/formats/info.py @@ -20,7 +20,6 @@ Dtype, WriteBuffer, ) -from pandas.util._decorators import doc from pandas.core.indexes.api import Index @@ -51,7 +50,11 @@ only if the DataFrame is smaller than ``pandas.options.display.max_info_rows`` and ``pandas.options.display.max_info_columns``. A value of True always - shows the counts, and False never shows the counts. + shows the counts, and False never shows the counts.""" +) + +null_counts_sub = dedent( + """ null_counts : bool, optional .. deprecated:: 1.2.0 Use show_counts instead.""" @@ -157,12 +160,94 @@ "type_sub": " and columns", "max_cols_sub": frame_max_cols_sub, "show_counts_sub": show_counts_sub, + "null_counts_sub": null_counts_sub, "examples_sub": frame_examples_sub, "see_also_sub": frame_see_also_sub, "version_added_sub": "", } +series_examples_sub = dedent( + """\ + >>> int_values = [1, 2, 3, 4, 5] + >>> text_values = ['alpha', 'beta', 'gamma', 'delta', 'epsilon'] + >>> s = pd.Series(text_values, index=int_values) + >>> s.info() + <class 'pandas.core.series.Series'> + Int64Index: 5 entries, 1 to 5 + Series name: None + Non-Null Count Dtype + -------------- ----- + 5 non-null object + dtypes: object(1) + memory usage: 80.0+ bytes + + Prints a summary excluding information about its values: + + >>> s.info(verbose=False) + <class 'pandas.core.series.Series'> + Int64Index: 5 entries, 1 to 5 + dtypes: object(1) + memory usage: 80.0+ bytes + + Pipe output of Series.info to buffer instead of sys.stdout, get + buffer content and writes to a text file: + + >>> import io + >>> buffer = io.StringIO() + >>> s.info(buf=buffer) + >>> s = buffer.getvalue() + >>> with open("df_info.txt", "w", + ... encoding="utf-8") as f: # doctest: +SKIP + ... f.write(s) + 260 + + The `memory_usage` parameter allows deep introspection mode, specially + useful for big Series and fine-tune memory optimization: + + >>> random_strings_array = np.random.choice(['a', 'b', 'c'], 10 ** 6) + >>> s = pd.Series(np.random.choice(['a', 'b', 'c'], 10 ** 6)) + >>> s.info() + <class 'pandas.core.series.Series'> + RangeIndex: 1000000 entries, 0 to 999999 + Series name: None + Non-Null Count Dtype + -------------- ----- + 1000000 non-null object + dtypes: object(1) + memory usage: 7.6+ MB + + >>> s.info(memory_usage='deep') + <class 'pandas.core.series.Series'> + RangeIndex: 1000000 entries, 0 to 999999 + Series name: None + Non-Null Count Dtype + -------------- ----- + 1000000 non-null object + dtypes: object(1) + memory usage: 55.3 MB""" +) + + +series_see_also_sub = dedent( + """\ + Series.describe: Generate descriptive statistics of Series. + Series.memory_usage: Memory usage of Series.""" +) + + +series_sub_kwargs = { + "klass": "Series", + "type_sub": "", + "max_cols_sub": "", + "show_counts_sub": show_counts_sub, + "null_counts_sub": "", + "examples_sub": series_examples_sub, + "see_also_sub": series_see_also_sub, + "version_added_sub": "\n.. versionadded:: 1.4.0\n", +} + + INFO_DOCSTRING = dedent( """ Print a concise summary of a {klass}. @@ -181,7 +266,7 @@ buf : writable buffer, defaults to sys.stdout Where to send the output. By default, the output is printed to sys.stdout. Pass a writable buffer if you need to further process - the output. + the output.\ {max_cols_sub} memory_usage : bool, str, optional Specifies whether total memory usage of the {klass} @@ -196,7 +281,7 @@ consume the same memory amount for corresponding dtypes. With deep memory introspection, a real memory usage calculation is performed at the cost of computational resources. - {show_counts_sub} + {show_counts_sub}{null_counts_sub} Returns ------- @@ -422,16 +507,6 @@ def memory_usage_bytes(self) -> int: deep = False return self.data.memory_usage(index=True, deep=deep).sum() - @doc( - INFO_DOCSTRING, - klass="DataFrame", - type_sub=" and columns", - max_cols_sub=frame_max_cols_sub, - show_counts_sub=show_counts_sub, - examples_sub=frame_examples_sub, - see_also_sub=frame_see_also_sub, - version_added_sub="", - ) def render( self, *, @@ -449,6 +524,69 @@ def render( printer.to_buffer(buf) +class SeriesInfo(BaseInfo): + """ + Class storing series-specific info. + """ + + def __init__( + self, + data: Series, + memory_usage: bool | str | None = None, + ): + self.data: Series = data + self.memory_usage = _initialize_memory_usage(memory_usage) + + def render( + self, + *, + buf: WriteBuffer[str] | None = None, + max_cols: int | None = None, + verbose: bool | None = None, + show_counts: bool | None = None, + ) -> None: + if max_cols is not None: + raise ValueError( + "Argument `max_cols` can only be passed " + "in DataFrame.info, not Series.info" + ) + printer = SeriesInfoPrinter( + info=self, + verbose=verbose, + show_counts=show_counts, + ) + printer.to_buffer(buf) + + @property + def non_null_counts(self) -> Sequence[int]: + return [self.data.count()] + + @property + def dtypes(self) -> Iterable[Dtype]: + return [self.data.dtypes] + + @property + def dtype_counts(self): + from pandas.core.frame import DataFrame + + return _get_dataframe_dtype_counts(DataFrame(self.data)) + + @property + def memory_usage_bytes(self) -> int: + """Memory usage in bytes. + + Returns + ------- + memory_usage_bytes : int + Object's total memory usage in bytes. + """ + if self.memory_usage == "deep": + deep = True + else: + deep = False + return self.data.memory_usage(index=True, deep=deep) + + class InfoPrinterAbstract: """ Class for printing dataframe or series info. @@ -548,6 +686,49 @@ def _create_table_builder(self) -> DataFrameTableBuilder: ) +class SeriesInfoPrinter(InfoPrinterAbstract): + """Class for printing series info. + + Parameters + ---------- + info : SeriesInfo + Instance of SeriesInfo. + verbose : bool, optional + Whether to print the full summary. + show_counts : bool, optional + Whether to show the non-null counts. + """ + + def __init__( + self, + info: SeriesInfo, + verbose: bool | None = None, + show_counts: bool | None = None, + ): + self.info = info + self.data = info.data + self.verbose = verbose + self.show_counts = self._initialize_show_counts(show_counts) + + def _create_table_builder(self) -> SeriesTableBuilder: + """ + Create instance of table builder based on verbosity. + """ + if self.verbose or self.verbose is None: + return SeriesTableBuilderVerbose( + info=self.info, + with_counts=self.show_counts, + ) + else: + return SeriesTableBuilderNonVerbose(info=self.info) + + def _initialize_show_counts(self, show_counts: bool | None) -> bool: + if show_counts is None: + return True + else: + return show_counts + + class TableBuilderAbstract(ABC): """ Abstract builder for info table. @@ -832,6 +1013,102 @@ def _gen_columns(self) -> Iterator[str]: yield pprint_thing(col) +class SeriesTableBuilder(TableBuilderAbstract): + """ + Abstract builder for series info table. + + Parameters + ---------- + info : SeriesInfo. + Instance of SeriesInfo. + """ + + def __init__(self, *, info: SeriesInfo): + self.info: SeriesInfo = info + + def get_lines(self) -> list[str]: + self._lines = [] + self._fill_non_empty_info() + return self._lines + + @property + def data(self) -> Series: + """Series.""" + return self.info.data + + def add_memory_usage_line(self) -> None: + """Add line containing memory usage.""" + self._lines.append(f"memory usage: {self.memory_usage_string}") + + @abstractmethod + def _fill_non_empty_info(self) -> None: + """Add lines to the info table, pertaining to non-empty series.""" + + +class SeriesTableBuilderNonVerbose(SeriesTableBuilder): + """ + Series info table builder for non-verbose output. + """ + + def _fill_non_empty_info(self) -> None: + """Add lines to the info table, pertaining to non-empty series.""" + self.add_object_type_line() + self.add_index_range_line() + self.add_dtypes_line() + if self.display_memory_usage: + self.add_memory_usage_line() + + +class SeriesTableBuilderVerbose(SeriesTableBuilder, TableBuilderVerboseMixin): + """ + Series info table builder for verbose output. + """ + + def __init__( + self, + *, + info: SeriesInfo, + with_counts: bool, + ): + self.info = info + self.with_counts = with_counts + self.strrows: Sequence[Sequence[str]] = list(self._gen_rows()) + self.gross_column_widths: Sequence[int] = self._get_gross_column_widths() + + def _fill_non_empty_info(self) -> None: + """Add lines to the info table, pertaining to non-empty series.""" + self.add_object_type_line() + self.add_index_range_line() + self.add_series_name_line() + self.add_header_line() + self.add_separator_line() + self.add_body_lines() + self.add_dtypes_line() + if self.display_memory_usage: + self.add_memory_usage_line() + + def add_series_name_line(self): + self._lines.append(f"Series name: {self.data.name}") + + @property + def headers(self) -> Sequence[str]: + """Headers names of the columns in verbose table.""" + if self.with_counts: + return ["Non-Null Count", "Dtype"] + return ["Dtype"] + + def _gen_rows_without_counts(self) -> Iterator[Sequence[str]]: + """Iterator with string representation of body data without counts.""" + yield from self._gen_dtypes() + + def _gen_rows_with_counts(self) -> Iterator[Sequence[str]]: + """Iterator with string representation of body data with counts.""" + yield from zip( + self._gen_non_null_counts(), + self._gen_dtypes(), + ) + + def _get_dataframe_dtype_counts(df: DataFrame) -> Mapping[str, int]: """ Create mapping between datatypes and their number of occurrences. diff --git a/pandas/tests/io/formats/test_series_info.py b/pandas/tests/io/formats/test_series_info.py new file mode 100644 index 0000000000000..1f755d675d078 --- /dev/null +++ b/pandas/tests/io/formats/test_series_info.py @@ -0,0 +1,183 @@ +from io import StringIO +from string import ascii_uppercase as uppercase +import textwrap + +import numpy as np +import pytest + +from pandas.compat import PYPY + +from pandas import ( + CategoricalIndex, + MultiIndex, + Series, + date_range, +) + + +def test_info_categorical_column_just_works(): + n = 2500 + data = np.array(list("abcdefghij")).take(np.random.randint(0, 10, size=n)) + s = Series(data).astype("category") + s.isna() + buf = StringIO() + s.info(buf=buf) + + s2 = s[s == "d"] + buf = StringIO() + s2.info(buf=buf) + + +def test_info_categorical(): + # GH14298 + idx = CategoricalIndex(["a", "b"]) + s = Series(np.zeros(2), index=idx) + buf = StringIO() + s.info(buf=buf) + + +@pytest.mark.parametrize("verbose", [True, False]) +def test_info_series(verbose): + index = MultiIndex( + levels=[["foo", "bar", "baz", "qux"], ["one", "two", "three"]], + codes=[[0, 0, 0, 1, 1, 2, 2, 3, 3, 3], [0, 1, 2, 0, 1, 1, 2, 0, 1, 2]], + names=["first", "second"], + ) + s = Series(range(len(index)), index=index, name="sth") + buf = StringIO() + s.info(verbose=verbose, buf=buf) + result = buf.getvalue() + + expected = textwrap.dedent( + """\ + <class 'pandas.core.series.Series'> + MultiIndex: 10 entries, ('foo', 'one') to ('qux', 'three') + """ + ) + if verbose: + expected += textwrap.dedent( + """\ + Series name: sth + Non-Null Count Dtype + -------------- ----- + 10 non-null int64 + """ + ) + expected += textwrap.dedent( + f"""\ + dtypes: int64(1) + memory usage: {s.memory_usage()}.0+ bytes + """ + ) + assert result == expected + + +def test_info_memory(): + s = Series([1, 2], dtype="i8") + buf = StringIO() + s.info(buf=buf) + result = buf.getvalue() + memory_bytes = float(s.memory_usage()) + expected = textwrap.dedent( + f"""\ + <class 'pandas.core.series.Series'> + RangeIndex: 2 entries, 0 to 1 + Series name: None + Non-Null Count Dtype + -------------- ----- + 2 non-null int64 + dtypes: int64(1) + memory usage: {memory_bytes} bytes + """ + ) + assert result == expected + + +def test_info_wide(): + s = Series(np.random.randn(101)) + msg = "Argument `max_cols` can only be passed in DataFrame.info, not Series.info" + with pytest.raises(ValueError, match=msg): + s.info(max_cols=1) + + +def test_info_shows_dtypes(): + dtypes = [ + "int64", + "float64", + "datetime64[ns]", + "timedelta64[ns]", + "complex128", + "object", + "bool", + ] + n = 10 + for dtype in dtypes: + s = Series(np.random.randint(2, size=n).astype(dtype)) + buf = StringIO() + s.info(buf=buf) + res = buf.getvalue() + name = f"{n:d} non-null {dtype}" + assert name in res + + +@pytest.mark.skipif(PYPY, reason="on PyPy deep=True doesn't change result") +def test_info_memory_usage_deep_not_pypy(): + s_with_object_index = Series({"a": [1]}, index=["foo"]) + assert s_with_object_index.memory_usage( + index=True, deep=True + ) > s_with_object_index.memory_usage(index=True) + + s_object = Series({"a": ["a"]}) + assert s_object.memory_usage(deep=True) > s_object.memory_usage() + + +@pytest.mark.skipif(not PYPY, reason="on PyPy deep=True does not change result") +def test_info_memory_usage_deep_pypy(): + s_with_object_index = Series({"a": [1]}, index=["foo"]) + assert s_with_object_index.memory_usage( + index=True, deep=True + ) == s_with_object_index.memory_usage(index=True) + + s_object = Series({"a": ["a"]}) + assert s_object.memory_usage(deep=True) == s_object.memory_usage() + + +@pytest.mark.parametrize( + "series, plus", + [ + (Series(1, index=[1, 2, 3]), False), + (Series(1, index=list("ABC")), True), + (Series(1, index=MultiIndex.from_product([range(3), range(3)])), False), + ( + Series(1, index=MultiIndex.from_product([range(3), ["foo", "bar"]])), + True, + ), + ], +) +def test_info_memory_usage_qualified(series, plus): + buf = StringIO() + series.info(buf=buf) + if plus: + assert "+" in buf.getvalue() + else: + assert "+" not in buf.getvalue() + + +def test_info_memory_usage_bug_on_multiindex(): + # GH 14308 + # memory usage introspection should not materialize .values + N = 100 + M = len(uppercase) + index = MultiIndex.from_product( + [list(uppercase), date_range("20160101", periods=N)], + names=["id", "date"], + ) + s = Series(np.random.randn(N * M), index=index) + + unstacked = s.unstack("id") + assert s.values.nbytes == unstacked.values.nbytes + assert s.memory_usage(deep=True) > unstacked.memory_usage(deep=True).sum() + + # high upper bound + diff = unstacked.memory_usage(deep=True).sum() - s.memory_usage(deep=True) + assert diff < 2000 diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 4e4eb89328540..a01b8d304d05d 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -110,12 +110,6 @@ def test_not_hashable(self): def test_contains(self, datetime_series): tm.assert_contains_all(datetime_series.index, datetime_series) - def test_raise_on_info(self): - s = Series(np.random.randn(10)) - msg = "'Series' object has no attribute 'info'" - with pytest.raises(AttributeError, match=msg): - s.info() - def test_axis_alias(self): s = Series([1, 2, np.nan]) tm.assert_series_equal(s.dropna(axis="rows"), s.dropna(axis="index"))
- [ ] closes #5167 - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry I took over https://github.com/pandas-dev/pandas/pull/31796 from @MarcoGorelli. In this PR I took the tests and the docstring from https://github.com/pandas-dev/pandas/pull/31796, refactored tests (separated into dataframe and series-related only test classes). Then on top of the recent changes (https://github.com/pandas-dev/pandas/pull/36752) I implemented series info. New classes: - ``SeriesInfo`` (store data, which will be used in the outputs) - ``SeriesInfoPrinter`` (basically creator of the appropriate table builder) - ``SeriesTableBuilder`` (both Verbose and NonVerbose) - ``TableBuilderVerboseMixin`` (shared functionality for verbose info builders of both dataframe and series) It seems to me that tests are not sufficient enough. In particular, it seems that empty series info should be covered. Currently there is a special empty dataframe info, but for series info there is just a generic verbose info with zero items. If there is a need for a dedicated empty series info, then I would need to add method ``_fill_empty_info`` into ``SeriesTableBuilder``. Static typing makes code quite verbose. In some cases we have the very same methods/properties, but with different type annotations to satisfy type checking (methods are small, but anyway). If somebody can suggest me a better way to handle it, then that would be great.
https://api.github.com/repos/pandas-dev/pandas/pulls/37320
2020-10-21T19:26:28Z
2021-12-01T01:30:44Z
2021-12-01T01:30:44Z
2021-12-01T01:30:53Z
TST/REF: collect tests by method
diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index 55465dffd2027..e1ce10970f07b 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -185,6 +185,53 @@ def test_setitem_extension_types(self, obj, dtype): tm.assert_frame_equal(df, expected) + def test_setitem_dt64_ndarray_with_NaT_and_diff_time_units(self): + # GH#7492 + data_ns = np.array([1, "nat"], dtype="datetime64[ns]") + result = Series(data_ns).to_frame() + result["new"] = data_ns + expected = DataFrame({0: [1, None], "new": [1, None]}, dtype="datetime64[ns]") + tm.assert_frame_equal(result, expected) + + # OutOfBoundsDatetime error shouldn't occur + data_s = np.array([1, "nat"], dtype="datetime64[s]") + result["new"] = data_s + expected = DataFrame({0: [1, None], "new": [1e9, None]}, dtype="datetime64[ns]") + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"]) + def test_frame_setitem_datetime64_col_other_units(self, unit): + # Check that non-nano dt64 values get cast to dt64 on setitem + # into a not-yet-existing column + n = 100 + + dtype = np.dtype(f"M8[{unit}]") + vals = np.arange(n, dtype=np.int64).view(dtype) + ex_vals = vals.astype("datetime64[ns]") + + df = DataFrame({"ints": np.arange(n)}, index=np.arange(n)) + df[unit] = vals + + assert df[unit].dtype == np.dtype("M8[ns]") + assert (df[unit].values == ex_vals).all() + + @pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"]) + def test_frame_setitem_existing_datetime64_col_other_units(self, unit): + # Check that non-nano dt64 values get cast to dt64 on setitem + # into an already-existing dt64 column + n = 100 + + dtype = np.dtype(f"M8[{unit}]") + vals = np.arange(n, dtype=np.int64).view(dtype) + ex_vals = vals.astype("datetime64[ns]") + + df = DataFrame({"ints": np.arange(n)}, index=np.arange(n)) + df["dates"] = np.arange(n, dtype=np.int64).view("M8[ns]") + + # We overwrite existing dt64 column with new, non-nano dt64 vals + df["dates"] = vals + assert (df["dates"].values == ex_vals).all() + def test_setitem_dt64tz(self, timezone_frame): df = timezone_frame diff --git a/pandas/tests/frame/test_add_prefix_suffix.py b/pandas/tests/frame/methods/test_add_prefix_suffix.py similarity index 100% rename from pandas/tests/frame/test_add_prefix_suffix.py rename to pandas/tests/frame/methods/test_add_prefix_suffix.py diff --git a/pandas/tests/frame/methods/test_reset_index.py b/pandas/tests/frame/methods/test_reset_index.py index 92c9f7564a670..56fd633f5f22b 100644 --- a/pandas/tests/frame/methods/test_reset_index.py +++ b/pandas/tests/frame/methods/test_reset_index.py @@ -71,6 +71,15 @@ def test_reset_index_tz(self, tz_aware_fixture): expected["idx"] = expected["idx"].apply(lambda d: Timestamp(d, tz=tz)) tm.assert_frame_equal(df.reset_index(), expected) + @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"]) + def test_frame_reset_index_tzaware_index(self, tz): + dr = date_range("2012-06-02", periods=10, tz=tz) + df = DataFrame(np.random.randn(len(dr)), dr) + roundtripped = df.reset_index().set_index("index") + xp = df.index.tz + rs = roundtripped.index.tz + assert xp == rs + def test_reset_index_with_intervals(self): idx = IntervalIndex.from_breaks(np.arange(11), name="x") original = DataFrame({"x": idx, "y": np.arange(10)})[["x", "y"]] diff --git a/pandas/tests/frame/methods/test_transpose.py b/pandas/tests/frame/methods/test_transpose.py index a5fe5f3a6d5e4..8635168f1eb03 100644 --- a/pandas/tests/frame/methods/test_transpose.py +++ b/pandas/tests/frame/methods/test_transpose.py @@ -1,45 +1,55 @@ import numpy as np +import pytest -import pandas as pd +from pandas import DataFrame, date_range import pandas._testing as tm class TestTranspose: def test_transpose_tzaware_1col_single_tz(self): # GH#26825 - dti = pd.date_range("2016-04-05 04:30", periods=3, tz="UTC") + dti = date_range("2016-04-05 04:30", periods=3, tz="UTC") - df = pd.DataFrame(dti) + df = DataFrame(dti) assert (df.dtypes == dti.dtype).all() res = df.T assert (res.dtypes == dti.dtype).all() def test_transpose_tzaware_2col_single_tz(self): # GH#26825 - dti = pd.date_range("2016-04-05 04:30", periods=3, tz="UTC") + dti = date_range("2016-04-05 04:30", periods=3, tz="UTC") - df3 = pd.DataFrame({"A": dti, "B": dti}) + df3 = DataFrame({"A": dti, "B": dti}) assert (df3.dtypes == dti.dtype).all() res3 = df3.T assert (res3.dtypes == dti.dtype).all() def test_transpose_tzaware_2col_mixed_tz(self): # GH#26825 - dti = pd.date_range("2016-04-05 04:30", periods=3, tz="UTC") + dti = date_range("2016-04-05 04:30", periods=3, tz="UTC") dti2 = dti.tz_convert("US/Pacific") - df4 = pd.DataFrame({"A": dti, "B": dti2}) + df4 = DataFrame({"A": dti, "B": dti2}) assert (df4.dtypes == [dti.dtype, dti2.dtype]).all() assert (df4.T.dtypes == object).all() tm.assert_frame_equal(df4.T.T, df4) + @pytest.mark.parametrize("tz", [None, "America/New_York"]) + def test_transpose_preserves_dtindex_equality_with_dst(self, tz): + # GH#19970 + idx = date_range("20161101", "20161130", freq="4H", tz=tz) + df = DataFrame({"a": range(len(idx)), "b": range(len(idx))}, index=idx) + result = df.T == df.T + expected = DataFrame(True, index=list("ab"), columns=idx) + tm.assert_frame_equal(result, expected) + def test_transpose_object_to_tzaware_mixed_tz(self): # GH#26825 - dti = pd.date_range("2016-04-05 04:30", periods=3, tz="UTC") + dti = date_range("2016-04-05 04:30", periods=3, tz="UTC") dti2 = dti.tz_convert("US/Pacific") # mixed all-tzaware dtypes - df2 = pd.DataFrame([dti, dti2]) + df2 = DataFrame([dti, dti2]) assert (df2.dtypes == object).all() res2 = df2.T assert (res2.dtypes == [dti.dtype, dti2.dtype]).all() @@ -47,7 +57,7 @@ def test_transpose_object_to_tzaware_mixed_tz(self): def test_transpose_uint64(self, uint64_frame): result = uint64_frame.T - expected = pd.DataFrame(uint64_frame.values.T) + expected = DataFrame(uint64_frame.values.T) expected.index = ["A", "B"] tm.assert_frame_equal(result, expected) @@ -63,7 +73,7 @@ def test_transpose_float(self, float_frame): # mixed type index, data = tm.getMixedTypeDict() - mixed = pd.DataFrame(data, index=index) + mixed = DataFrame(data, index=index) mixed_T = mixed.T for col, s in mixed_T.items(): diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 46e34a7a58ae4..408024e48a35a 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2737,6 +2737,35 @@ def test_constructor_list_str_na(self, string_dtype): class TestDataFrameConstructorWithDatetimeTZ: + @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"]) + def test_construction_preserves_tzaware_dtypes(self, tz): + # after GH#7822 + # these retain the timezones on dict construction + dr = date_range("2011/1/1", "2012/1/1", freq="W-FRI") + dr_tz = dr.tz_localize(tz) + df = DataFrame({"A": "foo", "B": dr_tz}, index=dr) + tz_expected = DatetimeTZDtype("ns", dr_tz.tzinfo) + assert df["B"].dtype == tz_expected + + # GH#2810 (with timezones) + datetimes_naive = [ts.to_pydatetime() for ts in dr] + datetimes_with_tz = [ts.to_pydatetime() for ts in dr_tz] + df = DataFrame({"dr": dr}) + df["dr_tz"] = dr_tz + df["datetimes_naive"] = datetimes_naive + df["datetimes_with_tz"] = datetimes_with_tz + result = df.dtypes + expected = Series( + [ + np.dtype("datetime64[ns]"), + DatetimeTZDtype(tz=tz), + np.dtype("datetime64[ns]"), + DatetimeTZDtype(tz=tz), + ], + index=["dr", "dr_tz", "datetimes_naive", "datetimes_with_tz"], + ) + tm.assert_series_equal(result, expected) + def test_constructor_data_aware_dtype_naive(self, tz_aware_fixture): # GH#25843 tz = tz_aware_fixture diff --git a/pandas/tests/frame/test_nonunique_indexes.py b/pandas/tests/frame/test_nonunique_indexes.py index c6b1c69442dbc..1c54855ee7bce 100644 --- a/pandas/tests/frame/test_nonunique_indexes.py +++ b/pandas/tests/frame/test_nonunique_indexes.py @@ -400,29 +400,6 @@ def check(result, expected=None): result = z.loc[["a", "c", "a"]] check(result, expected) - def test_column_dups_indexing2(self): - - # GH 8363 - # datetime ops with a non-unique index - df = DataFrame( - {"A": np.arange(5, dtype="int64"), "B": np.arange(1, 6, dtype="int64")}, - index=[2, 2, 3, 3, 4], - ) - result = df.B - df.A - expected = Series(1, index=[2, 2, 3, 3, 4]) - tm.assert_series_equal(result, expected) - - df = DataFrame( - { - "A": date_range("20130101", periods=5), - "B": date_range("20130101 09:00:00", periods=5), - }, - index=[2, 2, 3, 3, 4], - ) - result = df.B - df.A - expected = Series(pd.Timedelta("9 hours"), index=[2, 2, 3, 3, 4]) - tm.assert_series_equal(result, expected) - def test_columns_with_dups(self): # GH 3468 related diff --git a/pandas/tests/frame/test_timeseries.py b/pandas/tests/frame/test_timeseries.py deleted file mode 100644 index 22ffb30324366..0000000000000 --- a/pandas/tests/frame/test_timeseries.py +++ /dev/null @@ -1,57 +0,0 @@ -import numpy as np -import pytest - -import pandas as pd -from pandas import DataFrame, to_datetime -import pandas._testing as tm - - -class TestDataFrameTimeSeriesMethods: - @pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"]) - def test_frame_append_datetime64_col_other_units(self, unit): - n = 100 - - ns_dtype = np.dtype("M8[ns]") - - dtype = np.dtype(f"M8[{unit}]") - vals = np.arange(n, dtype=np.int64).view(dtype) - - df = DataFrame({"ints": np.arange(n)}, index=np.arange(n)) - df[unit] = vals - - ex_vals = to_datetime(vals.astype("O")).values - - assert df[unit].dtype == ns_dtype - assert (df[unit].values == ex_vals).all() - - @pytest.mark.parametrize("unit", ["h", "m", "s", "ms", "D", "M", "Y"]) - def test_frame_setitem_existing_datetime64_col_other_units(self, unit): - # Test insertion into existing datetime64 column - n = 100 - ns_dtype = np.dtype("M8[ns]") - - df = DataFrame({"ints": np.arange(n)}, index=np.arange(n)) - df["dates"] = np.arange(n, dtype=np.int64).view(ns_dtype) - - dtype = np.dtype(f"M8[{unit}]") - vals = np.arange(n, dtype=np.int64).view(dtype) - - tmp = df.copy() - - tmp["dates"] = vals - ex_vals = to_datetime(vals.astype("O")).values - - assert (tmp["dates"].values == ex_vals).all() - - def test_datetime_assignment_with_NaT_and_diff_time_units(self): - # GH 7492 - data_ns = np.array([1, "nat"], dtype="datetime64[ns]") - result = pd.Series(data_ns).to_frame() - result["new"] = data_ns - expected = DataFrame({0: [1, None], "new": [1, None]}, dtype="datetime64[ns]") - tm.assert_frame_equal(result, expected) - # OutOfBoundsDatetime error shouldn't occur - data_s = np.array([1, "nat"], dtype="datetime64[s]") - result["new"] = data_s - expected = DataFrame({0: [1, None], "new": [1e9, None]}, dtype="datetime64[ns]") - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/frame/test_timezones.py b/pandas/tests/frame/test_timezones.py deleted file mode 100644 index 1271a490d6b70..0000000000000 --- a/pandas/tests/frame/test_timezones.py +++ /dev/null @@ -1,60 +0,0 @@ -""" -Tests for DataFrame timezone-related methods -""" -import numpy as np -import pytest - -from pandas.core.dtypes.dtypes import DatetimeTZDtype - -from pandas import DataFrame, Series -import pandas._testing as tm -from pandas.core.indexes.datetimes import date_range - - -class TestDataFrameTimezones: - @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"]) - def test_frame_no_datetime64_dtype(self, tz): - # after GH#7822 - # these retain the timezones on dict construction - dr = date_range("2011/1/1", "2012/1/1", freq="W-FRI") - dr_tz = dr.tz_localize(tz) - df = DataFrame({"A": "foo", "B": dr_tz}, index=dr) - tz_expected = DatetimeTZDtype("ns", dr_tz.tzinfo) - assert df["B"].dtype == tz_expected - - # GH#2810 (with timezones) - datetimes_naive = [ts.to_pydatetime() for ts in dr] - datetimes_with_tz = [ts.to_pydatetime() for ts in dr_tz] - df = DataFrame({"dr": dr}) - df["dr_tz"] = dr_tz - df["datetimes_naive"] = datetimes_naive - df["datetimes_with_tz"] = datetimes_with_tz - result = df.dtypes - expected = Series( - [ - np.dtype("datetime64[ns]"), - DatetimeTZDtype(tz=tz), - np.dtype("datetime64[ns]"), - DatetimeTZDtype(tz=tz), - ], - index=["dr", "dr_tz", "datetimes_naive", "datetimes_with_tz"], - ) - tm.assert_series_equal(result, expected) - - @pytest.mark.parametrize("tz", ["US/Eastern", "dateutil/US/Eastern"]) - def test_frame_reset_index(self, tz): - dr = date_range("2012-06-02", periods=10, tz=tz) - df = DataFrame(np.random.randn(len(dr)), dr) - roundtripped = df.reset_index().set_index("index") - xp = df.index.tz - rs = roundtripped.index.tz - assert xp == rs - - @pytest.mark.parametrize("tz", [None, "America/New_York"]) - def test_boolean_compare_transpose_tzindex_with_dst(self, tz): - # GH 19970 - idx = date_range("20161101", "20161130", freq="4H", tz=tz) - df = DataFrame({"a": range(len(idx)), "b": range(len(idx))}, index=idx) - result = df.T == df.T - expected = DataFrame(True, index=list("ab"), columns=idx) - tm.assert_frame_equal(result, expected) diff --git a/pandas/tests/series/indexing/test_getitem.py b/pandas/tests/series/indexing/test_getitem.py index f8517c3b91fc1..5e87f8f6c1059 100644 --- a/pandas/tests/series/indexing/test_getitem.py +++ b/pandas/tests/series/indexing/test_getitem.py @@ -271,6 +271,21 @@ def test_getitem_boolean_different_order(self, string_series): exp = string_series[string_series > 0] tm.assert_series_equal(sel, exp) + def test_getitem_boolean_contiguous_preserve_freq(self): + rng = date_range("1/1/2000", "3/1/2000", freq="B") + + mask = np.zeros(len(rng), dtype=bool) + mask[10:20] = True + + masked = rng[mask] + expected = rng[10:20] + assert expected.freq == rng.freq + tm.assert_index_equal(masked, expected) + + mask[22] = True + masked = rng[mask] + assert masked.freq is None + class TestGetitemCallable: def test_getitem_callable(self): diff --git a/pandas/tests/series/methods/test_is_monotonic.py b/pandas/tests/series/methods/test_is_monotonic.py new file mode 100644 index 0000000000000..b242b293cb59e --- /dev/null +++ b/pandas/tests/series/methods/test_is_monotonic.py @@ -0,0 +1,25 @@ +import numpy as np + +from pandas import Series, date_range + + +class TestIsMonotonic: + def test_is_monotonic_numeric(self): + + ser = Series(np.random.randint(0, 10, size=1000)) + assert not ser.is_monotonic + ser = Series(np.arange(1000)) + assert ser.is_monotonic is True + assert ser.is_monotonic_increasing is True + ser = Series(np.arange(1000, 0, -1)) + assert ser.is_monotonic_decreasing is True + + def test_is_monotonic_dt64(self): + + ser = Series(date_range("20130101", periods=10)) + assert ser.is_monotonic is True + assert ser.is_monotonic_increasing is True + + ser = Series(list(reversed(ser))) + assert ser.is_monotonic is False + assert ser.is_monotonic_decreasing is True diff --git a/pandas/tests/series/methods/test_view.py b/pandas/tests/series/methods/test_view.py new file mode 100644 index 0000000000000..ccf3aa0d90e6f --- /dev/null +++ b/pandas/tests/series/methods/test_view.py @@ -0,0 +1,18 @@ +from pandas import Series, date_range +import pandas._testing as tm + + +class TestView: + def test_view_tz(self): + # GH#24024 + ser = Series(date_range("2000", periods=4, tz="US/Central")) + result = ser.view("i8") + expected = Series( + [ + 946706400000000000, + 946792800000000000, + 946879200000000000, + 946965600000000000, + ] + ) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py deleted file mode 100644 index ebb75adde5b13..0000000000000 --- a/pandas/tests/series/test_analytics.py +++ /dev/null @@ -1,23 +0,0 @@ -import numpy as np - -import pandas as pd -from pandas import Series - - -class TestSeriesAnalytics: - def test_is_monotonic(self): - - s = Series(np.random.randint(0, 10, size=1000)) - assert not s.is_monotonic - s = Series(np.arange(1000)) - assert s.is_monotonic is True - assert s.is_monotonic_increasing is True - s = Series(np.arange(1000, 0, -1)) - assert s.is_monotonic_decreasing is True - - s = Series(pd.date_range("20130101", periods=10)) - assert s.is_monotonic is True - assert s.is_monotonic_increasing is True - s = Series(list(reversed(s.tolist()))) - assert s.is_monotonic is False - assert s.is_monotonic_decreasing is True diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index 4920796f661fb..c595861d35934 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -15,6 +15,7 @@ Index, IntervalIndex, Series, + Timedelta, bdate_range, date_range, isna, @@ -277,6 +278,25 @@ def test_alignment_doesnt_change_tz(self): assert ser.index is dti assert ser_utc.index is dti_utc + def test_arithmetic_with_duplicate_index(self): + + # GH#8363 + # integer ops with a non-unique index + index = [2, 2, 3, 3, 4] + ser = Series(np.arange(1, 6, dtype="int64"), index=index) + other = Series(np.arange(5, dtype="int64"), index=index) + result = ser - other + expected = Series(1, index=[2, 2, 3, 3, 4]) + tm.assert_series_equal(result, expected) + + # GH#8363 + # datetime ops with a non-unique index + ser = Series(date_range("20130101 09:00:00", periods=5), index=index) + other = Series(date_range("20130101", periods=5), index=index) + result = ser - other + expected = Series(Timedelta("9 hours"), index=[2, 2, 3, 3, 4]) + tm.assert_series_equal(result, expected) + # ------------------------------------------------------------------ # Comparisons diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 5c4118bc40f4d..c8fbbcf9aed20 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1045,6 +1045,16 @@ def test_constructor_infer_period(self, data_constructor): tm.assert_series_equal(result, expected) assert result.dtype == "Period[D]" + @pytest.mark.xfail(reason="PeriodDtype Series not supported yet") + def test_construct_from_ints_including_iNaT_scalar_period_dtype(self): + series = Series([0, 1000, 2000, pd._libs.iNaT], dtype="period[D]") + + val = series[3] + assert isna(val) + + series[2] = val + assert isna(series[2]) + def test_constructor_period_incompatible_frequency(self): data = [pd.Period("2000", "D"), pd.Period("2001", "A")] result = Series(data) diff --git a/pandas/tests/series/test_period.py b/pandas/tests/series/test_period.py index d079111aa12d6..17dbfa9cf379a 100644 --- a/pandas/tests/series/test_period.py +++ b/pandas/tests/series/test_period.py @@ -1,36 +1,24 @@ import numpy as np -import pytest -import pandas as pd from pandas import DataFrame, Series, period_range class TestSeriesPeriod: - def setup_method(self, method): - self.series = Series(period_range("2000-01-01", periods=10, freq="D")) # --------------------------------------------------------------------- # NaT support - @pytest.mark.xfail(reason="PeriodDtype Series not supported yet") - def test_NaT_scalar(self): - series = Series([0, 1000, 2000, pd._libs.iNaT], dtype="period[D]") - - val = series[3] - assert pd.isna(val) - - series[2] = val - assert pd.isna(series[2]) - def test_intercept_astype_object(self): - expected = self.series.astype("object") + series = Series(period_range("2000-01-01", periods=10, freq="D")) + + expected = series.astype("object") - df = DataFrame({"a": self.series, "b": np.random.randn(len(self.series))}) + df = DataFrame({"a": series, "b": np.random.randn(len(series))}) result = df.values.squeeze() assert (result[:, 0] == expected.values).all() - df = DataFrame({"a": self.series, "b": ["foo"] * len(self.series)}) + df = DataFrame({"a": series, "b": ["foo"] * len(series)}) result = df.values.squeeze() assert (result[:, 0] == expected.values).all() diff --git a/pandas/tests/series/test_timeseries.py b/pandas/tests/series/test_timeseries.py index 8b32be45e8d57..0769606d18d57 100644 --- a/pandas/tests/series/test_timeseries.py +++ b/pandas/tests/series/test_timeseries.py @@ -1,26 +1,10 @@ import numpy as np -import pandas as pd from pandas import DataFrame, Series, date_range, timedelta_range import pandas._testing as tm class TestTimeSeries: - def test_contiguous_boolean_preserve_freq(self): - rng = date_range("1/1/2000", "3/1/2000", freq="B") - - mask = np.zeros(len(rng), dtype=bool) - mask[10:20] = True - - masked = rng[mask] - expected = rng[10:20] - assert expected.freq == rng.freq - tm.assert_index_equal(masked, expected) - - mask[22] = True - masked = rng[mask] - assert masked.freq is None - def test_promote_datetime_date(self): rng = date_range("1/1/2000", periods=20) ts = Series(np.random.randn(20), index=rng) @@ -55,17 +39,3 @@ def f(x): s.map(f) s.apply(f) DataFrame(s).applymap(f) - - def test_view_tz(self): - # GH#24024 - ser = Series(pd.date_range("2000", periods=4, tz="US/Central")) - result = ser.view("i8") - expected = Series( - [ - 946706400000000000, - 946792800000000000, - 946879200000000000, - 946965600000000000, - ] - ) - tm.assert_series_equal(result, expected)
https://api.github.com/repos/pandas-dev/pandas/pulls/37589
2020-11-02T15:23:23Z
2020-11-02T22:24:37Z
2020-11-02T22:24:37Z
2020-11-02T22:40:14Z
REF: prelims for single-path setitem_with_indexer
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index c2dad928845a7..c5e331a104726 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1592,7 +1592,11 @@ def _setitem_with_indexer(self, indexer, value): return # add a new item with the dtype setup - self.obj[key] = infer_fill_value(value) + if com.is_null_slice(indexer[0]): + # We are setting an entire column + self.obj[key] = value + else: + self.obj[key] = infer_fill_value(value) new_indexer = convert_from_missing_indexer_tuple( indexer, self.obj.axes @@ -1641,6 +1645,8 @@ def _setitem_with_indexer_split_path(self, indexer, value): if not isinstance(indexer, tuple): indexer = _tuplify(self.ndim, indexer) + if len(indexer) > self.ndim: + raise IndexError("too many indices for array") if isinstance(value, ABCSeries): value = self._align_series(indexer, value) diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index de70ff37a052a..614e424e8aca2 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -116,10 +116,6 @@ def test_setitem_ndarray_3d(self, index, obj, idxr, idxr_id): idxr = idxr(obj) nd3 = np.random.randint(5, size=(2, 2, 2)) - if (len(index) == 0) and (idxr_id == "iloc") and isinstance(obj, pd.DataFrame): - # gh-32896 - pytest.skip("This is currently failing. There's an xfailed test below.") - if idxr_id == "iloc": err = ValueError msg = f"Cannot set values with ndim > {obj.ndim}" @@ -140,7 +136,6 @@ def test_setitem_ndarray_3d(self, index, obj, idxr, idxr_id): idxr[nd3] = 0 def test_setitem_ndarray_3d_does_not_fail_for_iloc_empty_dataframe(self): - # when fixing this, please remove the pytest.skip in test_setitem_ndarray_3d i = Index([]) obj = DataFrame(np.random.randn(len(i), len(i)), index=i, columns=i) nd3 = np.random.randint(5, size=(2, 2, 2))
Removes a pytest.skip that was supposed to have been removed along with an xfail in a previous step.
https://api.github.com/repos/pandas-dev/pandas/pulls/37588
2020-11-02T15:03:04Z
2020-11-02T21:25:45Z
2020-11-02T21:25:45Z
2020-11-02T21:46:43Z
TST: catch FutureWarnings from Index.__and__ deprecation
diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index 4920796f661fb..4bb4d3eeda112 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -731,17 +731,23 @@ def test_series_ops_name_retention(flex, box, names, all_binary_operators): left = Series(range(10), name=names[0]) right = Series(range(10), name=names[1]) + name = op.__name__.strip("_") + is_logical = name in ["and", "rand", "xor", "rxor", "or", "ror"] + is_rlogical = is_logical and name.startswith("r") + right = box(right) if flex: - name = op.__name__.strip("_") - if name in ["and", "rand", "xor", "rxor", "or", "ror"]: + if is_logical: # Series doesn't have these as flex methods return result = getattr(left, name)(right) else: - result = op(left, right) + # GH#37374 logical ops behaving as set ops deprecated + warn = FutureWarning if is_rlogical and box is Index else None + with tm.assert_produces_warning(warn, check_stacklevel=False): + result = op(left, right) - if box is pd.Index and op.__name__.strip("_") in ["rxor", "ror", "rand"]: + if box is pd.Index and is_rlogical: # Index treats these as set operators, so does not defer assert isinstance(result, pd.Index) return
https://api.github.com/repos/pandas-dev/pandas/pulls/37587
2020-11-02T14:59:50Z
2020-11-02T17:29:54Z
2020-11-02T17:29:54Z
2020-11-02T17:30:19Z
CLN refactor rest of core
diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py index 2145551833e90..55863e649078d 100644 --- a/pandas/core/aggregation.py +++ b/pandas/core/aggregation.py @@ -388,7 +388,6 @@ def validate_func_kwargs( >>> validate_func_kwargs({'one': 'min', 'two': 'max'}) (['one', 'two'], ['min', 'max']) """ - no_arg_message = "Must provide 'func' or named aggregation **kwargs." tuple_given_message = "func is expected but received {} in **kwargs." columns = list(kwargs) func = [] @@ -397,6 +396,7 @@ def validate_func_kwargs( raise TypeError(tuple_given_message.format(type(col_func).__name__)) func.append(col_func) if not columns: + no_arg_message = "Must provide 'func' or named aggregation **kwargs." raise TypeError(no_arg_message) return columns, func @@ -499,14 +499,14 @@ def transform_dict_like( try: results[name] = transform(colg, how, 0, *args, **kwargs) except Exception as err: - if ( - str(err) == "Function did not transform" - or str(err) == "No transform functions were provided" - ): + if str(err) in { + "Function did not transform", + "No transform functions were provided", + }: raise err # combine results - if len(results) == 0: + if not results: raise ValueError("Transform function failed") return concat(results, axis=1) diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index 085ad5e6a0dcf..6553a67df47e2 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -150,12 +150,10 @@ def _ensure_data( from pandas import PeriodIndex values = PeriodIndex(values)._data - dtype = values.dtype elif is_timedelta64_dtype(values.dtype) or is_timedelta64_dtype(dtype): from pandas import TimedeltaIndex values = TimedeltaIndex(values)._data - dtype = values.dtype else: # Datetime if values.ndim > 1 and is_datetime64_ns_dtype(values.dtype): @@ -169,8 +167,7 @@ def _ensure_data( from pandas import DatetimeIndex values = DatetimeIndex(values)._data - dtype = values.dtype - + dtype = values.dtype return values.asi8, dtype elif is_categorical_dtype(values.dtype) and ( @@ -875,10 +872,9 @@ def value_counts_arraylike(values, dropna: bool): keys, counts = f(values, dropna) mask = isna(values) - if not dropna and mask.any(): - if not isna(keys).any(): - keys = np.insert(keys, 0, np.NaN) - counts = np.insert(counts, 0, mask.sum()) + if not dropna and mask.any() and not isna(keys).any(): + keys = np.insert(keys, 0, np.NaN) + counts = np.insert(counts, 0, mask.sum()) keys = _reconstruct_data(keys, original.dtype, original) @@ -1741,9 +1737,8 @@ def take_nd( dtype, fill_value = arr.dtype, arr.dtype.type() flip_order = False - if arr.ndim == 2: - if arr.flags.f_contiguous: - flip_order = True + if arr.ndim == 2 and arr.flags.f_contiguous: + flip_order = True if flip_order: arr = arr.T @@ -1915,8 +1910,7 @@ def searchsorted(arr, value, side="left", sorter=None) -> np.ndarray: # and `value` is a pd.Timestamp, we may need to convert value arr = ensure_wrapped_if_datetimelike(arr) - result = arr.searchsorted(value, side=side, sorter=sorter) - return result + return arr.searchsorted(value, side=side, sorter=sorter) # ---- # diff --git a/pandas/core/array_algos/replace.py b/pandas/core/array_algos/replace.py index 76d723beac7e6..1cac825cc0898 100644 --- a/pandas/core/array_algos/replace.py +++ b/pandas/core/array_algos/replace.py @@ -49,8 +49,7 @@ def _check_comparison_types( if is_scalar(result) and isinstance(a, np.ndarray): type_names = [type(a).__name__, type(b).__name__] - if isinstance(a, np.ndarray): - type_names[0] = f"ndarray(dtype={a.dtype})" + type_names[0] = f"ndarray(dtype={a.dtype})" raise TypeError( f"Cannot compare types {repr(type_names[0])} and {repr(type_names[1])}" diff --git a/pandas/core/base.py b/pandas/core/base.py index b603ba31f51dd..631f67ced77dd 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -321,10 +321,9 @@ def _try_aggregate_string_function(self, arg: str, *args, **kwargs): return f f = getattr(np, arg, None) - if f is not None: - if hasattr(self, "__array__"): - # in particular exclude Window - return f(self, *args, **kwargs) + if f is not None and hasattr(self, "__array__"): + # in particular exclude Window + return f(self, *args, **kwargs) raise AttributeError( f"'{arg}' is not a valid function for '{type(self).__name__}' object" @@ -1046,7 +1045,7 @@ def value_counts( 1.0 1 dtype: int64 """ - result = value_counts( + return value_counts( self, sort=sort, ascending=ascending, @@ -1054,7 +1053,6 @@ def value_counts( bins=bins, dropna=dropna, ) - return result def unique(self): values = self._values @@ -1317,8 +1315,7 @@ def drop_duplicates(self, keep="first"): duplicated = self.duplicated(keep=keep) # pandas\core\base.py:1507: error: Value of type "IndexOpsMixin" is not # indexable [index] - result = self[np.logical_not(duplicated)] # type: ignore[index] - return result + return self[~duplicated] # type: ignore[index] def duplicated(self, keep="first"): return duplicated(self._values, keep=keep) diff --git a/pandas/core/construction.py b/pandas/core/construction.py index 54a6f47ae1b38..2980547e23f24 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -343,8 +343,7 @@ def array( elif is_timedelta64_ns_dtype(dtype): return TimedeltaArray._from_sequence(data, dtype=dtype, copy=copy) - result = PandasArray._from_sequence(data, dtype=dtype, copy=copy) - return result + return PandasArray._from_sequence(data, dtype=dtype, copy=copy) def extract_array(obj: object, extract_numpy: bool = False) -> Union[Any, ArrayLike]: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ffc84ad94459a..0a1ea4041a10b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -770,7 +770,7 @@ def _repr_fits_horizontal_(self, ignore_width: bool = False) -> bool: # and to_string on entire frame may be expensive d = self - if not (max_rows is None): # unlimited rows + if max_rows is not None: # unlimited rows # min of two, where one may be None d = d.iloc[: min(max_rows, len(d))] else: @@ -2029,10 +2029,10 @@ def to_records( np.asarray(self.iloc[:, i]) for i in range(len(self.columns)) ] - count = 0 index_names = list(self.index.names) if isinstance(self.index, MultiIndex): + count = 0 for i, n in enumerate(index_names): if n is None: index_names[i] = f"level_{count}" @@ -3334,7 +3334,7 @@ def _set_value(self, index, col, value, takeable: bool = False): takeable : interpret the index/col as indexers, default False """ try: - if takeable is True: + if takeable: series = self._ixs(col, axis=1) series._set_value(index, value, takeable=True) return @@ -5041,7 +5041,7 @@ class max type multi_col = isinstance(self.columns, MultiIndex) for i, (lev, lab) in reversed(list(enumerate(to_insert))): - if not (level is None or i in level): + if level is not None and i not in level: continue name = names[i] if multi_col: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 6a80fa3e93362..27b1751a5045e 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -773,8 +773,7 @@ def droplevel(self: FrameOrSeries, level, axis=0) -> FrameOrSeries: """ labels = self._get_axis(axis) new_labels = labels.droplevel(level) - result = self.set_axis(new_labels, axis=axis, inplace=False) - return result + return self.set_axis(new_labels, axis=axis, inplace=False) def pop(self, item: Hashable) -> Union[Series, Any]: result = self[item] @@ -1445,8 +1444,7 @@ def __invert__(self): return self new_data = self._mgr.apply(operator.invert) - result = self._constructor(new_data).__finalize__(self, method="__invert__") - return result + return self._constructor(new_data).__finalize__(self, method="__invert__") @final def __nonzero__(self): @@ -2036,8 +2034,7 @@ def _repr_data_resource_(self): as_json = data.to_json(orient="table") as_json = cast(str, as_json) - payload = json.loads(as_json, object_pairs_hook=collections.OrderedDict) - return payload + return json.loads(as_json, object_pairs_hook=collections.OrderedDict) # ---------------------------------------------------------------------- # I/O Methods @@ -5342,11 +5339,11 @@ def sample( "Replace has to be set to `True` when " "upsampling the population `frac` > 1." ) - elif n is not None and frac is None and n % 1 != 0: + elif frac is None and n % 1 != 0: raise ValueError("Only integers accepted as `n` values") elif n is None and frac is not None: n = round(frac * axis_length) - elif n is not None and frac is not None: + elif frac is not None: raise ValueError("Please enter a value for `frac` OR `n`, not both") # Check for negative sizes @@ -5467,15 +5464,13 @@ def __getattr__(self, name: str): # Note: obj.x will always call obj.__getattribute__('x') prior to # calling obj.__getattr__('x'). if ( - name in self._internal_names_set - or name in self._metadata - or name in self._accessors + name not in self._internal_names_set + and name not in self._metadata + and name not in self._accessors + and self._info_axis._can_hold_identifiers_and_holds_name(name) ): - return object.__getattribute__(self, name) - else: - if self._info_axis._can_hold_identifiers_and_holds_name(name): - return self[name] - return object.__getattribute__(self, name) + return self[name] + return object.__getattribute__(self, name) def __setattr__(self, name: str, value) -> None: """ @@ -5585,17 +5580,16 @@ def _is_mixed_type(self) -> bool_t: @final def _check_inplace_setting(self, value) -> bool_t: """ check whether we allow in-place setting with this type of value """ - if self._is_mixed_type: - if not self._mgr.is_numeric_mixed_type: + if self._is_mixed_type and not self._mgr.is_numeric_mixed_type: - # allow an actual np.nan thru - if is_float(value) and np.isnan(value): - return True + # allow an actual np.nan thru + if is_float(value) and np.isnan(value): + return True - raise TypeError( - "Cannot do inplace boolean setting on " - "mixed-types with a non np.nan value" - ) + raise TypeError( + "Cannot do inplace boolean setting on " + "mixed-types with a non np.nan value" + ) return True @@ -6264,8 +6258,7 @@ def convert_dtypes( ) for col_name, col in self.items() ] - result = concat(results, axis=1, copy=False) - return result + return concat(results, axis=1, copy=False) # ---------------------------------------------------------------------- # Filling NA's @@ -7443,9 +7436,13 @@ def clip( upper = None # GH 2747 (arguments were reversed) - if lower is not None and upper is not None: - if is_scalar(lower) and is_scalar(upper): - lower, upper = min(lower, upper), max(lower, upper) + if ( + lower is not None + and upper is not None + and is_scalar(lower) + and is_scalar(upper) + ): + lower, upper = min(lower, upper), max(lower, upper) # fast-path for scalars if (lower is None or (is_scalar(lower) and is_number(lower))) and ( @@ -8234,10 +8231,9 @@ def first(self: FrameOrSeries, offset) -> FrameOrSeries: end_date = end = self.index[0] + offset # Tick-like, e.g. 3 weeks - if isinstance(offset, Tick): - if end_date in self.index: - end = self.index.searchsorted(end_date, side="left") - return self.iloc[:end] + if isinstance(offset, Tick) and end_date in self.index: + end = self.index.searchsorted(end_date, side="left") + return self.iloc[:end] return self.loc[:end] @@ -8646,17 +8642,19 @@ def _align_frame( is_series = isinstance(self, ABCSeries) - if axis is None or axis == 0: - if not self.index.equals(other.index): - join_index, ilidx, iridx = self.index.join( - other.index, how=join, level=level, return_indexers=True - ) + if (axis is None or axis == 0) and not self.index.equals(other.index): + join_index, ilidx, iridx = self.index.join( + other.index, how=join, level=level, return_indexers=True + ) - if axis is None or axis == 1: - if not is_series and not self.columns.equals(other.columns): - join_columns, clidx, cridx = self.columns.join( - other.columns, how=join, level=level, return_indexers=True - ) + if ( + (axis is None or axis == 1) + and not is_series + and not self.columns.equals(other.columns) + ): + join_columns, clidx, cridx = self.columns.join( + other.columns, how=join, level=level, return_indexers=True + ) if is_series: reindexers = {0: [join_index, ilidx]} @@ -9526,9 +9524,8 @@ def truncate( before = to_datetime(before) after = to_datetime(after) - if before is not None and after is not None: - if before > after: - raise ValueError(f"Truncate: {after} must be after {before}") + if before is not None and after is not None and before > after: + raise ValueError(f"Truncate: {after} must be after {before}") if len(ax) > 1 and ax.is_monotonic_decreasing: before, after = after, before diff --git a/pandas/core/indexers.py b/pandas/core/indexers.py index 79479c6db8d9d..399953fc17c73 100644 --- a/pandas/core/indexers.py +++ b/pandas/core/indexers.py @@ -82,12 +82,11 @@ def is_scalar_indexer(indexer, ndim: int) -> bool: if ndim == 1 and is_integer(indexer): # GH37748: allow indexer to be an integer for Series return True - if isinstance(indexer, tuple): - if len(indexer) == ndim: - return all( - is_integer(x) or (isinstance(x, np.ndarray) and x.ndim == len(x) == 1) - for x in indexer - ) + if isinstance(indexer, tuple) and len(indexer) == ndim: + return all( + is_integer(x) or (isinstance(x, np.ndarray) and x.ndim == len(x) == 1) + for x in indexer + ) return False diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 90ba03b312e56..c98242cae23f3 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1001,10 +1001,7 @@ def _multi_take_opportunity(self, tup: Tuple) -> bool: return False # just too complicated - if any(com.is_bool_indexer(x) for x in tup): - return False - - return True + return not any(com.is_bool_indexer(x) for x in tup) def _multi_take(self, tup: Tuple): """ @@ -1424,11 +1421,7 @@ def _is_scalar_access(self, key: Tuple) -> bool: if len(key) != self.ndim: return False - for k in key: - if not is_integer(k): - return False - - return True + return all(is_integer(k) for k in key) def _validate_integer(self, key: int, axis: int) -> None: """ @@ -1551,12 +1544,11 @@ 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 self.obj._mgr.blocks: - if 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) + if not take_split_path and self.obj._mgr.blocks 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) # 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/missing.py b/pandas/core/missing.py index 1120416eebeb9..ddee68c08b540 100644 --- a/pandas/core/missing.py +++ b/pandas/core/missing.py @@ -147,7 +147,7 @@ def find_valid_index(values, how: str): if how == "first": idxpos = is_valid[::].argmax() - if how == "last": + elif how == "last": idxpos = len(values) - 1 - is_valid[::-1].argmax() chk_notna = is_valid[idxpos] diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index fb9b20bd43d7c..8d3363df0d132 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -149,10 +149,7 @@ def _bn_ok_dtype(dtype: DtypeObj, name: str) -> bool: # further we also want to preserve NaN when all elements # are NaN, unlike bottleneck/numpy which consider this # to be 0 - if name in ["nansum", "nanprod"]: - return False - - return True + return name not in ["nansum", "nanprod"] return False @@ -184,14 +181,11 @@ def _get_fill_value( else: return -np.inf else: - if fill_value_typ is None: - return iNaT + if fill_value_typ == "+inf": + # need the max int here + return np.iinfo(np.int64).max else: - if fill_value_typ == "+inf": - # need the max int here - return np.iinfo(np.int64).max - else: - return iNaT + return iNaT def _maybe_get_mask( @@ -433,8 +427,7 @@ def _na_for_min_count( else: result_shape = values.shape[:axis] + values.shape[axis + 1 :] - result = np.full(result_shape, fill_value, dtype=values.dtype) - return result + return np.full(result_shape, fill_value, dtype=values.dtype) def nanany( @@ -1151,12 +1144,12 @@ def nanskew( if isinstance(result, np.ndarray): result = np.where(m2 == 0, 0, result) result[count < 3] = np.nan - return result else: result = 0 if m2 == 0 else result if count < 3: return np.nan - return result + + return result @disallow("M8", "m8") diff --git a/pandas/core/resample.py b/pandas/core/resample.py index f6c1da723a1d9..bae0d69f6b782 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -181,8 +181,7 @@ def _convert_obj(self, obj): ------- obj : converted object """ - obj = obj._consolidate() - return obj + return obj._consolidate() def _get_binner_for_time(self): raise AbstractMethodError(self) @@ -1070,17 +1069,16 @@ def _downsample(self, how, **kwargs): return obj # do we have a regular frequency - if ax.freq is not None or ax.inferred_freq is not None: - - # pandas\core\resample.py:1037: error: "BaseGrouper" has no - # attribute "binlabels" [attr-defined] - if ( - len(self.grouper.binlabels) > len(ax) # type: ignore[attr-defined] - and how is None - ): + # pandas\core\resample.py:1037: error: "BaseGrouper" has no + # attribute "binlabels" [attr-defined] + if ( + (ax.freq is not None or ax.inferred_freq is not None) + and len(self.grouper.binlabels) > len(ax) # type: ignore[attr-defined] + and how is None + ): - # let's do an asfreq - return self.asfreq() + # let's do an asfreq + return self.asfreq() # we are downsampling # we want to call the actual grouper method here diff --git a/pandas/core/series.py b/pandas/core/series.py index 3888194305d76..e1399f73128e3 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -950,7 +950,7 @@ def __setitem__(self, key, value): self._set_with_engine(key, value) except (KeyError, ValueError): values = self._values - if is_integer(key) and not self.index.inferred_type == "integer": + if is_integer(key) and self.index.inferred_type != "integer": # positional setter values[key] = value else: @@ -1284,9 +1284,7 @@ def __repr__(self) -> str: max_rows=max_rows, length=show_dimensions, ) - result = buf.getvalue() - - return result + return buf.getvalue() def to_string( self, @@ -1847,8 +1845,7 @@ def unique(self): ['b', 'a', 'c'] Categories (3, object): ['a' < 'b' < 'c'] """ - result = super().unique() - return result + return super().unique() def drop_duplicates(self, keep="first", inplace=False) -> Optional["Series"]: """ @@ -2704,8 +2701,7 @@ def _binop(self, other, func, level=None, fill_value=None): result = func(this_vals, other_vals) name = ops.get_op_result_name(self, other) - ret = this._construct_result(result, name) - return ret + return this._construct_result(result, name) def _construct_result( self, result: Union[ArrayLike, Tuple[ArrayLike, ArrayLike]], name: Hashable @@ -3757,9 +3753,7 @@ def explode(self, ignore_index: bool = False) -> Series: else: index = self.index.repeat(counts) - result = self._constructor(values, index=index, name=self.name) - - return result + return self._constructor(values, index=index, name=self.name) def unstack(self, level=-1, fill_value=None): """ diff --git a/pandas/core/sorting.py b/pandas/core/sorting.py index 8869533be30fb..21b213d71cd54 100644 --- a/pandas/core/sorting.py +++ b/pandas/core/sorting.py @@ -465,9 +465,7 @@ def _ensure_key_mapped_multiindex( for level in range(index.nlevels) ] - labels = type(index).from_arrays(mapped) - - return labels + return type(index).from_arrays(mapped) def ensure_key_mapped(values, key: Optional[Callable], levels=None):
Some refactorings found by Sourcery https://sourcery.ai/ I've removed the ones of the kind ```diff - if param: - var = a - else: - var = b + var = a if param else b ```
https://api.github.com/repos/pandas-dev/pandas/pulls/37586
2020-11-02T14:17:39Z
2021-01-20T01:40:49Z
2021-01-20T01:40:49Z
2021-01-20T17:36:20Z
CLN refactor core/computation
diff --git a/pandas/core/computation/align.py b/pandas/core/computation/align.py index 82867cf9dcd29..8a8b0d564ea49 100644 --- a/pandas/core/computation/align.py +++ b/pandas/core/computation/align.py @@ -38,8 +38,7 @@ def _align_core_single_unary_op( def _zip_axes_from_type( typ: Type[FrameOrSeries], new_axes: Sequence[int] ) -> Dict[str, int]: - axes = {name: new_axes[i] for i, name in enumerate(typ._AXIS_ORDERS)} - return axes + return {name: new_axes[i] for i, name in enumerate(typ._AXIS_ORDERS)} def _any_pandas_objects(terms) -> bool: @@ -186,8 +185,11 @@ def reconstruct_object(typ, obj, axes, dtype): # The condition is to distinguish 0-dim array (returned in case of # scalar) and 1 element array # e.g. np.array(0) and np.array([0]) - if len(obj.shape) == 1 and len(obj) == 1: - if not isinstance(ret_value, np.ndarray): - ret_value = np.array([ret_value]).astype(res_t) + if ( + len(obj.shape) == 1 + and len(obj) == 1 + and not isinstance(ret_value, np.ndarray) + ): + ret_value = np.array([ret_value]).astype(res_t) return ret_value diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index b77204861f0a4..12f16343362e2 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -52,12 +52,11 @@ def _check_engine(engine: Optional[str]) -> str: # TODO: validate this in a more general way (thinking of future engines # that won't necessarily be import-able) # Could potentially be done on engine instantiation - if engine == "numexpr": - if not NUMEXPR_INSTALLED: - raise ImportError( - "'numexpr' is not installed or an unsupported version. Cannot use " - "engine='numexpr' for query/eval if 'numexpr' is not installed" - ) + if engine == "numexpr" and not NUMEXPR_INSTALLED: + raise ImportError( + "'numexpr' is not installed or an unsupported version. Cannot use " + "engine='numexpr' for query/eval if 'numexpr' is not installed" + ) return engine diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index 8c56f02c8d3cc..c971551a7f400 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -496,15 +496,14 @@ def _maybe_evaluate_binop( f"'{lhs.type}' and '{rhs.type}'" ) - if self.engine != "pytables": - if ( - res.op in CMP_OPS_SYMS - and getattr(lhs, "is_datetime", False) - or getattr(rhs, "is_datetime", False) - ): - # all date ops must be done in python bc numexpr doesn't work - # well with NaT - return self._maybe_eval(res, self.binary_ops) + if self.engine != "pytables" and ( + res.op in CMP_OPS_SYMS + and getattr(lhs, "is_datetime", False) + or getattr(rhs, "is_datetime", False) + ): + # all date ops must be done in python bc numexpr doesn't work + # well with NaT + return self._maybe_eval(res, self.binary_ops) if res.op in eval_in_python: # "in"/"not in" ops are always evaluated in python diff --git a/pandas/core/computation/pytables.py b/pandas/core/computation/pytables.py index dd622ed724e8f..6ec637a8b4845 100644 --- a/pandas/core/computation/pytables.py +++ b/pandas/core/computation/pytables.py @@ -378,14 +378,14 @@ def prune(self, klass): operand = self.operand operand = operand.prune(klass) - if operand is not None: - if issubclass(klass, ConditionBinOp): - if operand.condition is not None: - return operand.invert() - elif issubclass(klass, FilterBinOp): - if operand.filter is not None: - return operand.invert() - + if operand is not None and ( + issubclass(klass, ConditionBinOp) + and operand.condition is not None + or not issubclass(klass, ConditionBinOp) + and issubclass(klass, FilterBinOp) + and operand.filter is not None + ): + return operand.invert() return None diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py index 2925f583bfc56..7a9b8caa985e3 100644 --- a/pandas/core/computation/scope.py +++ b/pandas/core/computation/scope.py @@ -144,8 +144,7 @@ def __init__( def __repr__(self) -> str: scope_keys = _get_pretty_string(list(self.scope.keys())) res_keys = _get_pretty_string(list(self.resolvers.keys())) - unicode_str = f"{type(self).__name__}(scope={scope_keys}, resolvers={res_keys})" - return unicode_str + return f"{type(self).__name__}(scope={scope_keys}, resolvers={res_keys})" @property def has_resolvers(self) -> bool:
Some refactorings found by Sourcery https://sourcery.ai/ I've removed the ones of the kind ```diff - if param: - var = a - else: - var = b + var = a if param else b ```
https://api.github.com/repos/pandas-dev/pandas/pulls/37585
2020-11-02T14:14:55Z
2020-11-02T23:13:18Z
2020-11-02T23:13:18Z
2020-11-03T08:12:52Z
CLN refactor core dtypes
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 1cfa9957874ac..87f6e73e09d66 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1,6 +1,9 @@ """ Routines for casting. """ + +from __future__ import annotations + from contextlib import suppress from datetime import datetime, timedelta from typing import ( @@ -114,12 +117,11 @@ def is_nested_object(obj) -> bool: This may not be necessarily be performant. """ - if isinstance(obj, ABCSeries) and is_object_dtype(obj.dtype): - - if any(isinstance(v, ABCSeries) for v in obj._values): - return True - - return False + return bool( + isinstance(obj, ABCSeries) + and is_object_dtype(obj.dtype) + and any(isinstance(v, ABCSeries) for v in obj._values) + ) def maybe_box_datetimelike(value: Scalar, dtype: Optional[Dtype] = None) -> Scalar: @@ -707,8 +709,8 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj, # a 1-element ndarray if isinstance(val, np.ndarray): - msg = "invalid ndarray passed to infer_dtype_from_scalar" if val.ndim != 0: + msg = "invalid ndarray passed to infer_dtype_from_scalar" raise ValueError(msg) dtype = val.dtype @@ -976,7 +978,7 @@ def astype_dt64_to_dt64tz( result = result.copy() return result - elif values.tz is not None and not aware: + elif values.tz is not None: result = values.tz_convert("UTC").tz_localize(None) if copy: result = result.copy() @@ -1574,7 +1576,7 @@ def find_common_type(types: List[DtypeObj]) -> DtypeObj: numpy.find_common_type """ - if len(types) == 0: + if not types: raise ValueError("no types given") first = types[0] @@ -1853,12 +1855,16 @@ def validate_numeric_casting(dtype: np.dtype, value: Scalar) -> None: ------ ValueError """ - if issubclass(dtype.type, (np.integer, np.bool_)): - if is_float(value) and np.isnan(value): - raise ValueError("Cannot assign nan to integer series") + if ( + issubclass(dtype.type, (np.integer, np.bool_)) + and is_float(value) + and np.isnan(value) + ): + raise ValueError("Cannot assign nan to integer series") - if issubclass(dtype.type, (np.integer, np.floating, complex)) and not issubclass( - dtype.type, np.bool_ + if ( + issubclass(dtype.type, (np.integer, np.floating, complex)) + and not issubclass(dtype.type, np.bool_) + and is_bool(value) ): - if is_bool(value): - raise ValueError("Cannot assign bool to float/integer series") + raise ValueError("Cannot assign bool to float/integer series") diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 46aff11835cec..1993c41db03f8 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -1724,7 +1724,7 @@ def infer_dtype_from_object(dtype): elif dtype in ["period"]: raise NotImplementedError - if dtype == "datetime" or dtype == "timedelta": + if dtype in ["datetime", "timedelta"]: dtype += "64" try: return infer_dtype_from_object(getattr(np, dtype)) @@ -1759,7 +1759,7 @@ def _validate_date_like_dtype(dtype) -> None: typ = np.datetime_data(dtype)[0] except ValueError as e: raise TypeError(e) from e - if typ != "generic" and typ != "ns": + if typ not in ["generic", "ns"]: raise ValueError( f"{repr(dtype.name)} is too specific of a frequency, " f"try passing {repr(dtype.type.__name__)}" diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index b8d2e7e1a40a9..d768f83e4d36b 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -91,10 +91,9 @@ def _cast_to_common_type(arr: ArrayLike, dtype: DtypeObj) -> ArrayLike: # are not coming from Index/Series._values), eg in BlockManager.quantile arr = ensure_wrapped_if_datetimelike(arr) - if is_extension_array_dtype(dtype): - if isinstance(arr, np.ndarray): - # numpy's astype cannot handle ExtensionDtypes - return array(arr, dtype=dtype, copy=False) + if is_extension_array_dtype(dtype) and isinstance(arr, np.ndarray): + # numpy's astype cannot handle ExtensionDtypes + return array(arr, dtype=dtype, copy=False) return arr.astype(dtype, copy=False) diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 123196f43ef2a..f31bcd97eafcf 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -421,14 +421,13 @@ def _hash_categories(categories, ordered: Ordered = True) -> int: categories = list(categories) # breaks if a np.array of categories cat_array = hash_tuples(categories) else: - if categories.dtype == "O": - if len({type(x) for x in categories}) != 1: - # TODO: hash_array doesn't handle mixed types. It casts - # everything to a str first, which means we treat - # {'1', '2'} the same as {'1', 2} - # find a better solution - hashed = hash((tuple(categories), ordered)) - return hashed + if categories.dtype == "O" and len({type(x) for x in categories}) != 1: + # TODO: hash_array doesn't handle mixed types. It casts + # everything to a str first, which means we treat + # {'1', '2'} the same as {'1', 2} + # find a better solution + hashed = hash((tuple(categories), ordered)) + return hashed if DatetimeTZDtype.is_dtype(categories.dtype): # Avoid future warning. @@ -905,7 +904,7 @@ def __hash__(self) -> int: def __eq__(self, other: Any) -> bool: if isinstance(other, str): - return other == self.name or other == self.name.title() + return other in [self.name, self.name.title()] return isinstance(other, PeriodDtype) and self.freq == other.freq diff --git a/pandas/core/dtypes/inference.py b/pandas/core/dtypes/inference.py index 329c4445b05bc..8f8ded2ad54b1 100644 --- a/pandas/core/dtypes/inference.py +++ b/pandas/core/dtypes/inference.py @@ -125,10 +125,7 @@ def is_file_like(obj) -> bool: if not (hasattr(obj, "read") or hasattr(obj, "write")): return False - if not hasattr(obj, "__iter__"): - return False - - return True + return bool(hasattr(obj, "__iter__")) def is_re(obj) -> bool: diff --git a/pandas/core/dtypes/missing.py b/pandas/core/dtypes/missing.py index e80e6f370f46e..f0455c01fa085 100644 --- a/pandas/core/dtypes/missing.py +++ b/pandas/core/dtypes/missing.py @@ -358,8 +358,8 @@ def isna_compat(arr, fill_value=np.nan) -> bool: ------- True if we can fill using this fill_value """ - dtype = arr.dtype if isna(fill_value): + dtype = arr.dtype return not (is_bool_dtype(dtype) or is_integer_dtype(dtype)) return True @@ -447,9 +447,10 @@ def array_equivalent( right = right.view("i8") # if we have structured dtypes, compare first - if left.dtype.type is np.void or right.dtype.type is np.void: - if left.dtype != right.dtype: - return False + if ( + left.dtype.type is np.void or right.dtype.type is np.void + ) and left.dtype != right.dtype: + return False return np.array_equal(left, right) @@ -637,8 +638,6 @@ def isna_all(arr: ArrayLike) -> bool: else: checker = lambda x: _isna_ndarraylike(x, inf_as_na=INF_AS_NA) - for i in range(0, total_len, chunk_len): - if not checker(arr[i : i + chunk_len]).all(): - return False - - return True + return all( + checker(arr[i : i + chunk_len]).all() for i in range(0, total_len, chunk_len) + )
Some refactorings found by Sourcery https://sourcery.ai/ I've removed the ones of the kind ```diff - if param: - var = a - else: - var = b + var = a if param else b ```
https://api.github.com/repos/pandas-dev/pandas/pulls/37584
2020-11-02T11:42:28Z
2021-01-03T17:30:25Z
2021-01-03T17:30:25Z
2021-01-03T18:06:10Z
CLN refactor core/groupby
diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py index 2387427d15670..8e278dc81a8cc 100644 --- a/pandas/core/groupby/base.py +++ b/pandas/core/groupby/base.py @@ -63,9 +63,8 @@ def _gotitem(self, key, ndim, subset=None): self = type(self)(subset, groupby=groupby, parent=self, **kwargs) self._reset_cache() - if subset.ndim == 2: - if is_scalar(key) and key in subset or is_list_like(key): - self._selection = key + if subset.ndim == 2 and (is_scalar(key) and key in subset or is_list_like(key)): + self._selection = key return self diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 457aed3a72799..d0b58e8abc4ee 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -512,12 +512,9 @@ def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): elif func not in base.transform_kernel_allowlist: msg = f"'{func}' is not a valid function name for transform(name)" raise ValueError(msg) - elif func in base.cythonized_kernels: + elif func in base.cythonized_kernels or func in base.transformation_kernels: # cythonized transform or canned "agg+broadcast" return getattr(self, func)(*args, **kwargs) - elif func in base.transformation_kernels: - return getattr(self, func)(*args, **kwargs) - # If func is a reduction, we need to broadcast the # result to the whole group. Compute func result # and deal with possible broadcasting below. @@ -1111,8 +1108,7 @@ def blk_func(bvalues: ArrayLike) -> ArrayLike: # unwrap DataFrame to get array result = result._mgr.blocks[0].values - res_values = cast_agg_result(result, bvalues, how) - return res_values + return cast_agg_result(result, bvalues, how) # TypeError -> we may have an exception in trying to aggregate # continue and exclude the block @@ -1368,12 +1364,9 @@ def transform(self, func, *args, engine=None, engine_kwargs=None, **kwargs): elif func not in base.transform_kernel_allowlist: msg = f"'{func}' is not a valid function name for transform(name)" raise ValueError(msg) - elif func in base.cythonized_kernels: + elif func in base.cythonized_kernels or func in base.transformation_kernels: # cythonized transformation or canned "reduction+broadcast" return getattr(self, func)(*args, **kwargs) - elif func in base.transformation_kernels: - return getattr(self, func)(*args, **kwargs) - # GH 30918 # Use _transform_fast only when we know func is an aggregation if func in base.reduction_kernels: @@ -1401,9 +1394,10 @@ def _transform_fast(self, result: DataFrame) -> DataFrame: # by take operation ids, _, ngroup = self.grouper.group_info result = result.reindex(self.grouper.result_index, copy=False) - output = [] - for i, _ in enumerate(result.columns): - output.append(algorithms.take_1d(result.iloc[:, i].values, ids)) + output = [ + algorithms.take_1d(result.iloc[:, i].values, ids) + for i, _ in enumerate(result.columns) + ] return self.obj._constructor._from_arrays( output, columns=result.columns, index=obj.index @@ -1462,7 +1456,7 @@ def _transform_item_by_item(self, obj: DataFrame, wrapper) -> DataFrame: else: inds.append(i) - if len(output) == 0: + if not output: raise TypeError("Transform function invalid for data types") columns = obj.columns diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index c5bc9b563ea5e..32023576b0a91 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -1001,7 +1001,7 @@ def _cython_transform(self, how: str, numeric_only: bool = True, **kwargs): key = base.OutputKey(label=name, position=idx) output[key] = result - if len(output) == 0: + if not output: raise DataError("No numeric types to aggregate") return self._wrap_transformed_output(output) @@ -1084,7 +1084,7 @@ def _cython_agg_general( output[key] = maybe_cast_result(result, obj, how=how) idx += 1 - if len(output) == 0: + if not output: raise DataError("No numeric types to aggregate") return self._wrap_aggregated_output(output, index=self.grouper.result_index) @@ -1182,7 +1182,7 @@ def _python_agg_general(self, func, *args, **kwargs): key = base.OutputKey(label=name, position=idx) output[key] = maybe_cast_result(result, obj, numeric_only=True) - if len(output) == 0: + if not output: return self._python_apply_general(f, self._selected_obj) if self.grouper._filter_empty_groups: @@ -2550,9 +2550,8 @@ def _get_cythonized_result( """ if result_is_index and aggregate: raise ValueError("'result_is_index' and 'aggregate' cannot both be True!") - if post_processing: - if not callable(post_processing): - raise ValueError("'post_processing' must be a callable!") + if post_processing and not callable(post_processing): + raise ValueError("'post_processing' must be a callable!") if pre_processing: if not callable(pre_processing): raise ValueError("'pre_processing' must be a callable!") @@ -2631,7 +2630,7 @@ def _get_cythonized_result( output[key] = result # error_msg is "" on an frame/series with no rows or columns - if len(output) == 0 and error_msg != "": + if not output and error_msg != "": raise TypeError(error_msg) if aggregate: diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index 9f0d953a2cc71..ff5379567f090 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -593,23 +593,25 @@ def group_index(self) -> Index: return self._group_index def _make_codes(self) -> None: - if self._codes is None or self._group_index is None: - # we have a list of groupers - if isinstance(self.grouper, ops.BaseGrouper): - codes = self.grouper.codes_info - uniques = self.grouper.result_index + if self._codes is not None and self._group_index is not None: + return + + # we have a list of groupers + if isinstance(self.grouper, ops.BaseGrouper): + codes = self.grouper.codes_info + uniques = self.grouper.result_index + else: + # GH35667, replace dropna=False with na_sentinel=None + if not self.dropna: + na_sentinel = None else: - # GH35667, replace dropna=False with na_sentinel=None - if not self.dropna: - na_sentinel = None - else: - na_sentinel = -1 - codes, uniques = algorithms.factorize( - self.grouper, sort=self.sort, na_sentinel=na_sentinel - ) - uniques = Index(uniques, name=self.name) - self._codes = codes - self._group_index = uniques + na_sentinel = -1 + codes, uniques = algorithms.factorize( + self.grouper, sort=self.sort, na_sentinel=na_sentinel + ) + uniques = Index(uniques, name=self.name) + self._codes = codes + self._group_index = uniques @cache_readonly def groups(self) -> Dict[Hashable, np.ndarray]: diff --git a/pandas/core/groupby/ops.py b/pandas/core/groupby/ops.py index 15725230d850a..438030008bb4d 100644 --- a/pandas/core/groupby/ops.py +++ b/pandas/core/groupby/ops.py @@ -322,10 +322,9 @@ def result_index(self) -> Index: codes = self.reconstructed_codes levels = [ping.result_index for ping in self.groupings] - result = MultiIndex( + return MultiIndex( levels=levels, codes=codes, verify_integrity=False, names=self.names ) - return result def get_group_levels(self) -> List[Index]: if not self.compressed and len(self.groupings) == 1:
Some refactorings found by Sourcery https://sourcery.ai/ I've removed the ones of the kind ```diff - if param: - var = a - else: - var = b + var = a if param else b ```
https://api.github.com/repos/pandas-dev/pandas/pulls/37583
2020-11-02T11:40:44Z
2020-11-04T22:57:59Z
2020-11-04T22:57:59Z
2020-11-05T07:12:21Z
CLN refactor core indexes
diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index 18981a2190552..d4f22e482af84 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -282,7 +282,4 @@ def all_indexes_same(indexes): """ itr = iter(indexes) first = next(itr) - for index in itr: - if not first.equals(index): - return False - return True + return all(first.equals(index) for index in itr) diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 2a5d6db41a56d..f5b9d0194833a 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -907,9 +907,7 @@ def __repr__(self) -> str_t: if data is None: data = "" - res = f"{klass_name}({data}{prepr})" - - return res + return f"{klass_name}({data}{prepr})" def _format_space(self) -> str_t: @@ -988,7 +986,6 @@ def _format_with_header( if is_object_dtype(values.dtype): values = lib.maybe_convert_objects(values, safe=1) - if is_object_dtype(values.dtype): result = [pprint_thing(x, escape_chars=("\t", "\r", "\n")) for x in values] # could have nans @@ -1616,7 +1613,7 @@ def _drop_level_numbers(self, levnums: List[int]): Drop MultiIndex levels by level _number_, not name. """ - if len(levnums) == 0: + if not levnums: return self if len(levnums) >= self.nlevels: raise ValueError( @@ -3154,7 +3151,7 @@ def _get_indexer( target, method=method, limit=limit, tolerance=tolerance ) - if method == "pad" or method == "backfill": + if method in ["pad", "backfill"]: indexer = self._get_fill_indexer(target, method, limit, tolerance) elif method == "nearest": indexer = self._get_nearest_indexer(target, limit, tolerance) @@ -3295,8 +3292,7 @@ def _filter_indexer_tolerance( ) -> np.ndarray: # error: Unsupported left operand type for - ("ExtensionArray") distance = abs(self._values[indexer] - target) # type: ignore[operator] - indexer = np.where(distance <= tolerance, indexer, -1) - return indexer + return np.where(distance <= tolerance, indexer, -1) # -------------------------------------------------------------------- # Indexer Conversion Methods @@ -3426,8 +3422,7 @@ def _convert_arr_indexer(self, keyarr): ------- converted_keyarr : array-like """ - keyarr = com.asarray_tuplesafe(keyarr) - return keyarr + return com.asarray_tuplesafe(keyarr) def _convert_list_indexer(self, keyarr): """ @@ -3795,9 +3790,8 @@ def _join_multi(self, other, how, return_indexers=True): other, level, how=how, return_indexers=return_indexers ) - if flip_order: - if isinstance(result, tuple): - return result[0], result[2], result[1] + if flip_order and isinstance(result, tuple): + return result[0], result[2], result[1] return result @final @@ -4329,7 +4323,7 @@ def append(self, other): to_concat = [self] if isinstance(other, (list, tuple)): - to_concat = to_concat + list(other) + to_concat += list(other) else: to_concat.append(other) @@ -4821,9 +4815,7 @@ def _should_fallback_to_positional(self) -> bool: """ Should an integer key be treated as positional? """ - if self.holds_integer() or self.is_boolean(): - return False - return True + return not self.holds_integer() and not self.is_boolean() def _get_values_for_loc(self, series: "Series", loc, key): """ @@ -5286,11 +5278,7 @@ def _validate_indexer(self, form: str_t, key, kind: str_t): """ assert kind in ["getitem", "iloc"] - if key is None: - pass - elif is_integer(key): - pass - else: + if key is not None and not is_integer(key): raise self._invalid_indexer(form, key) def _maybe_cast_slice_bound(self, label, side: str_t, kind): @@ -5609,9 +5597,10 @@ def _cmp_method(self, other, op): elif op in {operator.ne, operator.lt, operator.gt}: return np.zeros(len(self), dtype=bool) - if isinstance(other, (np.ndarray, Index, ABCSeries, ExtensionArray)): - if len(self) != len(other): - raise ValueError("Lengths must match to compare") + if isinstance(other, (np.ndarray, Index, ABCSeries, ExtensionArray)) and len( + self + ) != len(other): + raise ValueError("Lengths must match to compare") if not isinstance(other, ABCMultiIndex): other = extract_array(other, extract_numpy=True) @@ -5931,11 +5920,20 @@ def ensure_has_len(seq): def trim_front(strings: List[str]) -> List[str]: """ Trims zeros and decimal points. + + Examples + -------- + >>> trim_front([" a", " b"]) + ['a', 'b'] + + >>> trim_front([" a", " "]) + ['a', ''] """ - trimmed = strings - while len(strings) > 0 and all(x[0] == " " for x in trimmed): - trimmed = [x[1:] for x in trimmed] - return trimmed + if not strings: + return strings + while all(strings) and all(x[0] == " " for x in strings): + strings = [x[1:] for x in strings] + return strings def _validate_join_method(method: str): @@ -6003,15 +6001,11 @@ def _maybe_cast_with_dtype(data: np.ndarray, dtype: np.dtype, copy: bool) -> np. except ValueError: data = np.array(data, dtype=np.float64, copy=copy) - elif inferred == "string": - pass - else: + elif inferred != "string": data = data.astype(dtype) elif is_float_dtype(dtype): inferred = lib.infer_dtype(data, skipna=False) - if inferred == "string": - pass - else: + if inferred != "string": data = data.astype(dtype) else: data = np.array(data, dtype=dtype, copy=copy) diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 03a22f09b3f60..d176b6a5d8e6d 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -408,10 +408,7 @@ def _maybe_utc_convert(self, other: Index) -> Tuple["DatetimeIndex", Index]: this = self if isinstance(other, DatetimeIndex): - if self.tz is not None: - if other.tz is None: - raise TypeError("Cannot join tz-naive with tz-aware DatetimeIndex") - elif other.tz is not None: + if (self.tz is None) ^ (other.tz is None): raise TypeError("Cannot join tz-naive with tz-aware DatetimeIndex") if not timezones.tz_compare(self.tz, other.tz): @@ -745,8 +742,7 @@ def _get_string_slice(self, key: str): freq = getattr(self, "freqstr", getattr(self, "inferred_freq", None)) parsed, reso = parsing.parse_time_string(key, freq) reso = Resolution.from_attrname(reso) - loc = self._partial_date_slice(reso, parsed) - return loc + return self._partial_date_slice(reso, parsed) def slice_indexer(self, start=None, end=None, step=None, kind=None): """
Some refactorings found by Sourcery https://sourcery.ai/ I've removed the ones of the kind ```diff - if param: - var = a - else: - var = b + var = a if param else b ```
https://api.github.com/repos/pandas-dev/pandas/pulls/37582
2020-11-02T11:38:39Z
2020-12-22T21:06:18Z
2020-12-22T21:06:18Z
2020-12-23T08:06:32Z
CLN refactor core/arrays
diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 57f8f11d4d04c..82d79cc47a4ae 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -460,7 +460,7 @@ def astype(self, dtype, copy=True): if is_dtype_equal(dtype, self.dtype): if not copy: return self - elif copy: + else: return self.copy() if isinstance(dtype, StringDtype): # allow conversion to StringArrays return dtype.construct_array_type()._from_sequence(self, copy=False) @@ -544,14 +544,13 @@ def argsort( ascending = nv.validate_argsort_with_ascending(ascending, args, kwargs) values = self._values_for_argsort() - result = nargsort( + return nargsort( values, kind=kind, ascending=ascending, na_position=na_position, mask=np.asarray(self.isna()), ) - return result def argmin(self): """ @@ -780,12 +779,12 @@ def equals(self, other: object) -> bool: boolean Whether the arrays are equivalent. """ - if not type(self) == type(other): + if type(self) != type(other): return False other = cast(ExtensionArray, other) if not is_dtype_equal(self.dtype, other.dtype): return False - elif not len(self) == len(other): + elif len(self) != len(other): return False else: equal_values = self == other diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index 73aa97c832848..21306455573b8 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -170,12 +170,13 @@ def coerce_to_array( values[~mask_values] = values_object[~mask_values].astype(bool) # if the values were integer-like, validate it were actually 0/1's - if inferred_dtype in integer_like: - if not np.all( + if (inferred_dtype in integer_like) and not ( + np.all( values[~mask_values].astype(float) == values_object[~mask_values].astype(float) - ): - raise TypeError("Need to pass bool-like values") + ) + ): + raise TypeError("Need to pass bool-like values") if mask is None and mask_values is None: mask = np.zeros(len(values), dtype=bool) @@ -193,9 +194,9 @@ def coerce_to_array( if mask_values is not None: mask = mask | mask_values - if not values.ndim == 1: + if values.ndim != 1: raise ValueError("values must be a 1D list-like") - if not mask.ndim == 1: + if mask.ndim != 1: raise ValueError("mask must be a 1D list-like") return values, mask @@ -395,9 +396,8 @@ def astype(self, dtype, copy: bool = True) -> ArrayLike: self._data.astype(dtype.numpy_dtype), self._mask.copy(), copy=False ) # for integer, error if there are missing values - if is_integer_dtype(dtype): - if self._hasna: - raise ValueError("cannot convert NA to integer") + if is_integer_dtype(dtype) and self._hasna: + raise ValueError("cannot convert NA to integer") # for float dtype, ensure we use np.nan before casting (numpy cannot # deal with pd.NA) na_value = self._na_value @@ -576,7 +576,7 @@ def _logical_method(self, other, op): elif isinstance(other, np.bool_): other = other.item() - if other_is_scalar and not (other is libmissing.NA or lib.is_bool(other)): + if other_is_scalar and other is not libmissing.NA and not lib.is_bool(other): raise TypeError( "'other' should be pandas.NA or a bool. " f"Got {type(other).__name__} instead." diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 9f0414cf7a806..626fb495dec03 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1314,8 +1314,7 @@ def isna(self): Categorical.notna : Boolean inverse of Categorical.isna. """ - ret = self._codes == -1 - return ret + return self._codes == -1 isnull = isna @@ -1363,7 +1362,7 @@ def value_counts(self, dropna=True): from pandas import CategoricalIndex, Series code, cat = self._codes, self.categories - ncat, mask = len(cat), 0 <= code + ncat, mask = (len(cat), code >= 0) ix, clean = np.arange(ncat), mask.all() if dropna or clean: @@ -1920,8 +1919,7 @@ def _reverse_indexer(self) -> Dict[Hashable, np.ndarray]: ) counts = counts.cumsum() _result = (r[start:end] for start, end in zip(counts, counts[1:])) - result = dict(zip(categories, _result)) - return result + return dict(zip(categories, _result)) # ------------------------------------------------------------------ # Reductions diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 1955a96160a4a..aba142e4f3212 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1063,8 +1063,7 @@ def _time_shift(self, periods, freq=None): if isinstance(freq, str): freq = to_offset(freq) offset = periods * freq - result = self + offset - return result + return self + offset if periods == 0 or len(self) == 0: # GH#14811 empty case @@ -1534,10 +1533,9 @@ def _round(self, freq, mode, ambiguous, nonexistent): self = cast("DatetimeArray", self) naive = self.tz_localize(None) result = naive._round(freq, mode, ambiguous, nonexistent) - aware = result.tz_localize( + return result.tz_localize( self.tz, ambiguous=ambiguous, nonexistent=nonexistent ) - return aware values = self.view("i8") result = round_nsint64(values, mode, freq) diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index 9febba0f544ac..b633f268049e5 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -84,9 +84,9 @@ def __init__(self, values: np.ndarray, mask: np.ndarray, copy: bool = False): "mask should be boolean numpy array. Use " "the 'pd.array' function instead" ) - if not values.ndim == 1: + if values.ndim != 1: raise ValueError("values must be a 1D array") - if not mask.ndim == 1: + if mask.ndim != 1: raise ValueError("mask must be a 1D array") if copy: @@ -209,7 +209,8 @@ def to_numpy( dtype = object if self._hasna: if ( - not (is_object_dtype(dtype) or is_string_dtype(dtype)) + not is_object_dtype(dtype) + and not is_string_dtype(dtype) and na_value is libmissing.NA ): raise ValueError( diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index cd48f6cbc8170..e1a424b719a4a 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -281,17 +281,15 @@ def all(self, *, axis=None, out=None, keepdims=False, skipna=True): def min(self, *, skipna: bool = True, **kwargs) -> Scalar: nv.validate_min((), kwargs) - result = masked_reductions.min( + return masked_reductions.min( values=self.to_numpy(), mask=self.isna(), skipna=skipna ) - return result def max(self, *, skipna: bool = True, **kwargs) -> Scalar: nv.validate_max((), kwargs) - result = masked_reductions.max( + return masked_reductions.max( values=self.to_numpy(), mask=self.isna(), skipna=skipna ) - return result def sum(self, *, axis=None, skipna=True, min_count=0, **kwargs) -> Scalar: nv.validate_sum((), kwargs) diff --git a/pandas/core/arrays/period.py b/pandas/core/arrays/period.py index d808ade53ad33..8de84a0187e95 100644 --- a/pandas/core/arrays/period.py +++ b/pandas/core/arrays/period.py @@ -589,7 +589,7 @@ def astype(self, dtype, copy: bool = True): if is_dtype_equal(dtype, self._dtype): if not copy: return self - elif copy: + else: return self.copy() if is_period_dtype(dtype): return self.asfreq(dtype.freq) @@ -1080,11 +1080,9 @@ def _make_field_arrays(*fields): elif length is None: length = len(x) - arrays = [ + return [ np.asarray(x) if isinstance(x, (np.ndarray, list, ABCSeries)) else np.repeat(x, length) for x in fields ] - - return arrays diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 4346e02069667..5f4cd4b269a2a 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -316,9 +316,8 @@ def __init__( raise Exception("must only pass scalars with an index") if is_scalar(data): - if index is not None: - if data is None: - data = np.nan + if index is not None and data is None: + data = np.nan if index is not None: npoints = len(index) @@ -575,8 +574,7 @@ def density(self): >>> s.density 0.6 """ - r = float(self.sp_index.npoints) / float(self.sp_index.length) - return r + return float(self.sp_index.npoints) / float(self.sp_index.length) @property def npoints(self) -> int: @@ -736,25 +734,17 @@ def value_counts(self, dropna=True): keys, counts = algos.value_counts_arraylike(self.sp_values, dropna=dropna) fcounts = self.sp_index.ngaps - if fcounts > 0: - if self._null_fill_value and dropna: - pass + if fcounts > 0 and (not self._null_fill_value or not dropna): + mask = isna(keys) if self._null_fill_value else keys == self.fill_value + if mask.any(): + counts[mask] += fcounts else: - if self._null_fill_value: - mask = isna(keys) - else: - mask = keys == self.fill_value - - if mask.any(): - counts[mask] += fcounts - else: - keys = np.insert(keys, 0, self.fill_value) - counts = np.insert(counts, 0, fcounts) + keys = np.insert(keys, 0, self.fill_value) + counts = np.insert(counts, 0, fcounts) if not isinstance(keys, ABCIndexClass): keys = Index(keys) - result = Series(counts, index=keys) - return result + return Series(counts, index=keys) # -------- # Indexing @@ -1062,7 +1052,7 @@ def astype(self, dtype=None, copy=True): if is_dtype_equal(dtype, self._dtype): if not copy: return self - elif copy: + else: return self.copy() dtype = self.dtype.update_dtype(dtype) subtype = dtype._subtype_with_str diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index e4a844fd4c6ef..8a87df18b6adb 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -227,8 +227,7 @@ def _from_sequence( data, inferred_freq = sequence_to_td64ns(data, copy=copy, unit=None) freq, _ = dtl.validate_inferred_freq(None, inferred_freq, False) - result = cls._simple_new(data, freq=freq) - return result + return cls._simple_new(data, freq=freq) @classmethod def _from_sequence_not_strict( @@ -334,10 +333,9 @@ def astype(self, dtype, copy: bool = True): if self._hasnans: # avoid double-copying result = self._data.astype(dtype, copy=False) - values = self._maybe_mask_results( + return self._maybe_mask_results( result, fill_value=None, convert="float64" ) - return values result = self._data.astype(dtype, copy=copy) return result.astype("i8") elif is_timedelta64_ns_dtype(dtype):
Some refactorings found by Sourcery https://sourcery.ai/ I've removed the ones of the kind ```diff - if param: - var = a - else: - var = b + var = a if param else b ```
https://api.github.com/repos/pandas-dev/pandas/pulls/37581
2020-11-02T11:36:17Z
2020-11-04T13:47:37Z
2020-11-04T13:47:37Z
2020-11-04T14:23:02Z
CLN refactor non-core
diff --git a/pandas/_config/config.py b/pandas/_config/config.py index 0b802f2cc9e69..512b638fc4877 100644 --- a/pandas/_config/config.py +++ b/pandas/_config/config.py @@ -392,7 +392,7 @@ class option_context(ContextDecorator): """ def __init__(self, *args): - if not (len(args) % 2 == 0 and len(args) >= 2): + if len(args) % 2 != 0 or len(args) < 2: raise ValueError( "Need to invoke as option_context(pat, val, [(pat, val), ...])." ) @@ -648,7 +648,7 @@ def _build_option_description(k: str) -> str: s += f"\n [default: {o.defval}] [currently: {_get_option(k, True)}]" if d: - rkey = d.rkey if d.rkey else "" + rkey = d.rkey or "" s += "\n (Deprecated" s += f", use `{rkey}` instead." s += ")" diff --git a/pandas/_config/localization.py b/pandas/_config/localization.py index 3933c8f3d519c..bc76aca93da2a 100644 --- a/pandas/_config/localization.py +++ b/pandas/_config/localization.py @@ -99,8 +99,7 @@ def _valid_locales(locales, normalize): def _default_locale_getter(): - raw_locales = subprocess.check_output(["locale -a"], shell=True) - return raw_locales + return subprocess.check_output(["locale -a"], shell=True) def get_locales(prefix=None, normalize=True, locale_getter=_default_locale_getter): diff --git a/pandas/_testing.py b/pandas/_testing.py index a4fdb390abf42..80dc7ce153226 100644 --- a/pandas/_testing.py +++ b/pandas/_testing.py @@ -729,8 +729,7 @@ def _get_ilevel_values(index, level): unique = index.levels[level] level_codes = index.codes[level] filled = take_1d(unique._values, level_codes, fill_value=unique._na_value) - values = unique._shallow_copy(filled, name=index.names[level]) - return values + return unique._shallow_copy(filled, name=index.names[level]) if check_less_precise is not no_default: warnings.warn( @@ -1871,8 +1870,7 @@ def makeTimedeltaIndex(k=10, freq="D", name=None, **kwargs): def makePeriodIndex(k=10, name=None, **kwargs): dt = datetime(2000, 1, 1) - dr = pd.period_range(start=dt, periods=k, freq="B", name=name, **kwargs) - return dr + return pd.period_range(start=dt, periods=k, freq="B", name=name, **kwargs) def makeMultiIndex(k=10, names=None, **kwargs): @@ -2511,9 +2509,12 @@ def network( @wraps(t) def wrapper(*args, **kwargs): - if check_before_test and not raise_on_error: - if not can_connect(url, error_classes): - skip() + if ( + check_before_test + and not raise_on_error + and not can_connect(url, error_classes) + ): + skip() try: return t(*args, **kwargs) except Exception as err: @@ -2928,8 +2929,7 @@ def convert_rows_list_to_csv_str(rows_list: List[str]): Expected output of to_csv() in current OS. """ sep = os.linesep - expected = sep.join(rows_list) + sep - return expected + return sep.join(rows_list) + sep def external_error_raised(expected_exception: Type[Exception]) -> ContextManager: diff --git a/pandas/_version.py b/pandas/_version.py index b3fa8530d09eb..d2df063ff3acf 100644 --- a/pandas/_version.py +++ b/pandas/_version.py @@ -22,8 +22,7 @@ def get_keywords(): # get_keywords(). git_refnames = "$Format:%d$" git_full = "$Format:%H$" - keywords = {"refnames": git_refnames, "full": git_full} - return keywords + return {"refnames": git_refnames, "full": git_full} class VersioneerConfig: @@ -121,17 +120,16 @@ def git_get_keywords(versionfile_abs): # _version.py. keywords = {} try: - f = open(versionfile_abs) - for line in f.readlines(): - if line.strip().startswith("git_refnames ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["refnames"] = mo.group(1) - if line.strip().startswith("git_full ="): - mo = re.search(r'=\s*"(.*)"', line) - if mo: - keywords["full"] = mo.group(1) - f.close() + with open(versionfile_abs) as fd: + for line in fd.readlines(): + if line.strip().startswith("git_refnames ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["refnames"] = mo.group(1) + if line.strip().startswith("git_full ="): + mo = re.search(r'=\s*"(.*)"', line) + if mo: + keywords["full"] = mo.group(1) except OSError: pass return keywords @@ -286,13 +284,11 @@ def render_pep440(pieces): if pieces["distance"] or pieces["dirty"]: rendered += plus_or_dot(pieces) rendered += f"{pieces['distance']:d}.g{pieces['short']}" - if pieces["dirty"]: - rendered += ".dirty" else: # exception #1 rendered = f"0+untagged.{pieces['distance']:d}.g{pieces['short']}" - if pieces["dirty"]: - rendered += ".dirty" + if pieces["dirty"]: + rendered += ".dirty" return rendered @@ -348,13 +344,11 @@ def render_pep440_old(pieces): rendered = pieces["closest-tag"] if pieces["distance"] or pieces["dirty"]: rendered += f".post{pieces['distance']:d}" - if pieces["dirty"]: - rendered += ".dev0" else: # exception #1 rendered = f"0.post{pieces['distance']:d}" - if pieces["dirty"]: - rendered += ".dev0" + if pieces["dirty"]: + rendered += ".dev0" return rendered diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 57e378758cc78..2ac9b9e2c875c 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -50,7 +50,7 @@ def is_platform_windows() -> bool: bool True if the running platform is windows. """ - return sys.platform == "win32" or sys.platform == "cygwin" + return sys.platform in ["win32", "cygwin"] def is_platform_linux() -> bool: diff --git a/pandas/conftest.py b/pandas/conftest.py index 515d20e8c5781..207be8a86bb8b 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -386,13 +386,12 @@ def _create_multiindex(): major_codes = np.array([0, 0, 1, 2, 3, 3]) minor_codes = np.array([0, 1, 0, 1, 0, 1]) index_names = ["first", "second"] - mi = MultiIndex( + return MultiIndex( levels=[major_axis, minor_axis], codes=[major_codes, minor_codes], names=index_names, verify_integrity=False, ) - return mi def _create_mi_with_dt64tz_level():
Some refactorings found by Sourcery https://sourcery.ai/ I've removed the ones of the kind ```diff - if param: - var = a - else: - var = b + var = a if param else b ```
https://api.github.com/repos/pandas-dev/pandas/pulls/37580
2020-11-02T11:33:59Z
2020-11-02T22:42:17Z
2020-11-02T22:42:17Z
2020-11-03T08:14:17Z
DOC: Add windows.rst
diff --git a/doc/source/reference/window.rst b/doc/source/reference/window.rst index 77697b966df18..a255b3ae8081e 100644 --- a/doc/source/reference/window.rst +++ b/doc/source/reference/window.rst @@ -10,8 +10,10 @@ Rolling objects are returned by ``.rolling`` calls: :func:`pandas.DataFrame.roll Expanding objects are returned by ``.expanding`` calls: :func:`pandas.DataFrame.expanding`, :func:`pandas.Series.expanding`, etc. ExponentialMovingWindow objects are returned by ``.ewm`` calls: :func:`pandas.DataFrame.ewm`, :func:`pandas.Series.ewm`, etc. -Standard moving window functions --------------------------------- +.. _api.functions_rolling: + +Rolling window functions +------------------------ .. currentmodule:: pandas.core.window.rolling .. autosummary:: @@ -33,6 +35,16 @@ Standard moving window functions Rolling.aggregate Rolling.quantile Rolling.sem + +.. _api.functions_window: + +Weighted window functions +------------------------- +.. currentmodule:: pandas.core.window.rolling + +.. autosummary:: + :toctree: api/ + Window.mean Window.sum Window.var @@ -40,8 +52,8 @@ Standard moving window functions .. _api.functions_expanding: -Standard expanding window functions ------------------------------------ +Expanding window functions +-------------------------- .. currentmodule:: pandas.core.window.expanding .. autosummary:: @@ -64,8 +76,10 @@ Standard expanding window functions Expanding.quantile Expanding.sem -Exponentially-weighted moving window functions ----------------------------------------------- +.. _api.functions_ewm: + +Exponentially-weighted window functions +--------------------------------------- .. currentmodule:: pandas.core.window.ewm .. autosummary:: @@ -77,6 +91,8 @@ Exponentially-weighted moving window functions ExponentialMovingWindow.corr ExponentialMovingWindow.cov +.. _api.indexers_window: + Window indexer -------------- .. currentmodule:: pandas diff --git a/doc/source/user_guide/basics.rst b/doc/source/user_guide/basics.rst index a21e5180004b2..ffecaa222e1f9 100644 --- a/doc/source/user_guide/basics.rst +++ b/doc/source/user_guide/basics.rst @@ -538,8 +538,8 @@ standard deviation of 1), very concisely: Note that methods like :meth:`~DataFrame.cumsum` and :meth:`~DataFrame.cumprod` preserve the location of ``NaN`` values. This is somewhat different from -:meth:`~DataFrame.expanding` and :meth:`~DataFrame.rolling`. -For more details please see :ref:`this note <stats.moments.expanding.note>`. +:meth:`~DataFrame.expanding` and :meth:`~DataFrame.rolling` since ``NaN`` behavior +is furthermore dictated by a ``min_periods`` parameter. .. ipython:: python @@ -945,7 +945,7 @@ Aggregation API The aggregation API allows one to express possibly multiple aggregation operations in a single concise way. This API is similar across pandas objects, see :ref:`groupby API <groupby.aggregate>`, the -:ref:`window functions API <stats.aggregate>`, and the :ref:`resample API <timeseries.aggregate>`. +:ref:`window API <window.overview>`, and the :ref:`resample API <timeseries.aggregate>`. The entry point for aggregation is :meth:`DataFrame.aggregate`, or the alias :meth:`DataFrame.agg`. diff --git a/doc/source/user_guide/computation.rst b/doc/source/user_guide/computation.rst index 45d15f29fcce8..f05eb9cc40402 100644 --- a/doc/source/user_guide/computation.rst +++ b/doc/source/user_guide/computation.rst @@ -205,991 +205,3 @@ parameter: - ``min`` : lowest rank in the group - ``max`` : highest rank in the group - ``first`` : ranks assigned in the order they appear in the array - -.. _stats.moments: - -Window functions ----------------- - -.. currentmodule:: pandas.core.window - -For working with data, a number of window functions are provided for -computing common *window* or *rolling* statistics. Among these are count, sum, -mean, median, correlation, variance, covariance, standard deviation, skewness, -and kurtosis. - -The ``rolling()`` and ``expanding()`` -functions can be used directly from DataFrameGroupBy objects, -see the :ref:`groupby docs <groupby.transform.window_resample>`. - - -.. note:: - - The API for window statistics is quite similar to the way one works with ``GroupBy`` objects, see the documentation :ref:`here <groupby>`. - -.. warning:: - - When using ``rolling()`` and an associated function the results are calculated with rolling sums. As a consequence - when having values differing with magnitude :math:`1/np.finfo(np.double).eps` this results in truncation. It must be - noted, that large values may have an impact on windows, which do not include these values. `Kahan summation - <https://en.wikipedia.org/wiki/Kahan_summation_algorithm>`__ is used - to compute the rolling sums to preserve accuracy as much as possible. The same holds true for ``Rolling.var()`` for - values differing with magnitude :math:`(1/np.finfo(np.double).eps)^{0.5}`. - -We work with ``rolling``, ``expanding`` and ``exponentially weighted`` data through the corresponding -objects, :class:`~pandas.core.window.Rolling`, :class:`~pandas.core.window.Expanding` and :class:`~pandas.core.window.ExponentialMovingWindow`. - -.. ipython:: python - - s = pd.Series(np.random.randn(1000), index=pd.date_range("1/1/2000", periods=1000)) - s = s.cumsum() - s - -These are created from methods on ``Series`` and ``DataFrame``. - -.. ipython:: python - - r = s.rolling(window=60) - r - -These object provide tab-completion of the available methods and properties. - -.. code-block:: ipython - - In [14]: r.<TAB> # noqa: E225, E999 - r.agg r.apply r.count r.exclusions r.max r.median r.name r.skew r.sum - r.aggregate r.corr r.cov r.kurt r.mean r.min r.quantile r.std r.var - -Generally these methods all have the same interface. They all -accept the following arguments: - -- ``window``: size of moving window -- ``min_periods``: threshold of non-null data points to require (otherwise - result is NA) -- ``center``: boolean, whether to set the labels at the center (default is False) - -We can then call methods on these ``rolling`` objects. These return like-indexed objects: - -.. ipython:: python - - r.mean() - -.. ipython:: python - - s.plot(style="k--") - - @savefig rolling_mean_ex.png - r.mean().plot(style="k") - -.. ipython:: python - :suppress: - - plt.close("all") - -They can also be applied to DataFrame objects. This is really just syntactic -sugar for applying the moving window operator to all of the DataFrame's columns: - -.. ipython:: python - - df = pd.DataFrame( - np.random.randn(1000, 4), - index=pd.date_range("1/1/2000", periods=1000), - columns=["A", "B", "C", "D"], - ) - df = df.cumsum() - - @savefig rolling_mean_frame.png - df.rolling(window=60).sum().plot(subplots=True) - -.. _stats.summary: - -Method summary -~~~~~~~~~~~~~~ - -We provide a number of common statistical functions: - -.. currentmodule:: pandas.core.window - -.. csv-table:: - :header: "Method", "Description" - :widths: 20, 80 - - :meth:`~Rolling.count`, Number of non-null observations - :meth:`~Rolling.sum`, Sum of values - :meth:`~Rolling.mean`, Mean of values - :meth:`~Rolling.median`, Arithmetic median of values - :meth:`~Rolling.min`, Minimum - :meth:`~Rolling.max`, Maximum - :meth:`~Rolling.std`, Sample standard deviation - :meth:`~Rolling.var`, Sample variance - :meth:`~Rolling.skew`, Sample skewness (3rd moment) - :meth:`~Rolling.kurt`, Sample kurtosis (4th moment) - :meth:`~Rolling.quantile`, Sample quantile (value at %) - :meth:`~Rolling.apply`, Generic apply - :meth:`~Rolling.cov`, Sample covariance (binary) - :meth:`~Rolling.corr`, Sample correlation (binary) - :meth:`~Rolling.sem`, Standard error of mean - -.. _computation.window_variance.caveats: - -.. note:: - - Please note that :meth:`~Rolling.std` and :meth:`~Rolling.var` use the sample - variance formula by default, i.e. the sum of squared differences is divided by - ``window_size - 1`` and not by ``window_size`` during averaging. In statistics, - we use sample when the dataset is drawn from a larger population that we - don't have access to. Using it implies that the data in our window is a - random sample from the population, and we are interested not in the variance - inside the specific window but in the variance of some general window that - our windows represent. In this situation, using the sample variance formula - results in an unbiased estimator and so is preferred. - - Usually, we are instead interested in the variance of each window as we slide - it over the data, and in this case we should specify ``ddof=0`` when calling - these methods to use population variance instead of sample variance. Using - sample variance under the circumstances would result in a biased estimator - of the variable we are trying to determine. - - The same caveats apply to using any supported statistical sample methods. - -.. _stats.rolling_apply: - -Rolling apply -~~~~~~~~~~~~~ - -The :meth:`~Rolling.apply` function takes an extra ``func`` argument and performs -generic rolling computations. The ``func`` argument should be a single function -that produces a single value from an ndarray input. Suppose we wanted to -compute the mean absolute deviation on a rolling basis: - -.. ipython:: python - - def mad(x): - return np.fabs(x - x.mean()).mean() - - @savefig rolling_apply_ex.png - s.rolling(window=60).apply(mad, raw=True).plot(style="k") - -Using the Numba engine -~~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: 1.0 - -Additionally, :meth:`~Rolling.apply` can leverage `Numba <https://numba.pydata.org/>`__ -if installed as an optional dependency. The apply aggregation can be executed using Numba by specifying -``engine='numba'`` and ``engine_kwargs`` arguments (``raw`` must also be set to ``True``). -Numba will be applied in potentially two routines: - -1. If ``func`` is a standard Python function, the engine will `JIT <https://numba.pydata.org/numba-doc/latest/user/overview.html>`__ -the passed function. ``func`` can also be a JITed function in which case the engine will not JIT the function again. - -2. The engine will JIT the for loop where the apply function is applied to each window. - -The ``engine_kwargs`` argument is a dictionary of keyword arguments that will be passed into the -`numba.jit decorator <https://numba.pydata.org/numba-doc/latest/reference/jit-compilation.html#numba.jit>`__. -These keyword arguments will be applied to *both* the passed function (if a standard Python function) -and the apply for loop over each window. Currently only ``nogil``, ``nopython``, and ``parallel`` are supported, -and their default values are set to ``False``, ``True`` and ``False`` respectively. - -.. note:: - - In terms of performance, **the first time a function is run using the Numba engine will be slow** - as Numba will have some function compilation overhead. However, the compiled functions are cached, - and subsequent calls will be fast. In general, the Numba engine is performant with - a larger amount of data points (e.g. 1+ million). - -.. code-block:: ipython - - In [1]: data = pd.Series(range(1_000_000)) - - In [2]: roll = data.rolling(10) - - In [3]: def f(x): - ...: return np.sum(x) + 5 - # Run the first time, compilation time will affect performance - In [4]: %timeit -r 1 -n 1 roll.apply(f, engine='numba', raw=True) # noqa: E225 - 1.23 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each) - # Function is cached and performance will improve - In [5]: %timeit roll.apply(f, engine='numba', raw=True) - 188 ms ± 1.93 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) - - In [6]: %timeit roll.apply(f, engine='cython', raw=True) - 3.92 s ± 59 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) - -.. _stats.rolling_window: - -Rolling windows -~~~~~~~~~~~~~~~ - -Passing ``win_type`` to ``.rolling`` generates a generic rolling window computation, that is weighted according the ``win_type``. -The following methods are available: - -.. csv-table:: - :header: "Method", "Description" - :widths: 20, 80 - - :meth:`~Window.sum`, Sum of values - :meth:`~Window.mean`, Mean of values - -The weights used in the window are specified by the ``win_type`` keyword. -The list of recognized types are the `scipy.signal window functions -<https://docs.scipy.org/doc/scipy/reference/signal.windows.html#module-scipy.signal.windows>`__: - -* ``boxcar`` -* ``triang`` -* ``blackman`` -* ``hamming`` -* ``bartlett`` -* ``parzen`` -* ``bohman`` -* ``blackmanharris`` -* ``nuttall`` -* ``barthann`` -* ``kaiser`` (needs beta) -* ``gaussian`` (needs std) -* ``general_gaussian`` (needs power, width) -* ``slepian`` (needs width) -* ``exponential`` (needs tau). - -.. versionadded:: 1.2.0 - -All Scipy window types, concurrent with your installed version, are recognized ``win_types``. - -.. ipython:: python - - ser = pd.Series(np.random.randn(10), index=pd.date_range("1/1/2000", periods=10)) - - ser.rolling(window=5, win_type="triang").mean() - -Note that the ``boxcar`` window is equivalent to :meth:`~Rolling.mean`. - -.. ipython:: python - - ser.rolling(window=5, win_type="boxcar").mean() - ser.rolling(window=5).mean() - -For some windowing functions, additional parameters must be specified: - -.. ipython:: python - - ser.rolling(window=5, win_type="gaussian").mean(std=0.1) - -.. _stats.moments.normalization: - -.. note:: - - For ``.sum()`` with a ``win_type``, there is no normalization done to the - weights for the window. Passing custom weights of ``[1, 1, 1]`` will yield a different - result than passing weights of ``[2, 2, 2]``, for example. When passing a - ``win_type`` instead of explicitly specifying the weights, the weights are - already normalized so that the largest weight is 1. - - In contrast, the nature of the ``.mean()`` calculation is - such that the weights are normalized with respect to each other. Weights - of ``[1, 1, 1]`` and ``[2, 2, 2]`` yield the same result. - -.. _stats.moments.ts: - -Time-aware rolling -~~~~~~~~~~~~~~~~~~ - -It is possible to pass an offset (or convertible) to a ``.rolling()`` method and have it produce -variable sized windows based on the passed time window. For each time point, this includes all preceding values occurring -within the indicated time delta. - -This can be particularly useful for a non-regular time frequency index. - -.. ipython:: python - - dft = pd.DataFrame( - {"B": [0, 1, 2, np.nan, 4]}, - index=pd.date_range("20130101 09:00:00", periods=5, freq="s"), - ) - dft - -This is a regular frequency index. Using an integer window parameter works to roll along the window frequency. - -.. ipython:: python - - dft.rolling(2).sum() - dft.rolling(2, min_periods=1).sum() - -Specifying an offset allows a more intuitive specification of the rolling frequency. - -.. ipython:: python - - dft.rolling("2s").sum() - -Using a non-regular, but still monotonic index, rolling with an integer window does not impart any special calculation. - - -.. ipython:: python - - dft = pd.DataFrame( - {"B": [0, 1, 2, np.nan, 4]}, - index=pd.Index( - [ - pd.Timestamp("20130101 09:00:00"), - pd.Timestamp("20130101 09:00:02"), - pd.Timestamp("20130101 09:00:03"), - pd.Timestamp("20130101 09:00:05"), - pd.Timestamp("20130101 09:00:06"), - ], - name="foo", - ), - ) - dft - dft.rolling(2).sum() - - -Using the time-specification generates variable windows for this sparse data. - -.. ipython:: python - - dft.rolling("2s").sum() - -Furthermore, we now allow an optional ``on`` parameter to specify a column (rather than the -default of the index) in a DataFrame. - -.. ipython:: python - - dft = dft.reset_index() - dft - dft.rolling("2s", on="foo").sum() - -.. _stats.custom_rolling_window: - -Custom window rolling -~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: 1.0 - -In addition to accepting an integer or offset as a ``window`` argument, ``rolling`` also accepts -a ``BaseIndexer`` subclass that allows a user to define a custom method for calculating window bounds. -The ``BaseIndexer`` subclass will need to define a ``get_window_bounds`` method that returns -a tuple of two arrays, the first being the starting indices of the windows and second being the -ending indices of the windows. Additionally, ``num_values``, ``min_periods``, ``center``, ``closed`` -and will automatically be passed to ``get_window_bounds`` and the defined method must -always accept these arguments. - -For example, if we have the following ``DataFrame``: - -.. ipython:: python - - use_expanding = [True, False, True, False, True] - use_expanding - df = pd.DataFrame({"values": range(5)}) - df - -and we want to use an expanding window where ``use_expanding`` is ``True`` otherwise a window of size -1, we can create the following ``BaseIndexer`` subclass: - -.. code-block:: ipython - - In [2]: from pandas.api.indexers import BaseIndexer - ...: - ...: class CustomIndexer(BaseIndexer): - ...: - ...: def get_window_bounds(self, num_values, min_periods, center, closed): - ...: start = np.empty(num_values, dtype=np.int64) - ...: end = np.empty(num_values, dtype=np.int64) - ...: for i in range(num_values): - ...: if self.use_expanding[i]: - ...: start[i] = 0 - ...: end[i] = i + 1 - ...: else: - ...: start[i] = i - ...: end[i] = i + self.window_size - ...: return start, end - ...: - - In [3]: indexer = CustomIndexer(window_size=1, use_expanding=use_expanding) - - In [4]: df.rolling(indexer).sum() - Out[4]: - values - 0 0.0 - 1 1.0 - 2 3.0 - 3 3.0 - 4 10.0 - -You can view other examples of ``BaseIndexer`` subclasses `here <https://github.com/pandas-dev/pandas/blob/master/pandas/core/window/indexers.py>`__ - -.. versionadded:: 1.1 - -One subclass of note within those examples is the ``VariableOffsetWindowIndexer`` that allows -rolling operations over a non-fixed offset like a ``BusinessDay``. - -.. ipython:: python - - from pandas.api.indexers import VariableOffsetWindowIndexer - - df = pd.DataFrame(range(10), index=pd.date_range("2020", periods=10)) - offset = pd.offsets.BDay(1) - indexer = VariableOffsetWindowIndexer(index=df.index, offset=offset) - df - df.rolling(indexer).sum() - -For some problems knowledge of the future is available for analysis. For example, this occurs when -each data point is a full time series read from an experiment, and the task is to extract underlying -conditions. In these cases it can be useful to perform forward-looking rolling window computations. -:func:`FixedForwardWindowIndexer <pandas.api.indexers.FixedForwardWindowIndexer>` class is available for this purpose. -This :func:`BaseIndexer <pandas.api.indexers.BaseIndexer>` subclass implements a closed fixed-width -forward-looking rolling window, and we can use it as follows: - -.. ipython:: ipython - - from pandas.api.indexers import FixedForwardWindowIndexer - indexer = FixedForwardWindowIndexer(window_size=2) - df.rolling(indexer, min_periods=1).sum() - -.. _stats.rolling_window.endpoints: - -Rolling window endpoints -~~~~~~~~~~~~~~~~~~~~~~~~ - -The inclusion of the interval endpoints in rolling window calculations can be specified with the ``closed`` -parameter: - -.. csv-table:: - :header: "``closed``", "Description", "Default for" - :widths: 20, 30, 30 - - ``right``, close right endpoint, - ``left``, close left endpoint, - ``both``, close both endpoints, - ``neither``, open endpoints, - -For example, having the right endpoint open is useful in many problems that require that there is no contamination -from present information back to past information. This allows the rolling window to compute statistics -"up to that point in time", but not including that point in time. - -.. ipython:: python - - df = pd.DataFrame( - {"x": 1}, - index=[ - pd.Timestamp("20130101 09:00:01"), - pd.Timestamp("20130101 09:00:02"), - pd.Timestamp("20130101 09:00:03"), - pd.Timestamp("20130101 09:00:04"), - pd.Timestamp("20130101 09:00:06"), - ], - ) - - df["right"] = df.rolling("2s", closed="right").x.sum() # default - df["both"] = df.rolling("2s", closed="both").x.sum() - df["left"] = df.rolling("2s", closed="left").x.sum() - df["neither"] = df.rolling("2s", closed="neither").x.sum() - - df - -.. _stats.iter_rolling_window: - -Iteration over window: -~~~~~~~~~~~~~~~~~~~~~~ - -.. versionadded:: 1.1.0 - -``Rolling`` and ``Expanding`` objects now support iteration. Be noted that ``min_periods`` is ignored in iteration. - -.. ipython:: - - In [1]: df = pd.DataFrame({"A": [1, 2, 3], "B": [4, 5, 6]}) - - In [2]: for i in df.rolling(2): - ...: print(i) - ...: - - -.. _stats.moments.ts-versus-resampling: - -Time-aware rolling vs. resampling -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Using ``.rolling()`` with a time-based index is quite similar to :ref:`resampling <timeseries.resampling>`. They -both operate and perform reductive operations on time-indexed pandas objects. - -When using ``.rolling()`` with an offset. The offset is a time-delta. Take a backwards-in-time looking window, and -aggregate all of the values in that window (including the end-point, but not the start-point). This is the new value -at that point in the result. These are variable sized windows in time-space for each point of the input. You will get -a same sized result as the input. - -When using ``.resample()`` with an offset. Construct a new index that is the frequency of the offset. For each frequency -bin, aggregate points from the input within a backwards-in-time looking window that fall in that bin. The result of this -aggregation is the output for that frequency point. The windows are fixed size in the frequency space. Your result -will have the shape of a regular frequency between the min and the max of the original input object. - -To summarize, ``.rolling()`` is a time-based window operation, while ``.resample()`` is a frequency-based window operation. - -Centering windows -~~~~~~~~~~~~~~~~~ - -By default the labels are set to the right edge of the window, but a -``center`` keyword is available so the labels can be set at the center. - -.. ipython:: python - - ser.rolling(window=5).mean() - ser.rolling(window=5, center=True).mean() - -.. _stats.moments.binary: - -Binary window functions -~~~~~~~~~~~~~~~~~~~~~~~ - -:meth:`~Rolling.cov` and :meth:`~Rolling.corr` can compute moving window statistics about -two ``Series`` or any combination of ``DataFrame/Series`` or -``DataFrame/DataFrame``. Here is the behavior in each case: - -* two ``Series``: compute the statistic for the pairing. -* ``DataFrame/Series``: compute the statistics for each column of the DataFrame - with the passed Series, thus returning a DataFrame. -* ``DataFrame/DataFrame``: by default compute the statistic for matching column - names, returning a DataFrame. If the keyword argument ``pairwise=True`` is - passed then computes the statistic for each pair of columns, returning a - ``MultiIndexed DataFrame`` whose ``index`` are the dates in question (see :ref:`the next section - <stats.moments.corr_pairwise>`). - -For example: - -.. ipython:: python - - df = pd.DataFrame( - np.random.randn(1000, 4), - index=pd.date_range("1/1/2000", periods=1000), - columns=["A", "B", "C", "D"], - ) - df = df.cumsum() - - df2 = df[:20] - df2.rolling(window=5).corr(df2["B"]) - -.. _stats.moments.corr_pairwise: - -Computing rolling pairwise covariances and correlations -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -In financial data analysis and other fields it's common to compute covariance -and correlation matrices for a collection of time series. Often one is also -interested in moving-window covariance and correlation matrices. This can be -done by passing the ``pairwise`` keyword argument, which in the case of -``DataFrame`` inputs will yield a MultiIndexed ``DataFrame`` whose ``index`` are the dates in -question. In the case of a single DataFrame argument the ``pairwise`` argument -can even be omitted: - -.. note:: - - Missing values are ignored and each entry is computed using the pairwise - complete observations. Please see the :ref:`covariance section - <computation.covariance>` for :ref:`caveats - <computation.covariance.caveats>` associated with this method of - calculating covariance and correlation matrices. - -.. ipython:: python - - covs = ( - df[["B", "C", "D"]] - .rolling(window=50) - .cov(df[["A", "B", "C"]], pairwise=True) - ) - covs.loc["2002-09-22":] - -.. ipython:: python - - correls = df.rolling(window=50).corr() - correls.loc["2002-09-22":] - -You can efficiently retrieve the time series of correlations between two -columns by reshaping and indexing: - -.. ipython:: python - :suppress: - - plt.close("all") - -.. ipython:: python - - @savefig rolling_corr_pairwise_ex.png - correls.unstack(1)[("A", "C")].plot() - -.. _stats.aggregate: - -Aggregation ------------ - -Once the ``Rolling``, ``Expanding`` or ``ExponentialMovingWindow`` objects have been created, several methods are available to -perform multiple computations on the data. These operations are similar to the :ref:`aggregating API <basics.aggregate>`, -:ref:`groupby API <groupby.aggregate>`, and :ref:`resample API <timeseries.aggregate>`. - - -.. ipython:: python - - dfa = pd.DataFrame( - np.random.randn(1000, 3), - index=pd.date_range("1/1/2000", periods=1000), - columns=["A", "B", "C"], - ) - r = dfa.rolling(window=60, min_periods=1) - r - -We can aggregate by passing a function to the entire DataFrame, or select a -Series (or multiple Series) via standard ``__getitem__``. - -.. ipython:: python - - r.aggregate(np.sum) - - r["A"].aggregate(np.sum) - - r[["A", "B"]].aggregate(np.sum) - -As you can see, the result of the aggregation will have the selected columns, or all -columns if none are selected. - -.. _stats.aggregate.multifunc: - -Applying multiple functions -~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -With windowed ``Series`` you can also pass a list of functions to do -aggregation with, outputting a DataFrame: - -.. ipython:: python - - r["A"].agg([np.sum, np.mean, np.std]) - -On a windowed DataFrame, you can pass a list of functions to apply to each -column, which produces an aggregated result with a hierarchical index: - -.. ipython:: python - - r.agg([np.sum, np.mean]) - -Passing a dict of functions has different behavior by default, see the next -section. - -Applying different functions to DataFrame columns -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -By passing a dict to ``aggregate`` you can apply a different aggregation to the -columns of a ``DataFrame``: - -.. ipython:: python - - r.agg({"A": np.sum, "B": lambda x: np.std(x, ddof=1)}) - -The function names can also be strings. In order for a string to be valid it -must be implemented on the windowed object - -.. ipython:: python - - r.agg({"A": "sum", "B": "std"}) - -Furthermore you can pass a nested dict to indicate different aggregations on different columns. - -.. ipython:: python - - r.agg({"A": ["sum", "std"], "B": ["mean", "std"]}) - - -.. _stats.moments.expanding: - -Expanding windows ------------------ - -A common alternative to rolling statistics is to use an *expanding* window, -which yields the value of the statistic with all the data available up to that -point in time. - -These follow a similar interface to ``.rolling``, with the ``.expanding`` method -returning an :class:`~pandas.core.window.Expanding` object. - -As these calculations are a special case of rolling statistics, -they are implemented in pandas such that the following two calls are equivalent: - -.. ipython:: python - - df.rolling(window=len(df), min_periods=1).mean()[:5] - - df.expanding(min_periods=1).mean()[:5] - -These have a similar set of methods to ``.rolling`` methods. - -Method summary -~~~~~~~~~~~~~~ - -.. currentmodule:: pandas.core.window - -.. csv-table:: - :header: "Function", "Description" - :widths: 20, 80 - - :meth:`~Expanding.count`, Number of non-null observations - :meth:`~Expanding.sum`, Sum of values - :meth:`~Expanding.mean`, Mean of values - :meth:`~Expanding.median`, Arithmetic median of values - :meth:`~Expanding.min`, Minimum - :meth:`~Expanding.max`, Maximum - :meth:`~Expanding.std`, Sample standard deviation - :meth:`~Expanding.var`, Sample variance - :meth:`~Expanding.skew`, Sample skewness (3rd moment) - :meth:`~Expanding.kurt`, Sample kurtosis (4th moment) - :meth:`~Expanding.quantile`, Sample quantile (value at %) - :meth:`~Expanding.apply`, Generic apply - :meth:`~Expanding.cov`, Sample covariance (binary) - :meth:`~Expanding.corr`, Sample correlation (binary) - :meth:`~Expanding.sem`, Standard error of mean - -.. note:: - - Using sample variance formulas for :meth:`~Expanding.std` and - :meth:`~Expanding.var` comes with the same caveats as using them with rolling - windows. See :ref:`this section <computation.window_variance.caveats>` for more - information. - - The same caveats apply to using any supported statistical sample methods. - -.. currentmodule:: pandas - -Aside from not having a ``window`` parameter, these functions have the same -interfaces as their ``.rolling`` counterparts. Like above, the parameters they -all accept are: - -* ``min_periods``: threshold of non-null data points to require. Defaults to - minimum needed to compute statistic. No ``NaNs`` will be output once - ``min_periods`` non-null data points have been seen. -* ``center``: boolean, whether to set the labels at the center (default is False). - -.. _stats.moments.expanding.note: -.. note:: - - The output of the ``.rolling`` and ``.expanding`` methods do not return a - ``NaN`` if there are at least ``min_periods`` non-null values in the current - window. For example: - - .. ipython:: python - - sn = pd.Series([1, 2, np.nan, 3, np.nan, 4]) - sn - sn.rolling(2).max() - sn.rolling(2, min_periods=1).max() - - In case of expanding functions, this differs from :meth:`~DataFrame.cumsum`, - :meth:`~DataFrame.cumprod`, :meth:`~DataFrame.cummax`, - and :meth:`~DataFrame.cummin`, which return ``NaN`` in the output wherever - a ``NaN`` is encountered in the input. In order to match the output of ``cumsum`` - with ``expanding``, use :meth:`~DataFrame.fillna`: - - .. ipython:: python - - sn.expanding().sum() - sn.cumsum() - sn.cumsum().fillna(method="ffill") - - -An expanding window statistic will be more stable (and less responsive) than -its rolling window counterpart as the increasing window size decreases the -relative impact of an individual data point. As an example, here is the -:meth:`~core.window.Expanding.mean` output for the previous time series dataset: - -.. ipython:: python - :suppress: - - plt.close("all") - -.. ipython:: python - - s.plot(style="k--") - - @savefig expanding_mean_frame.png - s.expanding().mean().plot(style="k") - - -.. _stats.moments.exponentially_weighted: - -Exponentially weighted windows ------------------------------- - -.. currentmodule:: pandas.core.window - -A related set of functions are exponentially weighted versions of several of -the above statistics. A similar interface to ``.rolling`` and ``.expanding`` is accessed -through the ``.ewm`` method to receive an :class:`~ExponentialMovingWindow` object. -A number of expanding EW (exponentially weighted) -methods are provided: - - -.. csv-table:: - :header: "Function", "Description" - :widths: 20, 80 - - :meth:`~ExponentialMovingWindow.mean`, EW moving average - :meth:`~ExponentialMovingWindow.var`, EW moving variance - :meth:`~ExponentialMovingWindow.std`, EW moving standard deviation - :meth:`~ExponentialMovingWindow.corr`, EW moving correlation - :meth:`~ExponentialMovingWindow.cov`, EW moving covariance - -In general, a weighted moving average is calculated as - -.. math:: - - y_t = \frac{\sum_{i=0}^t w_i x_{t-i}}{\sum_{i=0}^t w_i}, - -where :math:`x_t` is the input, :math:`y_t` is the result and the :math:`w_i` -are the weights. - -The EW functions support two variants of exponential weights. -The default, ``adjust=True``, uses the weights :math:`w_i = (1 - \alpha)^i` -which gives - -.. math:: - - y_t = \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ... - + (1 - \alpha)^t x_{0}}{1 + (1 - \alpha) + (1 - \alpha)^2 + ... - + (1 - \alpha)^t} - -When ``adjust=False`` is specified, moving averages are calculated as - -.. math:: - - y_0 &= x_0 \\ - y_t &= (1 - \alpha) y_{t-1} + \alpha x_t, - -which is equivalent to using weights - -.. math:: - - w_i = \begin{cases} - \alpha (1 - \alpha)^i & \text{if } i < t \\ - (1 - \alpha)^i & \text{if } i = t. - \end{cases} - -.. note:: - - These equations are sometimes written in terms of :math:`\alpha' = 1 - \alpha`, e.g. - - .. math:: - - y_t = \alpha' y_{t-1} + (1 - \alpha') x_t. - -The difference between the above two variants arises because we are -dealing with series which have finite history. Consider a series of infinite -history, with ``adjust=True``: - -.. math:: - - y_t = \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...} - {1 + (1 - \alpha) + (1 - \alpha)^2 + ...} - -Noting that the denominator is a geometric series with initial term equal to 1 -and a ratio of :math:`1 - \alpha` we have - -.. math:: - - y_t &= \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...} - {\frac{1}{1 - (1 - \alpha)}}\\ - &= [x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...] \alpha \\ - &= \alpha x_t + [(1-\alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...]\alpha \\ - &= \alpha x_t + (1 - \alpha)[x_{t-1} + (1 - \alpha) x_{t-2} + ...]\alpha\\ - &= \alpha x_t + (1 - \alpha) y_{t-1} - -which is the same expression as ``adjust=False`` above and therefore -shows the equivalence of the two variants for infinite series. -When ``adjust=False``, we have :math:`y_0 = x_0` and -:math:`y_t = \alpha x_t + (1 - \alpha) y_{t-1}`. -Therefore, there is an assumption that :math:`x_0` is not an ordinary value -but rather an exponentially weighted moment of the infinite series up to that -point. - -One must have :math:`0 < \alpha \leq 1`, and while it is possible to pass -:math:`\alpha` directly, it's often easier to think about either the -**span**, **center of mass (com)** or **half-life** of an EW moment: - -.. math:: - - \alpha = - \begin{cases} - \frac{2}{s + 1}, & \text{for span}\ s \geq 1\\ - \frac{1}{1 + c}, & \text{for center of mass}\ c \geq 0\\ - 1 - \exp^{\frac{\log 0.5}{h}}, & \text{for half-life}\ h > 0 - \end{cases} - -One must specify precisely one of **span**, **center of mass**, **half-life** -and **alpha** to the EW functions: - -* **Span** corresponds to what is commonly called an "N-day EW moving average". -* **Center of mass** has a more physical interpretation and can be thought of - in terms of span: :math:`c = (s - 1) / 2`. -* **Half-life** is the period of time for the exponential weight to reduce to - one half. -* **Alpha** specifies the smoothing factor directly. - -.. versionadded:: 1.1.0 - -You can also specify ``halflife`` in terms of a timedelta convertible unit to specify the amount of -time it takes for an observation to decay to half its value when also specifying a sequence -of ``times``. - -.. ipython:: python - - df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]}) - df - times = ["2020-01-01", "2020-01-03", "2020-01-10", "2020-01-15", "2020-01-17"] - df.ewm(halflife="4 days", times=pd.DatetimeIndex(times)).mean() - -The following formula is used to compute exponentially weighted mean with an input vector of times: - -.. math:: - - y_t = \frac{\sum_{i=0}^t 0.5^\frac{t_{t} - t_{i}}{\lambda} x_{t-i}}{0.5^\frac{t_{t} - t_{i}}{\lambda}}, - -Here is an example for a univariate time series: - -.. ipython:: python - - s.plot(style="k--") - - @savefig ewma_ex.png - s.ewm(span=20).mean().plot(style="k") - -ExponentialMovingWindow has a ``min_periods`` argument, which has the same -meaning it does for all the ``.expanding`` and ``.rolling`` methods: -no output values will be set until at least ``min_periods`` non-null values -are encountered in the (expanding) window. - -ExponentialMovingWindow also has an ``ignore_na`` argument, which determines how -intermediate null values affect the calculation of the weights. -When ``ignore_na=False`` (the default), weights are calculated based on absolute -positions, so that intermediate null values affect the result. -When ``ignore_na=True``, -weights are calculated by ignoring intermediate null values. -For example, assuming ``adjust=True``, if ``ignore_na=False``, the weighted -average of ``3, NaN, 5`` would be calculated as - -.. math:: - - \frac{(1-\alpha)^2 \cdot 3 + 1 \cdot 5}{(1-\alpha)^2 + 1}. - -Whereas if ``ignore_na=True``, the weighted average would be calculated as - -.. math:: - - \frac{(1-\alpha) \cdot 3 + 1 \cdot 5}{(1-\alpha) + 1}. - -The :meth:`~Ewm.var`, :meth:`~Ewm.std`, and :meth:`~Ewm.cov` functions have a ``bias`` argument, -specifying whether the result should contain biased or unbiased statistics. -For example, if ``bias=True``, ``ewmvar(x)`` is calculated as -``ewmvar(x) = ewma(x**2) - ewma(x)**2``; -whereas if ``bias=False`` (the default), the biased variance statistics -are scaled by debiasing factors - -.. math:: - - \frac{\left(\sum_{i=0}^t w_i\right)^2}{\left(\sum_{i=0}^t w_i\right)^2 - \sum_{i=0}^t w_i^2}. - -(For :math:`w_i = 1`, this reduces to the usual :math:`N / (N - 1)` factor, -with :math:`N = t + 1`.) -See `Weighted Sample Variance <https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Weighted_sample_variance>`__ -on Wikipedia for further details. diff --git a/doc/source/user_guide/enhancingperf.rst b/doc/source/user_guide/enhancingperf.rst index 39257c06feffe..42621c032416d 100644 --- a/doc/source/user_guide/enhancingperf.rst +++ b/doc/source/user_guide/enhancingperf.rst @@ -375,7 +375,7 @@ Numba as an argument Additionally, we can leverage the power of `Numba <https://numba.pydata.org/>`__ by calling it as an argument in :meth:`~Rolling.apply`. See :ref:`Computation tools -<stats.rolling_apply>` for an extensive example. +<window.numba_engine>` for an extensive example. Vectorize ~~~~~~~~~ diff --git a/doc/source/user_guide/groupby.rst b/doc/source/user_guide/groupby.rst index 87ead5a1b80f0..e19dace572e59 100644 --- a/doc/source/user_guide/groupby.rst +++ b/doc/source/user_guide/groupby.rst @@ -478,7 +478,7 @@ Aggregation Once the GroupBy object has been created, several methods are available to perform a computation on the grouped data. These operations are similar to the -:ref:`aggregating API <basics.aggregate>`, :ref:`window functions API <stats.aggregate>`, +:ref:`aggregating API <basics.aggregate>`, :ref:`window API <window.overview>`, and :ref:`resample API <timeseries.aggregate>`. An obvious one is aggregation via the diff --git a/doc/source/user_guide/index.rst b/doc/source/user_guide/index.rst index 2fc9e066e6712..901f42097b911 100644 --- a/doc/source/user_guide/index.rst +++ b/doc/source/user_guide/index.rst @@ -40,6 +40,7 @@ Further information on any specific method can be obtained in the visualization computation groupby + window timeseries timedeltas style diff --git a/doc/source/user_guide/timeseries.rst b/doc/source/user_guide/timeseries.rst index ac8ba2fd929a6..169c0cfbbb87e 100644 --- a/doc/source/user_guide/timeseries.rst +++ b/doc/source/user_guide/timeseries.rst @@ -1580,11 +1580,6 @@ some advanced strategies. The ``resample()`` method can be used directly from ``DataFrameGroupBy`` objects, see the :ref:`groupby docs <groupby.transform.window_resample>`. -.. note:: - - ``.resample()`` is similar to using a :meth:`~Series.rolling` operation with - a time-based offset, see a discussion :ref:`here <stats.moments.ts-versus-resampling>`. - Basics ~~~~~~ @@ -1730,7 +1725,7 @@ We can instead only resample those groups where we have points as follows: Aggregation ~~~~~~~~~~~ -Similar to the :ref:`aggregating API <basics.aggregate>`, :ref:`groupby API <groupby.aggregate>`, and the :ref:`window functions API <stats.aggregate>`, +Similar to the :ref:`aggregating API <basics.aggregate>`, :ref:`groupby API <groupby.aggregate>`, and the :ref:`window API <window.overview>`, a ``Resampler`` can be selectively resampled. Resampling a ``DataFrame``, the default will be to act on all columns with the same function. diff --git a/doc/source/user_guide/window.rst b/doc/source/user_guide/window.rst new file mode 100644 index 0000000000000..47ef1e9c8c4d7 --- /dev/null +++ b/doc/source/user_guide/window.rst @@ -0,0 +1,593 @@ +.. _window: + +{{ header }} + +******************** +Windowing Operations +******************** + +pandas contains a compact set of APIs for performing windowing operations - an operation that performs +an aggregation over a sliding partition of values. The API functions similarly to the ``groupby`` API +in that :class:`Series` and :class:`DataFrame` call the windowing method with +necessary parameters and then subsequently call the aggregation function. + +.. ipython:: python + + s = pd.Series(range(5)) + s.rolling(window=2).sum() + +The windows are comprised by looking back the length of the window from the current observation. +The result above can be derived by taking the sum of the following windowed partitions of data: + +.. ipython:: python + + for window in s.rolling(window=2): + print(window) + + +.. _window.overview: + +Overview +-------- + +pandas supports 4 types of windowing operations: + +#. Rolling window: Generic fixed or variable sliding window over the values. +#. Weighted window: Weighted, non-rectangular window supplied by the ``scipy.signal`` library. +#. Expanding window: Accumulating window over the values. +#. Exponentially Weighted window: Accumulating and exponentially weighted window over the values. + +============================= ================= =========================== =========================== ======================== +Concept Method Returned Object Supports time-based windows Supports chained groupby +============================= ================= =========================== =========================== ======================== +Rolling window ``rolling`` ``Rolling`` Yes Yes +Weighted window ``rolling`` ``Window`` No No +Expanding window ``expanding`` ``Expanding`` No Yes +Exponentially Weighted window ``ewm`` ``ExponentialMovingWindow`` No No +============================= ================= =========================== =========================== ======================== + +As noted above, some operations support specifying a window based on a time offset: + +.. ipython:: python + + s = pd.Series(range(5), index=pd.date_range('2020-01-01', periods=5, freq='1D')) + s.rolling(window='2D').sum() + +Additionally, some methods support chaining a ``groupby`` operation with a windowing operation +which will first group the data by the specified keys and then perform a windowing operation per group. + +.. ipython:: python + + df = pd.DataFrame({'A': ['a', 'b', 'a', 'b', 'a'], 'B': range(5)}) + df.groupby('A').expanding().sum() + +.. note:: + + Windowing operations currently only support numeric data (integer and float) + and will always return ``float64`` values. + +.. warning:: + + Some windowing aggregation, ``mean``, ``sum``, ``var`` and ``std`` methods may suffer from numerical + imprecision due to the underlying windowing algorithms accumulating sums. When values differ + with magnitude :math:`1/np.finfo(np.double).eps` this results in truncation. It must be + noted, that large values may have an impact on windows, which do not include these values. `Kahan summation + <https://en.wikipedia.org/wiki/Kahan_summation_algorithm>`__ is used + to compute the rolling sums to preserve accuracy as much as possible. + + +All windowing operations support a ``min_periods`` argument that dictates the minimum amount of +non-``np.nan`` values a window must have; otherwise, the resulting value is ``np.nan``. +``min_peridos`` defaults to 1 for time-based windows and ``window`` for fixed windows + +.. ipython:: python + + s = pd.Series([np.nan, 1, 2, np.nan, np.nan, 3]) + s.rolling(window=3, min_periods=1).sum() + s.rolling(window=3, min_periods=2).sum() + # Equivalent to min_periods=3 + s.rolling(window=3, min_periods=None).sum() + + +Additionally, all windowing operations supports the ``aggregate`` method for returning a result +of multiple aggregations applied to a window. + +.. ipython:: python + + df = pd.DataFrame({"A": range(5), "B": range(10, 15)}) + df.expanding().agg([np.sum, np.mean, np.std]) + + +.. _window.generic: + +Rolling window +-------------- + +Generic rolling windows support specifying windows as a fixed number of observations or variable +number of observations based on an offset. If a time based offset is provided, the corresponding +time based index must be monotonic. + +.. ipython:: python + + times = ['2020-01-01', '2020-01-03', '2020-01-04', '2020-01-05', '2020-01-29'] + s = pd.Series(range(5), index=pd.DatetimeIndex(times)) + s + # Window with 2 observations + s.rolling(window=2).sum() + # Window with 2 days worth of observations + s.rolling(window='2D').sum() + +For all supported aggregation functions, see :ref:`api.functions_rolling`. + +.. _window.center: + +Centering windows +~~~~~~~~~~~~~~~~~ + +By default the labels are set to the right edge of the window, but a +``center`` keyword is available so the labels can be set at the center. + +.. ipython:: python + + s = pd.Series(range(10)) + s.rolling(window=5).mean() + s.rolling(window=5, center=True).mean() + + +.. _window.endpoints: + +Rolling window endpoints +~~~~~~~~~~~~~~~~~~~~~~~~ + +The inclusion of the interval endpoints in rolling window calculations can be specified with the ``closed`` +parameter: + +============= ==================== +Value Behavior +============= ==================== +``right'`` close right endpoint +``'left'`` close left endpoint +``'both'`` close both endpoints +``'neither'`` open endpoints +============= ==================== + +For example, having the right endpoint open is useful in many problems that require that there is no contamination +from present information back to past information. This allows the rolling window to compute statistics +"up to that point in time", but not including that point in time. + +.. ipython:: python + + df = pd.DataFrame( + {"x": 1}, + index=[ + pd.Timestamp("20130101 09:00:01"), + pd.Timestamp("20130101 09:00:02"), + pd.Timestamp("20130101 09:00:03"), + pd.Timestamp("20130101 09:00:04"), + pd.Timestamp("20130101 09:00:06"), + ], + ) + + df["right"] = df.rolling("2s", closed="right").x.sum() # default + df["both"] = df.rolling("2s", closed="both").x.sum() + df["left"] = df.rolling("2s", closed="left").x.sum() + df["neither"] = df.rolling("2s", closed="neither").x.sum() + + df + + +.. _window.custom_rolling_window: + +Custom window rolling +~~~~~~~~~~~~~~~~~~~~~ + +.. versionadded:: 1.0 + +In addition to accepting an integer or offset as a ``window`` argument, ``rolling`` also accepts +a ``BaseIndexer`` subclass that allows a user to define a custom method for calculating window bounds. +The ``BaseIndexer`` subclass will need to define a ``get_window_bounds`` method that returns +a tuple of two arrays, the first being the starting indices of the windows and second being the +ending indices of the windows. Additionally, ``num_values``, ``min_periods``, ``center``, ``closed`` +and will automatically be passed to ``get_window_bounds`` and the defined method must +always accept these arguments. + +For example, if we have the following :class:``DataFrame``: + +.. ipython:: python + + use_expanding = [True, False, True, False, True] + use_expanding + df = pd.DataFrame({"values": range(5)}) + df + +and we want to use an expanding window where ``use_expanding`` is ``True`` otherwise a window of size +1, we can create the following ``BaseIndexer`` subclass: + +.. code-block:: ipython + + In [2]: from pandas.api.indexers import BaseIndexer + ...: + ...: class CustomIndexer(BaseIndexer): + ...: + ...: def get_window_bounds(self, num_values, min_periods, center, closed): + ...: start = np.empty(num_values, dtype=np.int64) + ...: end = np.empty(num_values, dtype=np.int64) + ...: for i in range(num_values): + ...: if self.use_expanding[i]: + ...: start[i] = 0 + ...: end[i] = i + 1 + ...: else: + ...: start[i] = i + ...: end[i] = i + self.window_size + ...: return start, end + ...: + + In [3]: indexer = CustomIndexer(window_size=1, use_expanding=use_expanding) + + In [4]: df.rolling(indexer).sum() + Out[4]: + values + 0 0.0 + 1 1.0 + 2 3.0 + 3 3.0 + 4 10.0 + +You can view other examples of ``BaseIndexer`` subclasses `here <https://github.com/pandas-dev/pandas/blob/master/pandas/core/window/indexers.py>`__ + +.. versionadded:: 1.1 + +One subclass of note within those examples is the ``VariableOffsetWindowIndexer`` that allows +rolling operations over a non-fixed offset like a ``BusinessDay``. + +.. ipython:: python + + from pandas.api.indexers import VariableOffsetWindowIndexer + + df = pd.DataFrame(range(10), index=pd.date_range("2020", periods=10)) + offset = pd.offsets.BDay(1) + indexer = VariableOffsetWindowIndexer(index=df.index, offset=offset) + df + df.rolling(indexer).sum() + +For some problems knowledge of the future is available for analysis. For example, this occurs when +each data point is a full time series read from an experiment, and the task is to extract underlying +conditions. In these cases it can be useful to perform forward-looking rolling window computations. +:func:`FixedForwardWindowIndexer <pandas.api.indexers.FixedForwardWindowIndexer>` class is available for this purpose. +This :func:`BaseIndexer <pandas.api.indexers.BaseIndexer>` subclass implements a closed fixed-width +forward-looking rolling window, and we can use it as follows: + +.. ipython:: ipython + + from pandas.api.indexers import FixedForwardWindowIndexer + indexer = FixedForwardWindowIndexer(window_size=2) + df.rolling(indexer, min_periods=1).sum() + + +.. _window.rolling_apply: + +Rolling apply +~~~~~~~~~~~~~ + +The :meth:`~Rolling.apply` function takes an extra ``func`` argument and performs +generic rolling computations. The ``func`` argument should be a single function +that produces a single value from an ndarray input. ``raw`` specifies whether +the windows are cast as :class:`Series` objects (``raw=False``) or ndarray objects (``raw=True``). + +.. ipython:: python + + def mad(x): + return np.fabs(x - x.mean()).mean() + + s = pd.Series(range(10)) + s.rolling(window=4).apply(mad, raw=True) + + +.. _window.numba_engine: + +Numba engine +~~~~~~~~~~~~ + +.. versionadded:: 1.0 + +Additionally, :meth:`~Rolling.apply` can leverage `Numba <https://numba.pydata.org/>`__ +if installed as an optional dependency. The apply aggregation can be executed using Numba by specifying +``engine='numba'`` and ``engine_kwargs`` arguments (``raw`` must also be set to ``True``). +Numba will be applied in potentially two routines: + +#. If ``func`` is a standard Python function, the engine will `JIT <https://numba.pydata.org/numba-doc/latest/user/overview.html>`__ the passed function. ``func`` can also be a JITed function in which case the engine will not JIT the function again. +#. The engine will JIT the for loop where the apply function is applied to each window. + +The ``engine_kwargs`` argument is a dictionary of keyword arguments that will be passed into the +`numba.jit decorator <https://numba.pydata.org/numba-doc/latest/reference/jit-compilation.html#numba.jit>`__. +These keyword arguments will be applied to *both* the passed function (if a standard Python function) +and the apply for loop over each window. Currently only ``nogil``, ``nopython``, and ``parallel`` are supported, +and their default values are set to ``False``, ``True`` and ``False`` respectively. + +.. note:: + + In terms of performance, **the first time a function is run using the Numba engine will be slow** + as Numba will have some function compilation overhead. However, the compiled functions are cached, + and subsequent calls will be fast. In general, the Numba engine is performant with + a larger amount of data points (e.g. 1+ million). + +.. code-block:: ipython + + In [1]: data = pd.Series(range(1_000_000)) + + In [2]: roll = data.rolling(10) + + In [3]: def f(x): + ...: return np.sum(x) + 5 + # Run the first time, compilation time will affect performance + In [4]: %timeit -r 1 -n 1 roll.apply(f, engine='numba', raw=True) # noqa: E225, E999 + 1.23 s ± 0 ns per loop (mean ± std. dev. of 1 run, 1 loop each) + # Function is cached and performance will improve + In [5]: %timeit roll.apply(f, engine='numba', raw=True) + 188 ms ± 1.93 ms per loop (mean ± std. dev. of 7 runs, 10 loops each) + + In [6]: %timeit roll.apply(f, engine='cython', raw=True) + 3.92 s ± 59 ms per loop (mean ± std. dev. of 7 runs, 1 loop each) + +.. _window.cov_corr: + +Binary window functions +~~~~~~~~~~~~~~~~~~~~~~~ + +:meth:`~Rolling.cov` and :meth:`~Rolling.corr` can compute moving window statistics about +two :class:`Series` or any combination of :class:`DataFrame`/:class:`Series` or +:class:`DataFrame`/:class:`DataFrame`. Here is the behavior in each case: + +* two :class:`Series`: compute the statistic for the pairing. +* :class:`DataFrame`/:class:`Series`: compute the statistics for each column of the DataFrame + with the passed Series, thus returning a DataFrame. +* :class:`DataFrame`/:class:`DataFrame`: by default compute the statistic for matching column + names, returning a DataFrame. If the keyword argument ``pairwise=True`` is + passed then computes the statistic for each pair of columns, returning a + ``MultiIndexed DataFrame`` whose ``index`` are the dates in question (see :ref:`the next section + <window.corr_pairwise>`). + +For example: + +.. ipython:: python + + df = pd.DataFrame( + np.random.randn(10, 4), + index=pd.date_range("2020-01-01", periods=10), + columns=["A", "B", "C", "D"], + ) + df = df.cumsum() + + df2 = df[:4] + df2.rolling(window=2).corr(df2["B"]) + +.. _window.corr_pairwise: + +Computing rolling pairwise covariances and correlations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In financial data analysis and other fields it's common to compute covariance +and correlation matrices for a collection of time series. Often one is also +interested in moving-window covariance and correlation matrices. This can be +done by passing the ``pairwise`` keyword argument, which in the case of +:class:`DataFrame` inputs will yield a MultiIndexed :class:`DataFrame` whose ``index`` are the dates in +question. In the case of a single DataFrame argument the ``pairwise`` argument +can even be omitted: + +.. note:: + + Missing values are ignored and each entry is computed using the pairwise + complete observations. Please see the :ref:`covariance section + <computation.covariance>` for :ref:`caveats + <computation.covariance.caveats>` associated with this method of + calculating covariance and correlation matrices. + +.. ipython:: python + + covs = ( + df[["B", "C", "D"]] + .rolling(window=4) + .cov(df[["A", "B", "C"]], pairwise=True) + ) + covs + + +.. _window.weighted: + +Weighted window +--------------- + +The ``win_type`` argument in ``.rolling`` generates a weighted windows that are commonly used in filtering +and spectral estimation. ``win_type`` must be string that corresponds to a `scipy.signal window function +<https://docs.scipy.org/doc/scipy/reference/signal.windows.html#module-scipy.signal.windows>`__. +Scipy must be installed in order to use these windows, and supplementary arguments +that the Scipy window methods take must be specified in the aggregation function. + + +.. ipython:: python + + s = pd.Series(range(10)) + s.rolling(window=5).mean() + s.rolling(window=5, win_type="triang").mean() + # Supplementary Scipy arguments passed in the aggregation function + s.rolling(window=5, win_type="gaussian").mean(std=0.1) + +For all supported aggregation functions, see :ref:`api.functions_window`. + +.. _window.expanding: + +Expanding window +---------------- + +An expanding window yields the value of an aggregation statistic with all the data available up to that +point in time. Since these calculations are a special case of rolling statistics, +they are implemented in pandas such that the following two calls are equivalent: + +.. ipython:: python + + df = pd.DataFrame(range(5)) + df.rolling(window=len(df), min_periods=1).mean() + df.expanding(min_periods=1).mean() + +For all supported aggregation functions, see :ref:`api.functions_expanding`. + + +.. _window.exponentially_weighted: + +Exponentially Weighted window +----------------------------- + +An exponentially weighted window is similar to an expanding window but with each prior point +being exponentially weighted down relative to the current point. + +In general, a weighted moving average is calculated as + +.. math:: + + y_t = \frac{\sum_{i=0}^t w_i x_{t-i}}{\sum_{i=0}^t w_i}, + +where :math:`x_t` is the input, :math:`y_t` is the result and the :math:`w_i` +are the weights. + +For all supported aggregation functions, see :ref:`api.functions_ewm`. + +The EW functions support two variants of exponential weights. +The default, ``adjust=True``, uses the weights :math:`w_i = (1 - \alpha)^i` +which gives + +.. math:: + + y_t = \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ... + + (1 - \alpha)^t x_{0}}{1 + (1 - \alpha) + (1 - \alpha)^2 + ... + + (1 - \alpha)^t} + +When ``adjust=False`` is specified, moving averages are calculated as + +.. math:: + + y_0 &= x_0 \\ + y_t &= (1 - \alpha) y_{t-1} + \alpha x_t, + +which is equivalent to using weights + +.. math:: + + w_i = \begin{cases} + \alpha (1 - \alpha)^i & \text{if } i < t \\ + (1 - \alpha)^i & \text{if } i = t. + \end{cases} + +.. note:: + + These equations are sometimes written in terms of :math:`\alpha' = 1 - \alpha`, e.g. + + .. math:: + + y_t = \alpha' y_{t-1} + (1 - \alpha') x_t. + +The difference between the above two variants arises because we are +dealing with series which have finite history. Consider a series of infinite +history, with ``adjust=True``: + +.. math:: + + y_t = \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...} + {1 + (1 - \alpha) + (1 - \alpha)^2 + ...} + +Noting that the denominator is a geometric series with initial term equal to 1 +and a ratio of :math:`1 - \alpha` we have + +.. math:: + + y_t &= \frac{x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...} + {\frac{1}{1 - (1 - \alpha)}}\\ + &= [x_t + (1 - \alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...] \alpha \\ + &= \alpha x_t + [(1-\alpha)x_{t-1} + (1 - \alpha)^2 x_{t-2} + ...]\alpha \\ + &= \alpha x_t + (1 - \alpha)[x_{t-1} + (1 - \alpha) x_{t-2} + ...]\alpha\\ + &= \alpha x_t + (1 - \alpha) y_{t-1} + +which is the same expression as ``adjust=False`` above and therefore +shows the equivalence of the two variants for infinite series. +When ``adjust=False``, we have :math:`y_0 = x_0` and +:math:`y_t = \alpha x_t + (1 - \alpha) y_{t-1}`. +Therefore, there is an assumption that :math:`x_0` is not an ordinary value +but rather an exponentially weighted moment of the infinite series up to that +point. + +One must have :math:`0 < \alpha \leq 1`, and while it is possible to pass +:math:`\alpha` directly, it's often easier to think about either the +**span**, **center of mass (com)** or **half-life** of an EW moment: + +.. math:: + + \alpha = + \begin{cases} + \frac{2}{s + 1}, & \text{for span}\ s \geq 1\\ + \frac{1}{1 + c}, & \text{for center of mass}\ c \geq 0\\ + 1 - \exp^{\frac{\log 0.5}{h}}, & \text{for half-life}\ h > 0 + \end{cases} + +One must specify precisely one of **span**, **center of mass**, **half-life** +and **alpha** to the EW functions: + +* **Span** corresponds to what is commonly called an "N-day EW moving average". +* **Center of mass** has a more physical interpretation and can be thought of + in terms of span: :math:`c = (s - 1) / 2`. +* **Half-life** is the period of time for the exponential weight to reduce to + one half. +* **Alpha** specifies the smoothing factor directly. + +.. versionadded:: 1.1.0 + +You can also specify ``halflife`` in terms of a timedelta convertible unit to specify the amount of +time it takes for an observation to decay to half its value when also specifying a sequence +of ``times``. + +.. ipython:: python + + df = pd.DataFrame({"B": [0, 1, 2, np.nan, 4]}) + df + times = ["2020-01-01", "2020-01-03", "2020-01-10", "2020-01-15", "2020-01-17"] + df.ewm(halflife="4 days", times=pd.DatetimeIndex(times)).mean() + +The following formula is used to compute exponentially weighted mean with an input vector of times: + +.. math:: + + y_t = \frac{\sum_{i=0}^t 0.5^\frac{t_{t} - t_{i}}{\lambda} x_{t-i}}{0.5^\frac{t_{t} - t_{i}}{\lambda}}, + + +ExponentialMovingWindow also has an ``ignore_na`` argument, which determines how +intermediate null values affect the calculation of the weights. +When ``ignore_na=False`` (the default), weights are calculated based on absolute +positions, so that intermediate null values affect the result. +When ``ignore_na=True``, +weights are calculated by ignoring intermediate null values. +For example, assuming ``adjust=True``, if ``ignore_na=False``, the weighted +average of ``3, NaN, 5`` would be calculated as + +.. math:: + + \frac{(1-\alpha)^2 \cdot 3 + 1 \cdot 5}{(1-\alpha)^2 + 1}. + +Whereas if ``ignore_na=True``, the weighted average would be calculated as + +.. math:: + + \frac{(1-\alpha) \cdot 3 + 1 \cdot 5}{(1-\alpha) + 1}. + +The :meth:`~Ewm.var`, :meth:`~Ewm.std`, and :meth:`~Ewm.cov` functions have a ``bias`` argument, +specifying whether the result should contain biased or unbiased statistics. +For example, if ``bias=True``, ``ewmvar(x)`` is calculated as +``ewmvar(x) = ewma(x**2) - ewma(x)**2``; +whereas if ``bias=False`` (the default), the biased variance statistics +are scaled by debiasing factors + +.. math:: + + \frac{\left(\sum_{i=0}^t w_i\right)^2}{\left(\sum_{i=0}^t w_i\right)^2 - \sum_{i=0}^t w_i^2}. + +(For :math:`w_i = 1`, this reduces to the usual :math:`N / (N - 1)` factor, +with :math:`N = t + 1`.) +See `Weighted Sample Variance <https://en.wikipedia.org/wiki/Weighted_arithmetic_mean#Weighted_sample_variance>`__ +on Wikipedia for further details. diff --git a/doc/source/whatsnew/v0.14.0.rst b/doc/source/whatsnew/v0.14.0.rst index f2401c812a979..5b279a4973963 100644 --- a/doc/source/whatsnew/v0.14.0.rst +++ b/doc/source/whatsnew/v0.14.0.rst @@ -171,7 +171,7 @@ API changes ``expanding_cov``, ``expanding_corr`` to allow the calculation of moving window covariance and correlation matrices (:issue:`4950`). See :ref:`Computing rolling pairwise covariances and correlations - <stats.moments.corr_pairwise>` in the docs. + <window.corr_pairwise>` in the docs. .. code-block:: ipython diff --git a/doc/source/whatsnew/v0.15.0.rst b/doc/source/whatsnew/v0.15.0.rst index 1f054930b3709..fc2b070df4392 100644 --- a/doc/source/whatsnew/v0.15.0.rst +++ b/doc/source/whatsnew/v0.15.0.rst @@ -405,7 +405,7 @@ Rolling/expanding moments improvements - :func:`rolling_window` now normalizes the weights properly in rolling mean mode (`mean=True`) so that the calculated weighted means (e.g. 'triang', 'gaussian') are distributed about the same means as those - calculated without weighting (i.e. 'boxcar'). See :ref:`the note on normalization <stats.moments.normalization>` for further details. (:issue:`7618`) + calculated without weighting (i.e. 'boxcar'). See :ref:`the note on normalization <window.weighted>` for further details. (:issue:`7618`) .. ipython:: python @@ -490,7 +490,7 @@ Rolling/expanding moments improvements now have an optional ``adjust`` argument, just like :func:`ewma` does, affecting how the weights are calculated. The default value of ``adjust`` is ``True``, which is backwards-compatible. - See :ref:`Exponentially weighted moment functions <stats.moments.exponentially_weighted>` for details. (:issue:`7911`) + See :ref:`Exponentially weighted moment functions <window.exponentially_weighted>` for details. (:issue:`7911`) - :func:`ewma`, :func:`ewmstd`, :func:`ewmvol`, :func:`ewmvar`, :func:`ewmcov`, and :func:`ewmcorr` now have an optional ``ignore_na`` argument. @@ -595,7 +595,7 @@ Rolling/expanding moments improvements 3 1.425439 dtype: float64 - See :ref:`Exponentially weighted moment functions <stats.moments.exponentially_weighted>` for details. (:issue:`7912`) + See :ref:`Exponentially weighted moment functions <window.exponentially_weighted>` for details. (:issue:`7912`) .. _whatsnew_0150.sql: diff --git a/doc/source/whatsnew/v0.18.0.rst b/doc/source/whatsnew/v0.18.0.rst index ef5242b0e33c8..636414cdab8d8 100644 --- a/doc/source/whatsnew/v0.18.0.rst +++ b/doc/source/whatsnew/v0.18.0.rst @@ -53,7 +53,7 @@ New features Window functions are now methods ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Window functions have been refactored to be methods on ``Series/DataFrame`` objects, rather than top-level functions, which are now deprecated. This allows these window-type functions, to have a similar API to that of ``.groupby``. See the full documentation :ref:`here <stats.moments>` (:issue:`11603`, :issue:`12373`) +Window functions have been refactored to be methods on ``Series/DataFrame`` objects, rather than top-level functions, which are now deprecated. This allows these window-type functions, to have a similar API to that of ``.groupby``. See the full documentation :ref:`here <window.overview>` (:issue:`11603`, :issue:`12373`) .. ipython:: python diff --git a/doc/source/whatsnew/v0.19.0.rst b/doc/source/whatsnew/v0.19.0.rst index 2ac7b0f54361b..340e1ce9ee1ef 100644 --- a/doc/source/whatsnew/v0.19.0.rst +++ b/doc/source/whatsnew/v0.19.0.rst @@ -135,7 +135,7 @@ Method ``.rolling()`` is now time-series aware ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ``.rolling()`` objects are now time-series aware and can accept a time-series offset (or convertible) for the ``window`` argument (:issue:`13327`, :issue:`12995`). -See the full documentation :ref:`here <stats.moments.ts>`. +See the full documentation :ref:`here <window.generic>`. .. ipython:: python diff --git a/doc/source/whatsnew/v0.20.0.rst b/doc/source/whatsnew/v0.20.0.rst index a9e57f0039735..8ae5ea5726fe9 100644 --- a/doc/source/whatsnew/v0.20.0.rst +++ b/doc/source/whatsnew/v0.20.0.rst @@ -459,7 +459,7 @@ Selecting via a scalar value that is contained *in* the intervals. Other enhancements ^^^^^^^^^^^^^^^^^^ -- ``DataFrame.rolling()`` now accepts the parameter ``closed='right'|'left'|'both'|'neither'`` to choose the rolling window-endpoint closedness. See the :ref:`documentation <stats.rolling_window.endpoints>` (:issue:`13965`) +- ``DataFrame.rolling()`` now accepts the parameter ``closed='right'|'left'|'both'|'neither'`` to choose the rolling window-endpoint closedness. See the :ref:`documentation <window.endpoints>` (:issue:`13965`) - Integration with the ``feather-format``, including a new top-level ``pd.read_feather()`` and ``DataFrame.to_feather()`` method, see :ref:`here <io.feather>`. - ``Series.str.replace()`` now accepts a callable, as replacement, which is passed to ``re.sub`` (:issue:`15055`) - ``Series.str.replace()`` now accepts a compiled regular expression as a pattern (:issue:`15446`) @@ -988,7 +988,7 @@ A binary window operation, like ``.corr()`` or ``.cov()``, when operating on a ` will now return a 2-level ``MultiIndexed DataFrame`` rather than a ``Panel``, as ``Panel`` is now deprecated, see :ref:`here <whatsnew_0200.api_breaking.deprecate_panel>`. These are equivalent in function, but a MultiIndexed ``DataFrame`` enjoys more support in pandas. -See the section on :ref:`Windowed Binary Operations <stats.moments.binary>` for more information. (:issue:`15677`) +See the section on :ref:`Windowed Binary Operations <window.cov_corr>` for more information. (:issue:`15677`) .. ipython:: python diff --git a/doc/source/whatsnew/v0.6.1.rst b/doc/source/whatsnew/v0.6.1.rst index 8ee80fa2c44b1..139c6e2d1cb0c 100644 --- a/doc/source/whatsnew/v0.6.1.rst +++ b/doc/source/whatsnew/v0.6.1.rst @@ -25,12 +25,12 @@ New features constructor (:issue:`444`) - DataFrame.convert_objects method for :ref:`inferring better dtypes <basics.cast>` for object columns (:issue:`302`) -- Add :ref:`rolling_corr_pairwise <stats.moments.corr_pairwise>` function for +- Add :ref:`rolling_corr_pairwise <window.corr_pairwise>` function for computing Panel of correlation matrices (:issue:`189`) - Add :ref:`margins <reshaping.pivot.margins>` option to :ref:`pivot_table <reshaping.pivot>` for computing subgroup aggregates (:issue:`114`) - Add ``Series.from_csv`` function (:issue:`482`) -- :ref:`Can pass <stats.moments.binary>` DataFrame/DataFrame and +- :ref:`Can pass <window.cov_corr>` DataFrame/DataFrame and DataFrame/Series to rolling_corr/rolling_cov (GH #462) - MultiIndex.get_level_values can :ref:`accept the level name <advanced.get_level_values>` diff --git a/doc/source/whatsnew/v1.0.0.rst b/doc/source/whatsnew/v1.0.0.rst index 8f9ceb30a947a..6512e4cce02a9 100755 --- a/doc/source/whatsnew/v1.0.0.rst +++ b/doc/source/whatsnew/v1.0.0.rst @@ -46,7 +46,7 @@ We've added an ``engine`` keyword to :meth:`~core.window.rolling.Rolling.apply` that allows the user to execute the routine using `Numba <https://numba.pydata.org/>`__ instead of Cython. Using the Numba engine can yield significant performance gains if the apply function can operate on numpy arrays and the data set is larger (1 million rows or greater). For more details, see -:ref:`rolling apply documentation <stats.rolling_apply>` (:issue:`28987`, :issue:`30936`) +:ref:`rolling apply documentation <window.numba_engine>` (:issue:`28987`, :issue:`30936`) .. _whatsnew_100.custom_window: @@ -57,7 +57,7 @@ We've added a :func:`pandas.api.indexers.BaseIndexer` class that allows users to window bounds are created during ``rolling`` operations. Users can define their own ``get_window_bounds`` method on a :func:`pandas.api.indexers.BaseIndexer` subclass that will generate the start and end indices used for each window during the rolling aggregation. For more details and example usage, see -the :ref:`custom window rolling documentation <stats.custom_rolling_window>` +the :ref:`custom window rolling documentation <window.custom_rolling_window>` .. _whatsnew_100.to_markdown: diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index 9f7040943d9a3..b601bacec35f1 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -172,7 +172,7 @@ class ExponentialMovingWindow(BaseWindow): ----- More details can be found at: - :ref:`Exponentially weighted windows <stats.moments.exponentially_weighted>`. + :ref:`Exponentially weighted windows <window.exponentially_weighted>`. Examples -------- diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index 5d561c84ab462..f65452cb2f17f 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -1270,7 +1270,7 @@ def count(self): Notes ----- - See :ref:`stats.rolling_apply` for extended documentation and performance + See :ref:`window.numba_engine` for extended documentation and performance considerations for the Numba engine. """ )
Adding a dedicated `user_guide/windows.rst` for `rolling/expanding/ewm` operations. Mainly ported over from `computation.rst`.
https://api.github.com/repos/pandas-dev/pandas/pulls/37575
2020-11-02T04:30:53Z
2020-11-14T16:56:36Z
2020-11-14T16:56:36Z
2020-11-14T21:16:14Z
TST/REF: collect tests by method
diff --git a/pandas/tests/frame/methods/test_swapaxes.py b/pandas/tests/frame/methods/test_swapaxes.py new file mode 100644 index 0000000000000..306f7b2b21cda --- /dev/null +++ b/pandas/tests/frame/methods/test_swapaxes.py @@ -0,0 +1,22 @@ +import numpy as np +import pytest + +from pandas import DataFrame +import pandas._testing as tm + + +class TestSwapAxes: + def test_swapaxes(self): + df = DataFrame(np.random.randn(10, 5)) + tm.assert_frame_equal(df.T, df.swapaxes(0, 1)) + tm.assert_frame_equal(df.T, df.swapaxes(1, 0)) + + def test_swapaxes_noop(self): + df = DataFrame(np.random.randn(10, 5)) + tm.assert_frame_equal(df, df.swapaxes(0, 0)) + + def test_swapaxes_invalid_axis(self): + df = DataFrame(np.random.randn(10, 5)) + msg = "No axis named 2 for object type DataFrame" + with pytest.raises(ValueError, match=msg): + df.swapaxes(2, 5) diff --git a/pandas/tests/frame/test_add_prefix_suffix.py b/pandas/tests/frame/test_add_prefix_suffix.py new file mode 100644 index 0000000000000..ea75e9ff51552 --- /dev/null +++ b/pandas/tests/frame/test_add_prefix_suffix.py @@ -0,0 +1,20 @@ +from pandas import Index +import pandas._testing as tm + + +def test_add_prefix_suffix(float_frame): + with_prefix = float_frame.add_prefix("foo#") + expected = Index([f"foo#{c}" for c in float_frame.columns]) + tm.assert_index_equal(with_prefix.columns, expected) + + with_suffix = float_frame.add_suffix("#foo") + expected = Index([f"{c}#foo" for c in float_frame.columns]) + tm.assert_index_equal(with_suffix.columns, expected) + + with_pct_prefix = float_frame.add_prefix("%") + expected = Index([f"%{c}" for c in float_frame.columns]) + tm.assert_index_equal(with_pct_prefix.columns, expected) + + with_pct_suffix = float_frame.add_suffix("%") + expected = Index([f"{c}%" for c in float_frame.columns]) + tm.assert_index_equal(with_pct_suffix.columns, expected) diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index 68a004d8fbccb..25d3fab76ca36 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -1,5 +1,4 @@ from copy import deepcopy -import datetime import inspect import pydoc import warnings @@ -7,12 +6,11 @@ import numpy as np import pytest -from pandas.compat import IS64, is_platform_windows import pandas.util._test_decorators as td from pandas.util._test_decorators import async_mark, skip_if_no import pandas as pd -from pandas import Categorical, DataFrame, Series, date_range, timedelta_range +from pandas import DataFrame, Series, date_range, timedelta_range import pandas._testing as tm @@ -30,23 +28,6 @@ def test_getitem_pop_assign_name(self, float_frame): s2 = s.loc[:] assert s2.name == "B" - def test_add_prefix_suffix(self, float_frame): - with_prefix = float_frame.add_prefix("foo#") - expected = pd.Index([f"foo#{c}" for c in float_frame.columns]) - tm.assert_index_equal(with_prefix.columns, expected) - - with_suffix = float_frame.add_suffix("#foo") - expected = pd.Index([f"{c}#foo" for c in float_frame.columns]) - tm.assert_index_equal(with_suffix.columns, expected) - - with_pct_prefix = float_frame.add_prefix("%") - expected = pd.Index([f"%{c}" for c in float_frame.columns]) - tm.assert_index_equal(with_pct_prefix.columns, expected) - - with_pct_suffix = float_frame.add_suffix("%") - expected = pd.Index([f"{c}%" for c in float_frame.columns]) - tm.assert_index_equal(with_pct_suffix.columns, expected) - def test_get_axis(self, float_frame): f = float_frame assert f._get_axis_number(0) == 0 @@ -76,9 +57,6 @@ def test_get_axis(self, float_frame): with pytest.raises(ValueError, match="No axis named"): f._get_axis_number(None) - def test_keys(self, float_frame): - assert float_frame.keys() is float_frame.columns - def test_column_contains_raises(self, float_frame): with pytest.raises(TypeError, match="unhashable type: 'Index'"): float_frame.columns in float_frame @@ -149,143 +127,6 @@ def test_empty(self, float_frame, float_string_frame): del df["A"] assert not df.empty - def test_iteritems(self): - df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"]) - for k, v in df.items(): - assert isinstance(v, DataFrame._constructor_sliced) - - def test_items(self): - # GH 17213, GH 13918 - cols = ["a", "b", "c"] - df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=cols) - for c, (k, v) in zip(cols, df.items()): - assert c == k - assert isinstance(v, Series) - assert (df[k] == v).all() - - def test_iter(self, float_frame): - assert tm.equalContents(list(float_frame), float_frame.columns) - - def test_iterrows(self, float_frame, float_string_frame): - for k, v in float_frame.iterrows(): - exp = float_frame.loc[k] - tm.assert_series_equal(v, exp) - - for k, v in float_string_frame.iterrows(): - exp = float_string_frame.loc[k] - tm.assert_series_equal(v, exp) - - def test_iterrows_iso8601(self): - # GH 19671 - s = DataFrame( - { - "non_iso8601": ["M1701", "M1802", "M1903", "M2004"], - "iso8601": date_range("2000-01-01", periods=4, freq="M"), - } - ) - for k, v in s.iterrows(): - exp = s.loc[k] - tm.assert_series_equal(v, exp) - - def test_iterrows_corner(self): - # gh-12222 - df = DataFrame( - { - "a": [datetime.datetime(2015, 1, 1)], - "b": [None], - "c": [None], - "d": [""], - "e": [[]], - "f": [set()], - "g": [{}], - } - ) - expected = Series( - [datetime.datetime(2015, 1, 1), None, None, "", [], set(), {}], - index=list("abcdefg"), - name=0, - dtype="object", - ) - _, result = next(df.iterrows()) - tm.assert_series_equal(result, expected) - - def test_itertuples(self, float_frame): - for i, tup in enumerate(float_frame.itertuples()): - s = DataFrame._constructor_sliced(tup[1:]) - s.name = tup[0] - expected = float_frame.iloc[i, :].reset_index(drop=True) - tm.assert_series_equal(s, expected) - - df = DataFrame( - {"floats": np.random.randn(5), "ints": range(5)}, columns=["floats", "ints"] - ) - - for tup in df.itertuples(index=False): - assert isinstance(tup[1], int) - - df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]}) - dfaa = df[["a", "a"]] - - assert list(dfaa.itertuples()) == [(0, 1, 1), (1, 2, 2), (2, 3, 3)] - - # repr with int on 32-bit/windows - if not (is_platform_windows() or not IS64): - assert ( - repr(list(df.itertuples(name=None))) - == "[(0, 1, 4), (1, 2, 5), (2, 3, 6)]" - ) - - tup = next(df.itertuples(name="TestName")) - assert tup._fields == ("Index", "a", "b") - assert (tup.Index, tup.a, tup.b) == tup - assert type(tup).__name__ == "TestName" - - df.columns = ["def", "return"] - tup2 = next(df.itertuples(name="TestName")) - assert tup2 == (0, 1, 4) - assert tup2._fields == ("Index", "_1", "_2") - - df3 = DataFrame({"f" + str(i): [i] for i in range(1024)}) - # will raise SyntaxError if trying to create namedtuple - tup3 = next(df3.itertuples()) - assert isinstance(tup3, tuple) - assert hasattr(tup3, "_fields") - - # GH 28282 - df_254_columns = DataFrame([{f"foo_{i}": f"bar_{i}" for i in range(254)}]) - result_254_columns = next(df_254_columns.itertuples(index=False)) - assert isinstance(result_254_columns, tuple) - assert hasattr(result_254_columns, "_fields") - - df_255_columns = DataFrame([{f"foo_{i}": f"bar_{i}" for i in range(255)}]) - result_255_columns = next(df_255_columns.itertuples(index=False)) - assert isinstance(result_255_columns, tuple) - assert hasattr(result_255_columns, "_fields") - - def test_sequence_like_with_categorical(self): - - # GH 7839 - # make sure can iterate - df = DataFrame( - {"id": [1, 2, 3, 4, 5, 6], "raw_grade": ["a", "b", "b", "a", "a", "e"]} - ) - df["grade"] = Categorical(df["raw_grade"]) - - # basic sequencing testing - result = list(df.grade.values) - expected = np.array(df.grade.values).tolist() - tm.assert_almost_equal(result, expected) - - # iteration - for t in df.itertuples(index=False): - str(t) - - for row, s in df.iterrows(): - str(s) - - for c, col in df.items(): - str(s) - def test_len(self, float_frame): assert len(float_frame) == len(float_frame.index) @@ -294,15 +135,6 @@ def test_len(self, float_frame): expected = float_frame.reindex(columns=["A", "B"]).values tm.assert_almost_equal(arr, expected) - def test_swapaxes(self): - df = DataFrame(np.random.randn(10, 5)) - tm.assert_frame_equal(df.T, df.swapaxes(0, 1)) - tm.assert_frame_equal(df.T, df.swapaxes(1, 0)) - tm.assert_frame_equal(df, df.swapaxes(0, 0)) - msg = "No axis named 2 for object type DataFrame" - with pytest.raises(ValueError, match=msg): - df.swapaxes(2, 5) - def test_axis_aliases(self, float_frame): f = float_frame @@ -321,10 +153,6 @@ def test_class_axis(self): assert pydoc.getdoc(DataFrame.index) assert pydoc.getdoc(DataFrame.columns) - def test_items_names(self, float_string_frame): - for k, v in float_string_frame.items(): - assert v.name == k - def test_series_put_names(self, float_string_frame): series = float_string_frame._series for k, v in series.items(): diff --git a/pandas/tests/frame/test_iteration.py b/pandas/tests/frame/test_iteration.py new file mode 100644 index 0000000000000..d6268f90b2681 --- /dev/null +++ b/pandas/tests/frame/test_iteration.py @@ -0,0 +1,154 @@ +import datetime + +import numpy as np + +from pandas.compat import IS64, is_platform_windows + +from pandas import Categorical, DataFrame, Series, date_range +import pandas._testing as tm + + +class TestIteration: + def test_keys(self, float_frame): + assert float_frame.keys() is float_frame.columns + + def test_iteritems(self): + df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=["a", "a", "b"]) + for k, v in df.items(): + assert isinstance(v, DataFrame._constructor_sliced) + + def test_items(self): + # GH#17213, GH#13918 + cols = ["a", "b", "c"] + df = DataFrame([[1, 2, 3], [4, 5, 6]], columns=cols) + for c, (k, v) in zip(cols, df.items()): + assert c == k + assert isinstance(v, Series) + assert (df[k] == v).all() + + def test_items_names(self, float_string_frame): + for k, v in float_string_frame.items(): + assert v.name == k + + def test_iter(self, float_frame): + assert tm.equalContents(list(float_frame), float_frame.columns) + + def test_iterrows(self, float_frame, float_string_frame): + for k, v in float_frame.iterrows(): + exp = float_frame.loc[k] + tm.assert_series_equal(v, exp) + + for k, v in float_string_frame.iterrows(): + exp = float_string_frame.loc[k] + tm.assert_series_equal(v, exp) + + def test_iterrows_iso8601(self): + # GH#19671 + s = DataFrame( + { + "non_iso8601": ["M1701", "M1802", "M1903", "M2004"], + "iso8601": date_range("2000-01-01", periods=4, freq="M"), + } + ) + for k, v in s.iterrows(): + exp = s.loc[k] + tm.assert_series_equal(v, exp) + + def test_iterrows_corner(self): + # GH#12222 + df = DataFrame( + { + "a": [datetime.datetime(2015, 1, 1)], + "b": [None], + "c": [None], + "d": [""], + "e": [[]], + "f": [set()], + "g": [{}], + } + ) + expected = Series( + [datetime.datetime(2015, 1, 1), None, None, "", [], set(), {}], + index=list("abcdefg"), + name=0, + dtype="object", + ) + _, result = next(df.iterrows()) + tm.assert_series_equal(result, expected) + + def test_itertuples(self, float_frame): + for i, tup in enumerate(float_frame.itertuples()): + ser = DataFrame._constructor_sliced(tup[1:]) + ser.name = tup[0] + expected = float_frame.iloc[i, :].reset_index(drop=True) + tm.assert_series_equal(ser, expected) + + df = DataFrame( + {"floats": np.random.randn(5), "ints": range(5)}, columns=["floats", "ints"] + ) + + for tup in df.itertuples(index=False): + assert isinstance(tup[1], int) + + df = DataFrame(data={"a": [1, 2, 3], "b": [4, 5, 6]}) + dfaa = df[["a", "a"]] + + assert list(dfaa.itertuples()) == [(0, 1, 1), (1, 2, 2), (2, 3, 3)] + + # repr with int on 32-bit/windows + if not (is_platform_windows() or not IS64): + assert ( + repr(list(df.itertuples(name=None))) + == "[(0, 1, 4), (1, 2, 5), (2, 3, 6)]" + ) + + tup = next(df.itertuples(name="TestName")) + assert tup._fields == ("Index", "a", "b") + assert (tup.Index, tup.a, tup.b) == tup + assert type(tup).__name__ == "TestName" + + df.columns = ["def", "return"] + tup2 = next(df.itertuples(name="TestName")) + assert tup2 == (0, 1, 4) + assert tup2._fields == ("Index", "_1", "_2") + + df3 = DataFrame({"f" + str(i): [i] for i in range(1024)}) + # will raise SyntaxError if trying to create namedtuple + tup3 = next(df3.itertuples()) + assert isinstance(tup3, tuple) + assert hasattr(tup3, "_fields") + + # GH#28282 + df_254_columns = DataFrame([{f"foo_{i}": f"bar_{i}" for i in range(254)}]) + result_254_columns = next(df_254_columns.itertuples(index=False)) + assert isinstance(result_254_columns, tuple) + assert hasattr(result_254_columns, "_fields") + + df_255_columns = DataFrame([{f"foo_{i}": f"bar_{i}" for i in range(255)}]) + result_255_columns = next(df_255_columns.itertuples(index=False)) + assert isinstance(result_255_columns, tuple) + assert hasattr(result_255_columns, "_fields") + + def test_sequence_like_with_categorical(self): + + # GH#7839 + # make sure can iterate + df = DataFrame( + {"id": [1, 2, 3, 4, 5, 6], "raw_grade": ["a", "b", "b", "a", "a", "e"]} + ) + df["grade"] = Categorical(df["raw_grade"]) + + # basic sequencing testing + result = list(df.grade.values) + expected = np.array(df.grade.values).tolist() + tm.assert_almost_equal(result, expected) + + # iteration + for t in df.itertuples(index=False): + str(t) + + for row, s in df.iterrows(): + str(s) + + for c, col in df.items(): + str(s) diff --git a/pandas/tests/io/test_pickle.py b/pandas/tests/io/test_pickle.py index 890146f0789ae..925f6b5f125c7 100644 --- a/pandas/tests/io/test_pickle.py +++ b/pandas/tests/io/test_pickle.py @@ -563,11 +563,16 @@ def test_pickle_timeseries_periodindex(): "name", [777, 777.0, "name", datetime.datetime(2001, 11, 11), (1, 2)] ) def test_pickle_preserve_name(name): - def _pickle_roundtrip_name(obj): - with tm.ensure_clean() as path: - obj.to_pickle(path) - unpickled = pd.read_pickle(path) - return unpickled - unpickled = _pickle_roundtrip_name(tm.makeTimeSeries(name=name)) + unpickled = tm.round_trip_pickle(tm.makeTimeSeries(name=name)) assert unpickled.name == name + + +def test_pickle_datetimes(datetime_series): + unp_ts = tm.round_trip_pickle(datetime_series) + tm.assert_series_equal(unp_ts, datetime_series) + + +def test_pickle_strings(string_series): + unp_series = tm.round_trip_pickle(string_series) + tm.assert_series_equal(unp_series, string_series) diff --git a/pandas/tests/series/test_api.py b/pandas/tests/series/test_api.py index 5dbee5cc0567b..717d8b5c90d85 100644 --- a/pandas/tests/series/test_api.py +++ b/pandas/tests/series/test_api.py @@ -22,21 +22,6 @@ def test_getitem_preserve_name(self, datetime_series): result = datetime_series[5:10] assert result.name == datetime_series.name - def test_pickle_datetimes(self, datetime_series): - unp_ts = self._pickle_roundtrip(datetime_series) - tm.assert_series_equal(unp_ts, datetime_series) - - def test_pickle_strings(self, string_series): - unp_series = self._pickle_roundtrip(string_series) - tm.assert_series_equal(unp_series, string_series) - - def _pickle_roundtrip(self, obj): - - with tm.ensure_clean() as path: - obj.to_pickle(path) - unpickled = pd.read_pickle(path) - return unpickled - def test_tab_completion(self): # GH 9910 s = Series(list("abcd")) @@ -130,44 +115,11 @@ def test_not_hashable(self): def test_contains(self, datetime_series): tm.assert_contains_all(datetime_series.index, datetime_series) - def test_iter_datetimes(self, datetime_series): - for i, val in enumerate(datetime_series): - assert val == datetime_series[i] - - def test_iter_strings(self, string_series): - for i, val in enumerate(string_series): - assert val == string_series[i] - - def test_keys(self, datetime_series): - assert datetime_series.keys() is datetime_series.index - def test_values(self, datetime_series): tm.assert_almost_equal( datetime_series.values, datetime_series, check_dtype=False ) - def test_iteritems_datetimes(self, datetime_series): - for idx, val in datetime_series.iteritems(): - assert val == datetime_series[idx] - - def test_iteritems_strings(self, string_series): - for idx, val in string_series.iteritems(): - assert val == string_series[idx] - - # assert is lazy (generators don't define reverse, lists do) - assert not hasattr(string_series.iteritems(), "reverse") - - def test_items_datetimes(self, datetime_series): - for idx, val in datetime_series.items(): - assert val == datetime_series[idx] - - def test_items_strings(self, string_series): - for idx, val in string_series.items(): - assert val == string_series[idx] - - # assert is lazy (generators don't define reverse, lists do) - assert not hasattr(string_series.items(), "reverse") - def test_raise_on_info(self): s = Series(np.random.randn(10)) msg = "'Series' object has no attribute 'info'" diff --git a/pandas/tests/series/test_iteration.py b/pandas/tests/series/test_iteration.py new file mode 100644 index 0000000000000..dc9fe9e3bdd34 --- /dev/null +++ b/pandas/tests/series/test_iteration.py @@ -0,0 +1,33 @@ +class TestIteration: + def test_keys(self, datetime_series): + assert datetime_series.keys() is datetime_series.index + + def test_iter_datetimes(self, datetime_series): + for i, val in enumerate(datetime_series): + assert val == datetime_series[i] + + def test_iter_strings(self, string_series): + for i, val in enumerate(string_series): + assert val == string_series[i] + + def test_iteritems_datetimes(self, datetime_series): + for idx, val in datetime_series.iteritems(): + assert val == datetime_series[idx] + + def test_iteritems_strings(self, string_series): + for idx, val in string_series.iteritems(): + assert val == string_series[idx] + + # assert is lazy (generators don't define reverse, lists do) + assert not hasattr(string_series.iteritems(), "reverse") + + def test_items_datetimes(self, datetime_series): + for idx, val in datetime_series.items(): + assert val == datetime_series[idx] + + def test_items_strings(self, string_series): + for idx, val in string_series.items(): + assert val == string_series[idx] + + # assert is lazy (generators don't define reverse, lists do) + assert not hasattr(string_series.items(), "reverse")
This is something of an outlier in that it collects iter/iteritems/iterrows/itertuples into a test_iteration file. I think this is a sufficiently clear grouping, akin to test_arithmetic/test_reductions/test_unary, LMK if you disagree.
https://api.github.com/repos/pandas-dev/pandas/pulls/37573
2020-11-02T00:07:52Z
2020-11-02T13:39:08Z
2020-11-02T13:39:08Z
2020-11-02T14:29:53Z
BUG: to_dict should return a native datetime object for NumPy backed dataframes
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 9ac3585aa9002..6733a118165ff 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -435,7 +435,7 @@ Numeric Conversion ^^^^^^^^^^ -- +- Bug in :meth:`DataFrame.to_dict` with ``orient='records'`` now returns python native datetime objects for datetimelike columns (:issue:`21256`) - Strings diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 5f4cd4b269a2a..9152ce72d75aa 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -22,6 +22,7 @@ construct_1d_arraylike_from_scalar, find_common_type, infer_dtype_from_scalar, + maybe_box_datetimelike, ) from pandas.core.dtypes.common import ( is_array_like, @@ -805,7 +806,7 @@ def _get_val_at(self, loc): return self.fill_value else: val = self.sp_values[sp_loc] - val = com.maybe_box_datetimelike(val, self.sp_values.dtype) + val = maybe_box_datetimelike(val, self.sp_values.dtype) return val def take(self, indices, allow_fill=False, fill_value=None) -> "SparseArray": diff --git a/pandas/core/common.py b/pandas/core/common.py index b860c83f89cbc..9b6133d2f7627 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -6,7 +6,6 @@ from collections import abc, defaultdict import contextlib -from datetime import datetime, timedelta from functools import partial import inspect from typing import Any, Collection, Iterable, Iterator, List, Union, cast @@ -14,7 +13,7 @@ import numpy as np -from pandas._libs import lib, tslibs +from pandas._libs import lib from pandas._typing import AnyArrayLike, Scalar, T from pandas.compat.numpy import np_version_under1p18 @@ -78,21 +77,6 @@ def consensus_name_attr(objs): return name -def maybe_box_datetimelike(value, dtype=None): - # turn a datetime like into a Timestamp/timedelta as needed - if dtype == object: - # If we dont have datetime64/timedelta64 dtype, we dont want to - # box datetimelike scalars - return value - - if isinstance(value, (np.datetime64, datetime)): - value = tslibs.Timestamp(value) - elif isinstance(value, (np.timedelta64, timedelta)): - value = tslibs.Timedelta(value) - - return value - - def is_bool_indexer(key: Any) -> bool: """ Check whether `key` is a valid boolean indexer. @@ -347,23 +331,6 @@ def apply_if_callable(maybe_callable, obj, **kwargs): return maybe_callable -def dict_compat(d): - """ - Helper function to convert datetimelike-keyed dicts - to Timestamp-keyed dict. - - Parameters - ---------- - d: dict like object - - Returns - ------- - dict - - """ - return {maybe_box_datetimelike(key): value for key, value in d.items()} - - def standardize_mapping(into): """ Helper function to standardize a supplied mapping. diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index aded0af6aca0e..9758eae60c262 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -7,6 +7,7 @@ from typing import ( TYPE_CHECKING, Any, + Dict, List, Optional, Sequence, @@ -19,7 +20,7 @@ import numpy as np -from pandas._libs import lib, tslib +from pandas._libs import lib, tslib, tslibs from pandas._libs.tslibs import ( NaT, OutOfBoundsDatetime, @@ -134,6 +135,30 @@ def is_nested_object(obj) -> bool: return False +def maybe_box_datetimelike(value: Scalar, dtype: Optional[Dtype] = None) -> Scalar: + """ + Cast scalar to Timestamp or Timedelta if scalar is datetime-like + and dtype is not object. + + Parameters + ---------- + value : scalar + dtype : Dtype, optional + + Returns + ------- + scalar + """ + if dtype == object: + pass + elif isinstance(value, (np.datetime64, datetime)): + value = tslibs.Timestamp(value) + elif isinstance(value, (np.timedelta64, timedelta)): + value = tslibs.Timedelta(value) + + return value + + def maybe_downcast_to_dtype(result, dtype: Union[str, np.dtype]): """ try to cast to the specified dtype (e.g. convert back to bool/int @@ -791,6 +816,22 @@ def infer_dtype_from_scalar(val, pandas_dtype: bool = False) -> Tuple[DtypeObj, return dtype, val +def dict_compat(d: Dict[Scalar, Scalar]) -> Dict[Scalar, Scalar]: + """ + Convert datetimelike-keyed dicts to a Timestamp-keyed dict. + + Parameters + ---------- + d: dict-like object + + Returns + ------- + dict + + """ + return {maybe_box_datetimelike(key): value for key, value in d.items()} + + def infer_dtype_from_array( arr, pandas_dtype: bool = False ) -> Tuple[DtypeObj, ArrayLike]: diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 3ec575a849abe..9d223ba2bab0c 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -84,6 +84,7 @@ find_common_type, infer_dtype_from_scalar, invalidate_string_dtypes, + maybe_box_datetimelike, maybe_cast_to_datetime, maybe_casted_values, maybe_convert_platform, @@ -1538,7 +1539,7 @@ def to_dict(self, orient="dict", into=dict): ( "data", [ - list(map(com.maybe_box_datetimelike, t)) + list(map(maybe_box_datetimelike, t)) for t in self.itertuples(index=False, name=None) ], ), @@ -1546,7 +1547,7 @@ def to_dict(self, orient="dict", into=dict): ) elif orient == "series": - return into_c((k, com.maybe_box_datetimelike(v)) for k, v in self.items()) + return into_c((k, maybe_box_datetimelike(v)) for k, v in self.items()) elif orient == "records": columns = self.columns.tolist() @@ -1555,7 +1556,7 @@ def to_dict(self, orient="dict", into=dict): for row in self.itertuples(index=False, name=None) ) return [ - into_c((k, com.maybe_box_datetimelike(v)) for k, v in row.items()) + into_c((k, maybe_box_datetimelike(v)) for k, v in row.items()) for row in rows ] diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 2061e652a4c01..c700acc24f411 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -19,6 +19,7 @@ from pandas.core.dtypes.cast import ( find_common_type, infer_dtype_from_scalar, + maybe_box_datetimelike, maybe_downcast_to_dtype, ) from pandas.core.dtypes.common import ( @@ -1193,8 +1194,8 @@ def interval_range( IntervalIndex([[1, 2], [2, 3], [3, 4], [4, 5]], closed='both', dtype='interval[int64]') """ - start = com.maybe_box_datetimelike(start) - end = com.maybe_box_datetimelike(end) + start = maybe_box_datetimelike(start) + end = maybe_box_datetimelike(end) endpoint = start if start is not None else end if freq is None and com.any_none(periods, start, end): diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index ee630909cb990..1f34e91d71077 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -19,6 +19,7 @@ find_common_type, infer_dtype_from, infer_dtype_from_scalar, + maybe_box_datetimelike, maybe_downcast_numeric, maybe_downcast_to_dtype, maybe_infer_dtype_type, @@ -843,7 +844,7 @@ def comp(s: Scalar, mask: np.ndarray, regex: bool = False) -> np.ndarray: if isna(s): return ~mask - s = com.maybe_box_datetimelike(s) + s = maybe_box_datetimelike(s) return compare_or_regex_search(self.values, s, regex, mask) # Calculate the mask once, prior to the call of comp diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index bb8283604abb0..bcafa2c2fdca7 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -14,6 +14,7 @@ from pandas.core.dtypes.cast import ( construct_1d_arraylike_from_scalar, construct_1d_ndarray_preserving_na, + dict_compat, maybe_cast_to_datetime, maybe_convert_platform, maybe_infer_to_datetimelike, @@ -346,7 +347,7 @@ def _homogenize(data, index, dtype: Optional[DtypeObj]): oindex = index.astype("O") if isinstance(index, (ABCDatetimeIndex, ABCTimedeltaIndex)): - val = com.dict_compat(val) + val = dict_compat(val) else: val = dict(val) val = lib.fast_multiget(val, oindex._values, default=np.nan) diff --git a/pandas/tests/dtypes/cast/test_dict_compat.py b/pandas/tests/dtypes/cast/test_dict_compat.py new file mode 100644 index 0000000000000..13dc82d779f95 --- /dev/null +++ b/pandas/tests/dtypes/cast/test_dict_compat.py @@ -0,0 +1,14 @@ +import numpy as np + +from pandas.core.dtypes.cast import dict_compat + +from pandas import Timestamp + + +def test_dict_compat(): + data_datetime64 = {np.datetime64("1990-03-15"): 1, np.datetime64("2015-03-15"): 2} + data_unchanged = {1: 2, 3: 4, 5: 6} + expected = {Timestamp("1990-3-15"): 1, Timestamp("2015-03-15"): 2} + assert dict_compat(data_datetime64) == expected + assert dict_compat(expected) == expected + assert dict_compat(data_unchanged) == data_unchanged diff --git a/pandas/tests/frame/methods/test_to_dict.py b/pandas/tests/frame/methods/test_to_dict.py index f1656b46cf356..f8feef7a95eab 100644 --- a/pandas/tests/frame/methods/test_to_dict.py +++ b/pandas/tests/frame/methods/test_to_dict.py @@ -257,17 +257,30 @@ def test_to_dict_wide(self): assert result == expected def test_to_dict_orient_dtype(self): - # GH#22620 - # Input Data - input_data = {"a": [1, 2, 3], "b": [1.0, 2.0, 3.0], "c": ["X", "Y", "Z"]} - df = DataFrame(input_data) - # Expected Dtypes - expected = {"a": int, "b": float, "c": str} - # Extracting dtypes out of to_dict operation - for df_dict in df.to_dict("records"): - result = { - "a": type(df_dict["a"]), - "b": type(df_dict["b"]), - "c": type(df_dict["c"]), + # GH22620 & GH21256 + + df = DataFrame( + { + "bool": [True, True, False], + "datetime": [ + datetime(2018, 1, 1), + datetime(2019, 2, 2), + datetime(2020, 3, 3), + ], + "float": [1.0, 2.0, 3.0], + "int": [1, 2, 3], + "str": ["X", "Y", "Z"], } + ) + + expected = { + "int": int, + "float": float, + "str": str, + "datetime": Timestamp, + "bool": bool, + } + + for df_dict in df.to_dict("records"): + result = {col: type(df_dict[col]) for col in list(df.columns)} assert result == expected diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 366a1970f6f64..81d866ba63bc0 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -9,7 +9,7 @@ from pandas.compat.numpy import np_version_under1p17 import pandas as pd -from pandas import Series, Timestamp +from pandas import Series import pandas._testing as tm from pandas.core import ops import pandas.core.common as com @@ -109,15 +109,6 @@ def test_maybe_match_name(left, right, expected): assert ops.common._maybe_match_name(left, right) == expected -def test_dict_compat(): - data_datetime64 = {np.datetime64("1990-03-15"): 1, np.datetime64("2015-03-15"): 2} - data_unchanged = {1: 2, 3: 4, 5: 6} - expected = {Timestamp("1990-3-15"): 1, Timestamp("2015-03-15"): 2} - assert com.dict_compat(data_datetime64) == expected - assert com.dict_compat(expected) == expected - assert com.dict_compat(data_unchanged) == data_unchanged - - def test_standardize_mapping(): # No uninitialized defaultdicts msg = r"to_dict\(\) only accepts initialized defaultdicts"
- [x] closes #21256 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Added a fix for datetime. Added tests for datetime and for bool
https://api.github.com/repos/pandas-dev/pandas/pulls/37571
2020-11-01T23:27:18Z
2020-11-04T23:50:34Z
2020-11-04T23:50:34Z
2020-11-04T23:50:47Z
TST: avoid/suppress DeprecationWarnings
diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index 028a0c4684aef..73aa97c832848 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -664,6 +664,11 @@ def _arith_method(self, other, op): dtype = "bool" result = np.zeros(len(self._data), dtype=dtype) else: + if op_name in {"pow", "rpow"} and isinstance(other, np.bool_): + # Avoid DeprecationWarning: In future, it will be an error + # for 'np.bool_' scalars to be interpreted as an index + other = bool(other) + with np.errstate(all="ignore"): result = op(self._data, other) diff --git a/pandas/tests/indexes/test_index_new.py b/pandas/tests/indexes/test_index_new.py index 9248c185bccd7..c8f580babc0b2 100644 --- a/pandas/tests/indexes/test_index_new.py +++ b/pandas/tests/indexes/test_index_new.py @@ -90,16 +90,25 @@ def test_constructor_infer_nat_dt_like( data = [ctor] data.insert(pos, nulls_fixture) + warn = None if nulls_fixture is NA: expected = Index([NA, NaT]) mark = pytest.mark.xfail(reason="Broken with np.NaT ctor; see GH 31884") request.node.add_marker(mark) + # GH#35942 numpy will emit a DeprecationWarning within the + # assert_index_equal calls. Since we can't do anything + # about it until GH#31884 is fixed, we suppress that warning. + warn = DeprecationWarning result = Index(data) - tm.assert_index_equal(result, expected) + + with tm.assert_produces_warning(warn): + tm.assert_index_equal(result, expected) result = Index(np.array(data, dtype=object)) - tm.assert_index_equal(result, expected) + + with tm.assert_produces_warning(warn): + tm.assert_index_equal(result, expected) @pytest.mark.parametrize("swap_objs", [True, False]) def test_constructor_mixed_nat_objs_infers_object(self, swap_objs):
After this, all thats left for me locally is plotting warnings about multiple subplots
https://api.github.com/repos/pandas-dev/pandas/pulls/37570
2020-11-01T22:43:18Z
2020-11-02T00:28:19Z
2020-11-02T00:28:18Z
2020-11-02T01:09:51Z
PERF: faster numeric indexes comparisons when self is identical to other
diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 546b90249b5ca..d6f571360b457 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -1,3 +1,4 @@ +import operator from typing import Any import numpy as np @@ -185,6 +186,18 @@ def _union(self, other, sort): else: return super()._union(other, sort) + def _cmp_method(self, other, op): + if self.is_(other): # fastpath + if op in {operator.eq, operator.le, operator.ge}: + arr = np.ones(len(self), dtype=bool) + if self._can_hold_na: + arr[self.isna()] = False + return arr + elif op in {operator.ne, operator.lt, operator.gt}: + return np.zeros(len(self), dtype=bool) + + return super()._cmp_method(other, op) + _num_index_shared_docs[ "class_descr" diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index 3afcb0fa343d5..4b8207331838e 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -813,11 +813,8 @@ def any(self, *args, **kwargs) -> bool: def _cmp_method(self, other, op): if isinstance(other, RangeIndex) and self._range == other._range: - if op in {operator.eq, operator.le, operator.ge}: - return np.ones(len(self), dtype=bool) - elif op in {operator.ne, operator.lt, operator.gt}: - return np.zeros(len(self), dtype=bool) - + # Both are immutable so if ._range attr. are equal, shortcut is possible + return super()._cmp_method(self, op) return super()._cmp_method(other, op) def _arith_method(self, other, op):
Further performance improvement over #37130, this time improving all numeric indexes. The improvement is larger for `Int64Index`, because that doesn't need to check for `na` values. Examples: ```python >>> n = 100_000 >>> idx1 = pd.Int64Index(range(n)) >>> idx2 = idx1.view() >>> %timeit idx1 == idx2 145 µs ± 2.43 µs per loop # master 11.4 µs ± 290 ns per loop # this PR >>> idx3 = pd.Float64Index(range(n)) >>> idx4 = idx3.view() >>> %timeit idx3 == idx4 104 µs ± 2.12 µs per loop # master 49.8 µs ± 886 ns per loop # this PR ```
https://api.github.com/repos/pandas-dev/pandas/pulls/37569
2020-11-01T22:11:40Z
2020-11-02T00:32:18Z
2020-11-02T00:32:18Z
2021-01-01T22:13:54Z
BUG: Fix bug in combine_first with string dtype and only NA
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 84f594acf5e4c..980103ad3ad8e 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -531,7 +531,7 @@ Reshaping - Bug in :meth:`Series.transform` would give incorrect results or raise when the argument ``func`` was dictionary (:issue:`35811`) - Bug in :meth:`DataFrame.pivot` did not preserve :class:`MultiIndex` level names for columns when rows and columns both multiindexed (:issue:`36360`) - Bug in :func:`join` returned a non deterministic level-order for the resulting :class:`MultiIndex` (:issue:`36910`) -- +- Bug in :meth:`DataFrame.combine_first()` caused wrong alignment with dtype ``string`` and one level of ``MultiIndex`` containing only ``NA`` (:issue:`37591`) Sparse ^^^^^^ diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 53e5d95907bde..6620a5b5e737f 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -320,7 +320,7 @@ def __init__( # sanitize_array coerces np.nan to a string under certain versions # of numpy values = maybe_infer_to_datetimelike(values, convert_dates=True) - if not isinstance(values, np.ndarray): + if not isinstance(values, (np.ndarray, ExtensionArray)): values = com.convert_to_list_like(values) # By convention, empty lists result in object dtype: diff --git a/pandas/tests/frame/methods/test_combine_first.py b/pandas/tests/frame/methods/test_combine_first.py index d1f38d90547fd..4850c6a50f8a8 100644 --- a/pandas/tests/frame/methods/test_combine_first.py +++ b/pandas/tests/frame/methods/test_combine_first.py @@ -353,3 +353,15 @@ def test_combine_first_with_asymmetric_other(self, val): exp = DataFrame({"isBool": [True], "isNum": [val]}) tm.assert_frame_equal(res, exp) + + def test_combine_first_string_dtype_only_na(self): + # GH: 37519 + df = DataFrame({"a": ["962", "85"], "b": [pd.NA] * 2}, dtype="string") + df2 = DataFrame({"a": ["85"], "b": [pd.NA]}, dtype="string") + df.set_index(["a", "b"], inplace=True) + df2.set_index(["a", "b"], inplace=True) + result = df.combine_first(df2) + expected = DataFrame( + {"a": ["962", "85"], "b": [pd.NA] * 2}, dtype="string" + ).set_index(["a", "b"]) + tm.assert_frame_equal(result, expected)
- [x] closes #37519 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry This caused bugs in ``Index.union()`` and ``Index.join()`` with ``how=outer`` too, but they are called from combine_first. Could add test, if this would be preferable. Hope Adding ExtensionArray to the if condition does not crash anything else. Run most categorical tests already locally.
https://api.github.com/repos/pandas-dev/pandas/pulls/37568
2020-11-01T22:11:31Z
2020-11-02T00:42:22Z
2020-11-02T00:42:21Z
2020-12-13T19:29:30Z
CLN: de-duplicate asof_locs
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 1938722225b98..b9dc8b3014a20 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -4490,7 +4490,7 @@ def asof(self, label): loc = loc.indices(len(self))[-1] return self[loc] - def asof_locs(self, where, mask): + def asof_locs(self, where: "Index", mask) -> np.ndarray: """ Return the locations (indices) of labels in the index. @@ -4518,13 +4518,13 @@ def asof_locs(self, where, mask): which correspond to the return values of the `asof` function for every element in `where`. """ - locs = self.values[mask].searchsorted(where.values, side="right") + locs = self._values[mask].searchsorted(where._values, side="right") locs = np.where(locs > 0, locs - 1, 0) result = np.arange(len(self))[mask].take(locs) first = mask.argmax() - result[(locs == 0) & (where.values < self.values[first])] = -1 + result[(locs == 0) & (where._values < self._values[first])] = -1 return result diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index e90d31c6957b7..44c20ad0de848 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -404,28 +404,17 @@ def __array_wrap__(self, result, context=None): # cannot pass _simple_new as it is return type(self)(result, freq=self.freq, name=self.name) - def asof_locs(self, where, mask: np.ndarray) -> np.ndarray: + def asof_locs(self, where: Index, mask: np.ndarray) -> np.ndarray: """ where : array of timestamps mask : array of booleans where data is not NA """ - where_idx = where - if isinstance(where_idx, DatetimeIndex): - where_idx = PeriodIndex(where_idx._values, freq=self.freq) - elif not isinstance(where_idx, PeriodIndex): + if isinstance(where, DatetimeIndex): + where = PeriodIndex(where._values, freq=self.freq) + elif not isinstance(where, PeriodIndex): raise TypeError("asof_locs `where` must be DatetimeIndex or PeriodIndex") - elif where_idx.freq != self.freq: - raise raise_on_incompatible(self, where_idx) - locs = self.asi8[mask].searchsorted(where_idx.asi8, side="right") - - locs = np.where(locs > 0, locs - 1, 0) - result = np.arange(len(self))[mask].take(locs) - - first = mask.argmax() - result[(locs == 0) & (where_idx.asi8 < self.asi8[first])] = -1 - - return result + return super().asof_locs(where, mask) @doc(Index.astype) def astype(self, dtype, copy: bool = True, how="start"):
We might want to deprecate allowing DatetimeIndex `where` in `PeriodIndex.asof_locs`. We only have one test for it, and allowing it is inconsistent with how we treat other comparisons (unless we want to start allowing dt64 in PeriodArray.searchsorted...)
https://api.github.com/repos/pandas-dev/pandas/pulls/37567
2020-11-01T21:48:15Z
2020-11-02T13:38:13Z
2020-11-02T13:38:13Z
2020-11-02T14:30:26Z
REGR: pd.to_hdf(..., dropna=True) not dropping missing rows
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 7111d54d65815..5fedd57cd2bc8 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -492,6 +492,7 @@ I/O - Bug in output rendering of complex numbers showing too many trailing zeros (:issue:`36799`) - Bug in :class:`HDFStore` threw a ``TypeError`` when exporting an empty :class:`DataFrame` with ``datetime64[ns, tz]`` dtypes with a fixed HDF5 store (:issue:`20594`) - Bug in :class:`HDFStore` was dropping timezone information when exporting :class:`Series` with ``datetime64[ns, tz]`` dtypes with a fixed HDF5 store (:issue:`20594`) +- Bug in :meth:`DataFrame.to_hdf` was not dropping missing rows with ``dropna=True`` (:issue:`35719`) Plotting ^^^^^^^^ diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index 347ce6e853794..bf21a8fe2fc74 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -268,6 +268,7 @@ def to_hdf( data_columns=data_columns, errors=errors, encoding=encoding, + dropna=dropna, ) path_or_buf = stringify_path(path_or_buf) @@ -1051,6 +1052,7 @@ def put( encoding=None, errors: str = "strict", track_times: bool = True, + dropna: bool = False, ): """ Store object in HDFStore. @@ -1100,6 +1102,7 @@ def put( encoding=encoding, errors=errors, track_times=track_times, + dropna=dropna, ) def remove(self, key: str, where=None, start=None, stop=None): diff --git a/pandas/tests/io/pytables/test_store.py b/pandas/tests/io/pytables/test_store.py index f37b0aabd3aed..d76a5a6f64055 100644 --- a/pandas/tests/io/pytables/test_store.py +++ b/pandas/tests/io/pytables/test_store.py @@ -1253,17 +1253,32 @@ def test_append_all_nans(self, setup_path): store.append("df2", df[10:], dropna=False) tm.assert_frame_equal(store["df2"], df) - # Test to make sure defaults are to not drop. - # Corresponding to Issue 9382 + def test_store_dropna(self, setup_path): df_with_missing = DataFrame( - {"col1": [0, np.nan, 2], "col2": [1, np.nan, np.nan]} + {"col1": [0.0, np.nan, 2.0], "col2": [1.0, np.nan, np.nan]}, + index=list("abc"), ) + df_without_missing = DataFrame( + {"col1": [0.0, 2.0], "col2": [1.0, np.nan]}, index=list("ac") + ) + + # # Test to make sure defaults are to not drop. + # # Corresponding to Issue 9382 + with ensure_clean_path(setup_path) as path: + df_with_missing.to_hdf(path, "df", format="table") + reloaded = read_hdf(path, "df") + tm.assert_frame_equal(df_with_missing, reloaded) with ensure_clean_path(setup_path) as path: - df_with_missing.to_hdf(path, "df_with_missing", format="table") - reloaded = read_hdf(path, "df_with_missing") + df_with_missing.to_hdf(path, "df", format="table", dropna=False) + reloaded = read_hdf(path, "df") tm.assert_frame_equal(df_with_missing, reloaded) + with ensure_clean_path(setup_path) as path: + df_with_missing.to_hdf(path, "df", format="table", dropna=True) + reloaded = read_hdf(path, "df") + tm.assert_frame_equal(df_without_missing, reloaded) + def test_read_missing_key_close_store(self, setup_path): # GH 25766 with ensure_clean_path(setup_path) as path:
- [x] closes #35719 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37564
2020-11-01T19:19:55Z
2020-11-04T01:59:22Z
2020-11-04T01:59:22Z
2020-11-04T08:07:23Z
CLN: remove redundant variable in setitem_with_indexer
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 3cb9cba01da48..096ce9a791285 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1645,11 +1645,6 @@ def _setitem_with_indexer_split_path(self, indexer, value): if isinstance(value, ABCSeries): value = self._align_series(indexer, value) - info_idx = indexer[1] - if is_integer(info_idx): - info_idx = [info_idx] - labels = self.obj.columns[info_idx] - # Ensure we have something we can iterate over ilocs = self._ensure_iterable_column_indexer(indexer[1]) @@ -1657,7 +1652,7 @@ def _setitem_with_indexer_split_path(self, indexer, value): lplane_indexer = length_of_indexer(plane_indexer[0], self.obj.index) # lplane_indexer gives the expected length of obj[indexer[0]] - if len(labels) == 1: + if len(ilocs) == 1: # We can operate on a single column # require that we are setting the right number of values that @@ -1678,7 +1673,7 @@ def _setitem_with_indexer_split_path(self, indexer, value): if isinstance(value, ABCDataFrame): self._setitem_with_indexer_frame_value(indexer, value) - # we have an equal len ndarray/convertible to our labels + # we have an equal len ndarray/convertible to our ilocs # hasattr first, to avoid coercing to ndarray without reason. # But we may be relying on the ndarray coercion to check ndim. # Why not just convert to an ndarray earlier on if needed? @@ -1686,12 +1681,12 @@ def _setitem_with_indexer_split_path(self, indexer, value): self._setitem_with_indexer_2d_value(indexer, value) elif ( - len(labels) == 1 + len(ilocs) == 1 and lplane_indexer == len(value) and not is_scalar(plane_indexer[0]) ): # we have an equal len list/ndarray - # We only get here with len(labels) == len(ilocs) == 1 + # We only get here with len(ilocs) == 1 self._setitem_single_column(ilocs[0], value, plane_indexer) elif lplane_indexer == 0 and len(value) == len(self.obj.index):
https://api.github.com/repos/pandas-dev/pandas/pulls/37563
2020-11-01T18:04:59Z
2020-11-02T00:22:44Z
2020-11-02T00:22:44Z
2020-11-02T00:26:12Z
TST: fix xfailing indexing test
diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 3cb9cba01da48..d831e2e6a6dc5 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1710,6 +1710,9 @@ def _setitem_with_indexer_split_path(self, indexer, value): self._setitem_single_column(loc, v, plane_indexer) else: + if isinstance(indexer[0], np.ndarray) and indexer[0].ndim > 2: + raise ValueError(r"Cannot set values with ndim > 2") + # scalar value for loc in ilocs: self._setitem_single_column(loc, value, plane_indexer) diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index 79834dc36ce7d..de70ff37a052a 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -139,7 +139,6 @@ def test_setitem_ndarray_3d(self, index, obj, idxr, idxr_id): with pytest.raises(err, match=msg): idxr[nd3] = 0 - @pytest.mark.xfail(reason="gh-32896") def test_setitem_ndarray_3d_does_not_fail_for_iloc_empty_dataframe(self): # when fixing this, please remove the pytest.skip in test_setitem_ndarray_3d i = Index([])
When moving to the always-go-split_path, a bunch of tests fail without this fix.
https://api.github.com/repos/pandas-dev/pandas/pulls/37562
2020-11-01T17:54:23Z
2020-11-02T00:22:09Z
2020-11-02T00:22:09Z
2020-11-02T00:27:21Z
REF: move IntervalIndex.equals up to ExtensionIndex.equals
diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index 1f26ceaf2d1b7..90b73da8a53ba 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -283,6 +283,17 @@ def astype(self, dtype, copy=True): def _isnan(self) -> np.ndarray: return self._data.isna() + @doc(Index.equals) + def equals(self, other) -> bool: + # Dispatch to the ExtensionArray's .equals method. + if self.is_(other): + return True + + if not isinstance(other, type(self)): + return False + + return self._data.equals(other._data) + class NDArrayBackedExtensionIndex(ExtensionIndex): """ diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index b9d51f6895ef0..1bd71f00b534d 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -970,18 +970,6 @@ def _format_space(self) -> str: def argsort(self, *args, **kwargs) -> np.ndarray: return np.lexsort((self.right, self.left)) - def equals(self, other: object) -> bool: - """ - Determines if two IntervalIndex objects contain the same elements. - """ - if self.is_(other): - return True - - if not isinstance(other, IntervalIndex): - return False - - return self._data.equals(other._data) - # -------------------------------------------------------------------- # Set Operations
https://api.github.com/repos/pandas-dev/pandas/pulls/37561
2020-11-01T17:50:25Z
2020-11-02T00:33:49Z
2020-11-02T00:33:49Z
2020-11-02T17:45:30Z
REF: move _wrap_joined_index up to NDarrayBackedExtensionIndex
diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index c137509a2cd2d..2f2836519d847 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -29,7 +29,6 @@ from pandas.core.indexes.base import Index, _index_shared_docs, maybe_extract_name from pandas.core.indexes.extension import NDArrayBackedExtensionIndex, inherit_names import pandas.core.missing as missing -from pandas.core.ops import get_op_result_name _index_doc_kwargs = dict(ibase._index_doc_kwargs) _index_doc_kwargs.update(dict(target_klass="CategoricalIndex")) @@ -669,10 +668,3 @@ def _delegate_method(self, name: str, *args, **kwargs): if is_scalar(res): return res return CategoricalIndex(res, name=self.name) - - def _wrap_joined_index( - self, joined: np.ndarray, other: "CategoricalIndex" - ) -> "CategoricalIndex": - name = get_op_result_name(self, other) - cat = self._data._from_backing_data(joined) - return type(self)._simple_new(cat, name=name) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 751eafaa0d78e..9215fc8994d87 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -38,7 +38,6 @@ make_wrapped_arith_op, ) from pandas.core.indexes.numeric import Int64Index -from pandas.core.ops import get_op_result_name from pandas.core.tools.timedeltas import to_timedelta if TYPE_CHECKING: @@ -629,20 +628,23 @@ def insert(self, loc: int, item): def _can_union_without_object_cast(self, other) -> bool: return is_dtype_equal(self.dtype, other.dtype) - def _wrap_joined_index(self, joined: np.ndarray, other): - assert other.dtype == self.dtype, (other.dtype, self.dtype) - name = get_op_result_name(self, other) - + def _get_join_freq(self, other): + """ + Get the freq to attach to the result of a join operation. + """ if is_period_dtype(self.dtype): freq = self.freq else: self = cast(DatetimeTimedeltaMixin, self) freq = self.freq if self._can_fast_union(other) else None + return freq - new_data = self._data._from_backing_data(joined) - new_data._freq = freq + def _wrap_joined_index(self, joined: np.ndarray, other): + assert other.dtype == self.dtype, (other.dtype, self.dtype) - return type(self)._simple_new(new_data, name=name) + result = super()._wrap_joined_index(joined, other) + result._data._freq = self._get_join_freq(other) + return result @doc(Index._convert_arr_indexer) def _convert_arr_indexer(self, keyarr): diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index 1f26ceaf2d1b7..3376aef8bef87 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -1,7 +1,7 @@ """ Shared methods for Index subclasses backed by ExtensionArray. """ -from typing import List +from typing import List, TypeVar import numpy as np @@ -18,6 +18,8 @@ from pandas.core.indexes.base import Index from pandas.core.ops import get_op_result_name +_T = TypeVar("_T", bound="NDArrayBackedExtensionIndex") + def inherit_from_data(name: str, delegate, cache: bool = False, wrap: bool = False): """ @@ -338,3 +340,8 @@ def putmask(self, mask, value): np.putmask(new_values, mask, value) new_arr = self._data._from_backing_data(new_values) return type(self)._simple_new(new_arr, name=self.name) + + def _wrap_joined_index(self: _T, joined: np.ndarray, other: _T) -> _T: + name = get_op_result_name(self, other) + arr = self._data._from_backing_data(joined) + return type(self)._simple_new(arr, name=name)
Small steps towards a) supporting arbitrary ExtensionIndex b) using `@final` more in index code
https://api.github.com/repos/pandas-dev/pandas/pulls/37560
2020-11-01T17:17:32Z
2020-11-02T00:35:06Z
2020-11-02T00:35:05Z
2020-11-02T15:12:42Z
Add ss02
diff --git a/ci/code_checks.sh b/ci/code_checks.sh index b5d63e259456b..1ec3d25137a71 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -238,8 +238,8 @@ fi ### DOCSTRINGS ### if [[ -z "$CHECK" || "$CHECK" == "docstrings" ]]; then - MSG='Validate docstrings (GL03, GL04, GL05, GL06, GL07, GL09, GL10, SS04, SS05, PR03, PR04, PR05, PR10, EX04, RT01, RT04, RT05, SA02, SA03)' ; echo $MSG - $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=GL03,GL04,GL05,GL06,GL07,GL09,GL10,SS04,SS05,PR03,PR04,PR05,PR10,EX04,RT01,RT04,RT05,SA02,SA03 + MSG='Validate docstrings (GL03, GL04, GL05, GL06, GL07, GL09, GL10, SS02, SS04, SS05, PR03, PR04, PR05, PR10, EX04, RT01, RT04, RT05, SA02, SA03)' ; echo $MSG + $BASE_DIR/scripts/validate_docstrings.py --format=actions --errors=GL03,GL04,GL05,GL06,GL07,GL09,GL10,SS02,SS04,SS05,PR03,PR04,PR05,PR10,EX04,RT01,RT04,RT05,SA02,SA03 RET=$(($RET + $?)) ; echo $MSG "DONE" MSG='Validate correct capitalization among titles in documentation' ; echo $MSG diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index e10ac6a05ead8..561143f48e0ec 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -418,7 +418,6 @@ class NaTType(_NaT): utctimetuple = _make_error_func("utctimetuple", datetime) timetz = _make_error_func("timetz", datetime) timetuple = _make_error_func("timetuple", datetime) - strftime = _make_error_func("strftime", datetime) isocalendar = _make_error_func("isocalendar", datetime) dst = _make_error_func("dst", datetime) ctime = _make_error_func("ctime", datetime) @@ -435,6 +434,23 @@ class NaTType(_NaT): # The remaining methods have docstrings copy/pasted from the analogous # Timestamp methods. + strftime = _make_error_func( + "strftime", + """ + Timestamp.strftime(format) + + Return a string representing the given POSIX timestamp + controlled by an explicit format string. + + Parameters + ---------- + format : str + Format string to convert Timestamp to string. + See strftime documentation for more information on the format string: + https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior. + """, + ) + strptime = _make_error_func( "strptime", """ @@ -457,7 +473,7 @@ class NaTType(_NaT): """ Timestamp.fromtimestamp(ts) - timestamp[, tz] -> tz's local time from POSIX timestamp. + Transform timestamp[, tz] to tz's local time from POSIX timestamp. """, ) combine = _make_error_func( @@ -465,7 +481,7 @@ class NaTType(_NaT): """ Timestamp.combine(date, time) - date, time -> datetime with same date and time fields. + Combine date, time into datetime with same date and time fields. """, ) utcnow = _make_error_func( @@ -606,7 +622,7 @@ timedelta}, default 'raise' floor = _make_nat_func( "floor", """ - return a new Timestamp floored to this resolution. + Return a new Timestamp floored to this resolution. Parameters ---------- @@ -645,7 +661,7 @@ timedelta}, default 'raise' ceil = _make_nat_func( "ceil", """ - return a new Timestamp ceiled to this resolution. + Return a new Timestamp ceiled to this resolution. Parameters ---------- @@ -761,7 +777,7 @@ default 'raise' replace = _make_nat_func( "replace", """ - implements datetime.replace, handles nanoseconds. + Implements datetime.replace, handles nanoseconds. Parameters ---------- diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index b3ae69d7a3237..242eb89d1e723 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -912,10 +912,26 @@ class Timestamp(_Timestamp): """ Timestamp.fromtimestamp(ts) - timestamp[, tz] -> tz's local time from POSIX timestamp. + Transform timestamp[, tz] to tz's local time from POSIX timestamp. """ return cls(datetime.fromtimestamp(ts)) + def strftime(self, format): + """ + Timestamp.strftime(format) + + Return a string representing the given POSIX timestamp + controlled by an explicit format string. + + Parameters + ---------- + format : str + Format string to convert Timestamp to string. + See strftime documentation for more information on the format string: + https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior. + """ + return datetime.strftime(self, format) + # Issue 25016. @classmethod def strptime(cls, date_string, format): @@ -934,7 +950,7 @@ class Timestamp(_Timestamp): """ Timestamp.combine(date, time) - date, time -> datetime with same date and time fields. + Combine date, time into datetime with same date and time fields. """ return cls(datetime.combine(date, time)) @@ -1153,7 +1169,7 @@ timedelta}, default 'raise' def floor(self, freq, ambiguous='raise', nonexistent='raise'): """ - return a new Timestamp floored to this resolution. + Return a new Timestamp floored to this resolution. Parameters ---------- @@ -1192,7 +1208,7 @@ timedelta}, default 'raise' def ceil(self, freq, ambiguous='raise', nonexistent='raise'): """ - return a new Timestamp ceiled to this resolution. + Return a new Timestamp ceiled to this resolution. Parameters ---------- @@ -1377,7 +1393,7 @@ default 'raise' fold=None, ): """ - implements datetime.replace, handles nanoseconds. + Implements datetime.replace, handles nanoseconds. Parameters ----------
- [x] closes #25113, closes https://github.com/pandas-dev/pandas/issues/36745 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37559
2020-11-01T16:10:09Z
2020-11-10T03:38:05Z
2020-11-10T03:38:04Z
2020-12-30T08:10:29Z
ENH: Improve numerical stability for window functions skew and kurt
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index d4d28dde52d58..fab4a8dce8ea8 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -232,6 +232,7 @@ Other enhancements - :meth:`testing.assert_index_equal` now has a ``check_order`` parameter that allows indexes to be checked in an order-insensitive manner (:issue:`37478`) - :func:`read_csv` supports memory-mapping for compressed files (:issue:`37621`) - Improve error reporting for :meth:`DataFrame.merge()` when invalid merge column definitions were given (:issue:`16228`) +- Improve numerical stability for :meth:`Rolling.skew()`, :meth:`Rolling.kurt()`, :meth:`Expanding.skew()` and :meth:`Expanding.kurt()` through implementation of Kahan summation (:issue:`6929`) .. _whatsnew_120.api_breaking.python: diff --git a/pandas/_libs/window/aggregations.pyx b/pandas/_libs/window/aggregations.pyx index 3556085bb300b..4de7a5860c465 100644 --- a/pandas/_libs/window/aggregations.pyx +++ b/pandas/_libs/window/aggregations.pyx @@ -2,6 +2,7 @@ import cython +from libc.math cimport round from libcpp.deque cimport deque import numpy as np @@ -458,42 +459,71 @@ cdef inline float64_t calc_skew(int64_t minp, int64_t nobs, cdef inline void add_skew(float64_t val, int64_t *nobs, float64_t *x, float64_t *xx, - float64_t *xxx) nogil: + float64_t *xxx, + float64_t *compensation_x, + float64_t *compensation_xx, + float64_t *compensation_xxx) nogil: """ add a value from the skew calc """ + cdef: + float64_t y, t # Not NaN if notnan(val): nobs[0] = nobs[0] + 1 - # seriously don't ask me why this is faster - x[0] = x[0] + val - xx[0] = xx[0] + val * val - xxx[0] = xxx[0] + val * val * val + y = val - compensation_x[0] + t = x[0] + y + compensation_x[0] = t - x[0] - y + x[0] = t + y = val * val - compensation_xx[0] + t = xx[0] + y + compensation_xx[0] = t - xx[0] - y + xx[0] = t + y = val * val * val - compensation_xxx[0] + t = xxx[0] + y + compensation_xxx[0] = t - xxx[0] - y + xxx[0] = t cdef inline void remove_skew(float64_t val, int64_t *nobs, float64_t *x, float64_t *xx, - float64_t *xxx) nogil: + float64_t *xxx, + float64_t *compensation_x, + float64_t *compensation_xx, + float64_t *compensation_xxx) nogil: """ remove a value from the skew calc """ + cdef: + float64_t y, t # Not NaN if notnan(val): nobs[0] = nobs[0] - 1 - # seriously don't ask me why this is faster - x[0] = x[0] - val - xx[0] = xx[0] - val * val - xxx[0] = xxx[0] - val * val * val + y = - val - compensation_x[0] + t = x[0] + y + compensation_x[0] = t - x[0] - y + x[0] = t + y = - val * val - compensation_xx[0] + t = xx[0] + y + compensation_xx[0] = t - xx[0] - y + xx[0] = t + y = - val * val * val - compensation_xxx[0] + t = xxx[0] + y + compensation_xxx[0] = t - xxx[0] - y + xxx[0] = t def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, ndarray[int64_t] end, int64_t minp): cdef: - float64_t val, prev + 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, i, j, N = len(values) + int64_t nobs = 0, i, j, N = len(values), nobs_mean = 0 int64_t s, e - ndarray[float64_t] output + ndarray[float64_t] output, mean_array bint is_monotonic_increasing_bounds minp = max(minp, 3) @@ -501,8 +531,20 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, start, end ) output = np.empty(N, dtype=float) + min_val = np.nanmin(values) with nogil: + for i in range(0, N): + val = values[i] + if notnan(val): + nobs_mean += 1 + sum_val += val + mean_val = sum_val / nobs_mean + # 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): + values[i] = values[i] - mean_val for i in range(0, N): @@ -515,22 +557,24 @@ def roll_skew(ndarray[float64_t] values, ndarray[int64_t] start, for j in range(s, e): val = values[j] - add_skew(val, &nobs, &x, &xx, &xxx) + add_skew(val, &nobs, &x, &xx, &xxx, &compensation_x_add, + &compensation_xx_add, &compensation_xxx_add) else: # After the first window, observations can both be added # and removed + # calculate deletes + for j in range(start[i - 1], s): + val = values[j] + remove_skew(val, &nobs, &x, &xx, &xxx, &compensation_x_remove, + &compensation_xx_remove, &compensation_xxx_remove) # calculate adds for j in range(end[i - 1], e): val = values[j] - add_skew(val, &nobs, &x, &xx, &xxx) - - # calculate deletes - for j in range(start[i - 1], s): - val = values[j] - remove_skew(val, &nobs, &x, &xx, &xxx) + add_skew(val, &nobs, &x, &xx, &xxx, &compensation_x_add, + &compensation_xx_add, &compensation_xxx_add) output[i] = calc_skew(minp, nobs, x, xx, xxx) @@ -585,42 +629,80 @@ cdef inline float64_t calc_kurt(int64_t minp, int64_t nobs, cdef inline void add_kurt(float64_t val, int64_t *nobs, float64_t *x, float64_t *xx, - float64_t *xxx, float64_t *xxxx) nogil: + float64_t *xxx, float64_t *xxxx, + float64_t *compensation_x, + float64_t *compensation_xx, + float64_t *compensation_xxx, + float64_t *compensation_xxxx) nogil: """ add a value from the kurotic calc """ + cdef: + float64_t y, t # Not NaN if notnan(val): nobs[0] = nobs[0] + 1 - # seriously don't ask me why this is faster - x[0] = x[0] + val - xx[0] = xx[0] + val * val - xxx[0] = xxx[0] + val * val * val - xxxx[0] = xxxx[0] + val * val * val * val + y = val - compensation_x[0] + t = x[0] + y + compensation_x[0] = t - x[0] - y + x[0] = t + y = val * val - compensation_xx[0] + t = xx[0] + y + compensation_xx[0] = t - xx[0] - y + xx[0] = t + y = val * val * val - compensation_xxx[0] + t = xxx[0] + y + compensation_xxx[0] = t - xxx[0] - y + xxx[0] = t + y = val * val * val * val - compensation_xxxx[0] + t = xxxx[0] + y + compensation_xxxx[0] = t - xxxx[0] - y + xxxx[0] = t cdef inline void remove_kurt(float64_t val, int64_t *nobs, float64_t *x, float64_t *xx, - float64_t *xxx, float64_t *xxxx) nogil: + float64_t *xxx, float64_t *xxxx, + float64_t *compensation_x, + float64_t *compensation_xx, + float64_t *compensation_xxx, + float64_t *compensation_xxxx) nogil: """ remove a value from the kurotic calc """ + cdef: + float64_t y, t # Not NaN if notnan(val): nobs[0] = nobs[0] - 1 - # seriously don't ask me why this is faster - x[0] = x[0] - val - xx[0] = xx[0] - val * val - xxx[0] = xxx[0] - val * val * val - xxxx[0] = xxxx[0] - val * val * val * val + y = - val - compensation_x[0] + t = x[0] + y + compensation_x[0] = t - x[0] - y + x[0] = t + y = - val * val - compensation_xx[0] + t = xx[0] + y + compensation_xx[0] = t - xx[0] - y + xx[0] = t + y = - val * val * val - compensation_xxx[0] + t = xxx[0] + y + compensation_xxx[0] = t - xxx[0] - y + xxx[0] = t + y = - val * val * val * val - compensation_xxxx[0] + t = xxxx[0] + y + compensation_xxxx[0] = t - xxxx[0] - y + xxxx[0] = t def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, ndarray[int64_t] end, int64_t minp): cdef: - float64_t val, prev + 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, i, j, s, e, N = len(values) + int64_t nobs = 0, i, j, s, e, N = len(values), nobs_mean = 0 ndarray[float64_t] output bint is_monotonic_increasing_bounds @@ -629,8 +711,20 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, start, end ) output = np.empty(N, dtype=float) + min_val = np.nanmin(values) with nogil: + for i in range(0, N): + val = values[i] + if notnan(val): + nobs_mean += 1 + sum_val += val + mean_val = sum_val / nobs_mean + # 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): + values[i] = values[i] - mean_val for i in range(0, N): @@ -642,20 +736,25 @@ def roll_kurt(ndarray[float64_t] values, ndarray[int64_t] start, if i == 0 or not is_monotonic_increasing_bounds: for j in range(s, e): - add_kurt(values[j], &nobs, &x, &xx, &xxx, &xxxx) + add_kurt(values[j], &nobs, &x, &xx, &xxx, &xxxx, + &compensation_x_add, &compensation_xx_add, + &compensation_xxx_add, &compensation_xxxx_add) else: # After the first window, observations can both be added # and removed + # calculate deletes + for j in range(start[i - 1], s): + remove_kurt(values[j], &nobs, &x, &xx, &xxx, &xxxx, + &compensation_x_remove, &compensation_xx_remove, + &compensation_xxx_remove, &compensation_xxxx_remove) # calculate adds for j in range(end[i - 1], e): - add_kurt(values[j], &nobs, &x, &xx, &xxx, &xxxx) - - # calculate deletes - for j in range(start[i - 1], s): - remove_kurt(values[j], &nobs, &x, &xx, &xxx, &xxxx) + add_kurt(values[j], &nobs, &x, &xx, &xxx, &xxxx, + &compensation_x_add, &compensation_xx_add, + &compensation_xxx_add, &compensation_xxxx_add) output[i] = calc_kurt(minp, nobs, x, xx, xxx, xxxx) diff --git a/pandas/tests/window/test_expanding.py b/pandas/tests/window/test_expanding.py index 21c7477918d02..ace6848a58c9c 100644 --- a/pandas/tests/window/test_expanding.py +++ b/pandas/tests/window/test_expanding.py @@ -255,3 +255,13 @@ def test_expanding_sem(constructor): result = Series(result[0].values) expected = Series([np.nan] + [0.707107] * 2) tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize("method", ["skew", "kurt"]) +def test_expanding_skew_kurt_numerical_stability(method): + # GH: 6929 + s = Series(np.random.rand(10)) + expected = getattr(s.expanding(3), method)() + s = s + 5000 + result = getattr(s.expanding(3), method)() + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index 02bcfab8d3388..6cad93f2d77ba 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -1102,3 +1102,28 @@ def test_groupby_rolling_nan_included(): ), ) tm.assert_frame_equal(result, expected) + + +@pytest.mark.parametrize("method", ["skew", "kurt"]) +def test_rolling_skew_kurt_numerical_stability(method): + # GH: 6929 + s = Series(np.random.rand(10)) + expected = getattr(s.rolling(3), method)() + s = s + 50000 + result = getattr(s.rolling(3), method)() + tm.assert_series_equal(result, expected) + + +@pytest.mark.parametrize( + ("method", "values"), + [ + ("skew", [2.0, 0.854563, 0.0, 1.999984]), + ("kurt", [4.0, -1.289256, -1.2, 3.999946]), + ], +) +def test_rolling_skew_kurt_large_value_range(method, values): + # GH: 37557 + s = Series([3000000, 1, 1, 2, 3, 4, 999]) + result = getattr(s.rolling(4), method)() + expected = Series([np.nan] * 3 + values) + tm.assert_series_equal(result, expected)
- [x] closes #6929 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Used the same procedure as in ``DataFrame.skew()``
https://api.github.com/repos/pandas-dev/pandas/pulls/37557
2020-11-01T13:51:37Z
2020-11-09T21:20:06Z
2020-11-09T21:20:05Z
2020-11-09T21:44:11Z
TYP: Check untyped defs (except vendored)
diff --git a/pandas/_testing.py b/pandas/_testing.py index ded2ed3141b47..5dcd1247e52ba 100644 --- a/pandas/_testing.py +++ b/pandas/_testing.py @@ -117,14 +117,24 @@ def set_testing_mode(): # set the testing mode filters testing_mode = os.environ.get("PANDAS_TESTING_MODE", "None") if "deprecate" in testing_mode: - warnings.simplefilter("always", _testing_mode_warnings) + # pandas\_testing.py:119: error: Argument 2 to "simplefilter" has + # incompatible type "Tuple[Type[DeprecationWarning], + # Type[ResourceWarning]]"; expected "Type[Warning]" + warnings.simplefilter( + "always", _testing_mode_warnings # type: ignore[arg-type] + ) def reset_testing_mode(): # reset the testing mode filters testing_mode = os.environ.get("PANDAS_TESTING_MODE", "None") if "deprecate" in testing_mode: - warnings.simplefilter("ignore", _testing_mode_warnings) + # pandas\_testing.py:126: error: Argument 2 to "simplefilter" has + # incompatible type "Tuple[Type[DeprecationWarning], + # Type[ResourceWarning]]"; expected "Type[Warning]" + warnings.simplefilter( + "ignore", _testing_mode_warnings # type: ignore[arg-type] + ) set_testing_mode() @@ -241,16 +251,22 @@ def decompress_file(path, compression): if compression is None: f = open(path, "rb") elif compression == "gzip": - f = gzip.open(path, "rb") + # pandas\_testing.py:243: error: Incompatible types in assignment + # (expression has type "IO[Any]", variable has type "BinaryIO") + f = gzip.open(path, "rb") # type: ignore[assignment] elif compression == "bz2": - f = bz2.BZ2File(path, "rb") + # pandas\_testing.py:245: error: Incompatible types in assignment + # (expression has type "BZ2File", variable has type "BinaryIO") + f = bz2.BZ2File(path, "rb") # type: ignore[assignment] elif compression == "xz": f = get_lzma_file(lzma)(path, "rb") elif compression == "zip": zip_file = zipfile.ZipFile(path) zip_names = zip_file.namelist() if len(zip_names) == 1: - f = zip_file.open(zip_names.pop()) + # pandas\_testing.py:252: error: Incompatible types in assignment + # (expression has type "IO[bytes]", variable has type "BinaryIO") + f = zip_file.open(zip_names.pop()) # type: ignore[assignment] else: raise ValueError(f"ZIP file {path} error. Only one file per ZIP.") else: @@ -286,9 +302,15 @@ def write_to_compressed(compression, path, data, dest="test"): if compression == "zip": compress_method = zipfile.ZipFile elif compression == "gzip": - compress_method = gzip.GzipFile + # pandas\_testing.py:288: error: Incompatible types in assignment + # (expression has type "Type[GzipFile]", variable has type + # "Type[ZipFile]") + compress_method = gzip.GzipFile # type: ignore[assignment] elif compression == "bz2": - compress_method = bz2.BZ2File + # pandas\_testing.py:290: error: Incompatible types in assignment + # (expression has type "Type[BZ2File]", variable has type + # "Type[ZipFile]") + compress_method = bz2.BZ2File # type: ignore[assignment] elif compression == "xz": compress_method = get_lzma_file(lzma) else: @@ -300,7 +322,10 @@ def write_to_compressed(compression, path, data, dest="test"): method = "writestr" else: mode = "wb" - args = (data,) + # pandas\_testing.py:302: error: Incompatible types in assignment + # (expression has type "Tuple[Any]", variable has type "Tuple[Any, + # Any]") + args = (data,) # type: ignore[assignment] method = "write" with compress_method(path, mode=mode) as f: @@ -1996,7 +2021,8 @@ def all_timeseries_index_generator(k=10): """ make_index_funcs = [makeDateIndex, makePeriodIndex, makeTimedeltaIndex] for make_index_func in make_index_funcs: - yield make_index_func(k=k) + # pandas\_testing.py:1986: error: Cannot call function of unknown type + yield make_index_func(k=k) # type: ignore[operator] # make series @@ -2130,7 +2156,8 @@ def makeCustomIndex( p=makePeriodIndex, ).get(idx_type) if idx_func: - idx = idx_func(nentries) + # pandas\_testing.py:2120: error: Cannot call function of unknown type + idx = idx_func(nentries) # type: ignore[operator] # but we need to fill in the name if names: idx.name = names[0] @@ -2158,7 +2185,8 @@ def keyfunc(x): # build a list of lists to create the index from div_factor = nentries // ndupe_l[i] + 1 - cnt = Counter() + # pandas\_testing.py:2148: error: Need type annotation for 'cnt' + cnt = Counter() # type: ignore[var-annotated] for j in range(div_factor): label = f"{prefix}_l{i}_g{j}" cnt[label] = ndupe_l[i] @@ -2316,7 +2344,14 @@ def _gen_unique_rand(rng, _extra_size): def makeMissingDataframe(density=0.9, random_state=None): df = makeDataFrame() - i, j = _create_missing_idx(*df.shape, density=density, random_state=random_state) + # pandas\_testing.py:2306: error: "_create_missing_idx" gets multiple + # values for keyword argument "density" [misc] + + # pandas\_testing.py:2306: error: "_create_missing_idx" gets multiple + # values for keyword argument "random_state" [misc] + i, j = _create_missing_idx( # type: ignore[misc] + *df.shape, density=density, random_state=random_state + ) df.values[i, j] = np.nan return df @@ -2341,7 +2376,10 @@ def dec(f): is_decorating = not kwargs and len(args) == 1 and callable(args[0]) if is_decorating: f = args[0] - args = [] + # pandas\_testing.py:2331: error: Incompatible types in assignment + # (expression has type "List[<nothing>]", variable has type + # "Tuple[Any, ...]") + args = [] # type: ignore[assignment] return dec(f) else: return dec @@ -2534,7 +2572,9 @@ def wrapper(*args, **kwargs): except Exception as err: errno = getattr(err, "errno", None) if not errno and hasattr(errno, "reason"): - errno = getattr(err.reason, "errno", None) + # pandas\_testing.py:2521: error: "Exception" has no attribute + # "reason" + errno = getattr(err.reason, "errno", None) # type: ignore[attr-defined] if errno in skip_errnos: skip(f"Skipping test due to known errno and error {err}") diff --git a/pandas/core/apply.py b/pandas/core/apply.py index a14debce6eea7..fa4fbe711fbe4 100644 --- a/pandas/core/apply.py +++ b/pandas/core/apply.py @@ -141,7 +141,11 @@ def get_result(self): """ compute the results """ # dispatch to agg if is_list_like(self.f) or is_dict_like(self.f): - return self.obj.aggregate(self.f, axis=self.axis, *self.args, **self.kwds) + # pandas\core\apply.py:144: error: "aggregate" of "DataFrame" gets + # multiple values for keyword argument "axis" + return self.obj.aggregate( # type: ignore[misc] + self.f, axis=self.axis, *self.args, **self.kwds + ) # all empty if len(self.columns) == 0 and len(self.index) == 0: diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 8d90035491d28..f2f843886e802 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -431,7 +431,9 @@ def _validate_comparison_value(self, other): raise InvalidComparison(other) if isinstance(other, self._recognized_scalars) or other is NaT: - other = self._scalar_type(other) + # pandas\core\arrays\datetimelike.py:432: error: Too many arguments + # for "object" [call-arg] + other = self._scalar_type(other) # type: ignore[call-arg] try: self._check_compatible_with(other) except TypeError as err: @@ -491,14 +493,18 @@ def _validate_shift_value(self, fill_value): if is_valid_nat_for_dtype(fill_value, self.dtype): fill_value = NaT elif isinstance(fill_value, self._recognized_scalars): - fill_value = self._scalar_type(fill_value) + # pandas\core\arrays\datetimelike.py:746: error: Too many arguments + # for "object" [call-arg] + fill_value = self._scalar_type(fill_value) # type: ignore[call-arg] else: # only warn if we're not going to raise if self._scalar_type is Period and lib.is_integer(fill_value): # kludge for #31971 since Period(integer) tries to cast to str new_fill = Period._from_ordinal(fill_value, freq=self.freq) else: - new_fill = self._scalar_type(fill_value) + # pandas\core\arrays\datetimelike.py:753: error: Too many + # arguments for "object" [call-arg] + new_fill = self._scalar_type(fill_value) # type: ignore[call-arg] # stacklevel here is chosen to be correct when called from # DataFrame.shift or Series.shift diff --git a/pandas/core/arrays/string_.py b/pandas/core/arrays/string_.py index c73855f281bcc..3b297e7c2b13b 100644 --- a/pandas/core/arrays/string_.py +++ b/pandas/core/arrays/string_.py @@ -186,7 +186,10 @@ def __init__(self, values, copy=False): values = extract_array(values) super().__init__(values, copy=copy) - self._dtype = StringDtype() + # pandas\core\arrays\string_.py:188: error: Incompatible types in + # assignment (expression has type "StringDtype", variable has type + # "PandasDtype") [assignment] + self._dtype = StringDtype() # type: ignore[assignment] if not isinstance(values, type(self)): self._validate() diff --git a/pandas/core/base.py b/pandas/core/base.py index b979298fa53f6..0f6c369f5e19b 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -95,7 +95,9 @@ def __sizeof__(self): either a value or Series of values """ if hasattr(self, "memory_usage"): - mem = self.memory_usage(deep=True) + # pandas\core\base.py:84: error: "PandasObject" has no attribute + # "memory_usage" [attr-defined] + mem = self.memory_usage(deep=True) # type: ignore[attr-defined] return int(mem if is_scalar(mem) else mem.sum()) # no memory_usage attribute, so fall back to object's 'sizeof' @@ -204,10 +206,18 @@ def _selection_list(self): @cache_readonly def _selected_obj(self): - if self._selection is None or isinstance(self.obj, ABCSeries): - return self.obj + # pandas\core\base.py:195: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] + if self._selection is None or isinstance( + self.obj, ABCSeries # type: ignore[attr-defined] + ): + # pandas\core\base.py:194: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] + return self.obj # type: ignore[attr-defined] else: - return self.obj[self._selection] + # pandas\core\base.py:204: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] + return self.obj[self._selection] # type: ignore[attr-defined] @cache_readonly def ndim(self) -> int: @@ -215,21 +225,46 @@ def ndim(self) -> int: @cache_readonly def _obj_with_exclusions(self): - if self._selection is not None and isinstance(self.obj, ABCDataFrame): - return self.obj.reindex(columns=self._selection_list) + # pandas\core\base.py:209: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] + if self._selection is not None and isinstance( + self.obj, ABCDataFrame # type: ignore[attr-defined] + ): + # pandas\core\base.py:217: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] + return self.obj.reindex( # type: ignore[attr-defined] + columns=self._selection_list + ) + + # pandas\core\base.py:207: error: "SelectionMixin" has no attribute + # "exclusions" [attr-defined] + if len(self.exclusions) > 0: # type: ignore[attr-defined] + # pandas\core\base.py:208: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] - if len(self.exclusions) > 0: - return self.obj.drop(self.exclusions, axis=1) + # pandas\core\base.py:208: error: "SelectionMixin" has no attribute + # "exclusions" [attr-defined] + return self.obj.drop(self.exclusions, axis=1) # type: ignore[attr-defined] else: - return self.obj + # pandas\core\base.py:210: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] + return self.obj # type: ignore[attr-defined] def __getitem__(self, key): if self._selection is not None: raise IndexError(f"Column(s) {self._selection} already selected") if isinstance(key, (list, tuple, ABCSeries, ABCIndexClass, np.ndarray)): - if len(self.obj.columns.intersection(key)) != len(key): - bad_keys = list(set(key).difference(self.obj.columns)) + # pandas\core\base.py:217: error: "SelectionMixin" has no attribute + # "obj" [attr-defined] + if len( + self.obj.columns.intersection(key) # type: ignore[attr-defined] + ) != len(key): + # pandas\core\base.py:218: error: "SelectionMixin" has no + # attribute "obj" [attr-defined] + bad_keys = list( + set(key).difference(self.obj.columns) # type: ignore[attr-defined] + ) raise KeyError(f"Columns not found: {str(bad_keys)[1:-1]}") return self._gotitem(list(key), ndim=2) @@ -559,7 +594,11 @@ def to_numpy(self, dtype=None, copy=False, na_value=lib.no_default, **kwargs): dtype='datetime64[ns]') """ if is_extension_array_dtype(self.dtype): - return self.array.to_numpy(dtype, copy=copy, na_value=na_value, **kwargs) + # pandas\core\base.py:837: error: Too many arguments for "to_numpy" + # of "ExtensionArray" [call-arg] + return self.array.to_numpy( # type: ignore[call-arg] + dtype, copy=copy, na_value=na_value, **kwargs + ) elif kwargs: bad_keys = list(kwargs.keys())[0] raise TypeError( @@ -851,8 +890,15 @@ def _map_values(self, mapper, na_action=None): if is_categorical_dtype(self.dtype): # use the built in categorical series mapper which saves # time by mapping the categories instead of all values - self = cast("Categorical", self) - return self._values.map(mapper) + + # pandas\core\base.py:893: error: Incompatible types in + # assignment (expression has type "Categorical", variable has + # type "IndexOpsMixin") [assignment] + self = cast("Categorical", self) # type: ignore[assignment] + # pandas\core\base.py:894: error: Item "ExtensionArray" of + # "Union[ExtensionArray, Any]" has no attribute "map" + # [union-attr] + return self._values.map(mapper) # type: ignore[union-attr] values = self._values @@ -869,7 +915,9 @@ def _map_values(self, mapper, na_action=None): raise NotImplementedError map_f = lambda values, f: values.map(f) else: - values = self.astype(object)._values + # pandas\core\base.py:1142: error: "IndexOpsMixin" has no attribute + # "astype" [attr-defined] + values = self.astype(object)._values # type: ignore[attr-defined] if na_action == "ignore": def map_f(values, f): @@ -1111,7 +1159,9 @@ def memory_usage(self, deep=False): are not components of the array if deep=False or if used on PyPy """ if hasattr(self.array, "memory_usage"): - return self.array.memory_usage(deep=deep) + # pandas\core\base.py:1379: error: "ExtensionArray" has no + # attribute "memory_usage" [attr-defined] + return self.array.memory_usage(deep=deep) # type: ignore[attr-defined] v = self.array.nbytes if deep and is_object_dtype(self) and not PYPY: @@ -1245,7 +1295,9 @@ def searchsorted(self, value, side="left", sorter=None) -> np.ndarray: def drop_duplicates(self, keep="first"): duplicated = self.duplicated(keep=keep) - result = self[np.logical_not(duplicated)] + # pandas\core\base.py:1507: error: Value of type "IndexOpsMixin" is not + # indexable [index] + result = self[np.logical_not(duplicated)] # type: ignore[index] return result def duplicated(self, keep="first"): diff --git a/pandas/core/computation/expr.py b/pandas/core/computation/expr.py index c971551a7f400..88a25ad9996a0 100644 --- a/pandas/core/computation/expr.py +++ b/pandas/core/computation/expr.py @@ -659,7 +659,11 @@ def visit_Call(self, node, side=None, **kwargs): raise if res is None: - raise ValueError(f"Invalid function call {node.func.id}") + # pandas\core\computation\expr.py:663: error: "expr" has no + # attribute "id" [attr-defined] + raise ValueError( + f"Invalid function call {node.func.id}" # type: ignore[attr-defined] + ) if hasattr(res, "value"): res = res.value @@ -680,7 +684,12 @@ def visit_Call(self, node, side=None, **kwargs): for key in node.keywords: if not isinstance(key, ast.keyword): - raise ValueError(f"keyword error in function call '{node.func.id}'") + # pandas\core\computation\expr.py:684: error: "expr" has no + # attribute "id" [attr-defined] + raise ValueError( + "keyword error in function call " # type: ignore[attr-defined] + f"'{node.func.id}'" + ) if key.arg: kwargs[key.arg] = self.visit(key.value).value diff --git a/pandas/core/computation/ops.py b/pandas/core/computation/ops.py index 5759cd17476d6..74bee80c6c8a6 100644 --- a/pandas/core/computation/ops.py +++ b/pandas/core/computation/ops.py @@ -69,7 +69,9 @@ def __init__(self, name: str, is_local: Optional[bool] = None): class Term: def __new__(cls, name, env, side=None, encoding=None): klass = Constant if not isinstance(name, str) else cls - supr_new = super(Term, klass).__new__ + # pandas\core\computation\ops.py:72: error: Argument 2 for "super" not + # an instance of argument 1 [misc] + supr_new = super(Term, klass).__new__ # type: ignore[misc] return supr_new(klass) is_local: bool @@ -589,7 +591,8 @@ def __init__(self, func, args): self.func = func def __call__(self, env): - operands = [op(env) for op in self.operands] + # pandas\core\computation\ops.py:592: error: "Op" not callable [operator] + operands = [op(env) for op in self.operands] # type: ignore[operator] with np.errstate(all="ignore"): return self.func.func(*operands) diff --git a/pandas/core/computation/scope.py b/pandas/core/computation/scope.py index 7a9b8caa985e3..d2708da04b7e9 100644 --- a/pandas/core/computation/scope.py +++ b/pandas/core/computation/scope.py @@ -129,15 +129,29 @@ def __init__( # shallow copy here because we don't want to replace what's in # scope when we align terms (alignment accesses the underlying # numpy array of pandas objects) - self.scope = self.scope.new_child((global_dict or frame.f_globals).copy()) + + # pandas\core\computation\scope.py:132: error: Incompatible types + # in assignment (expression has type "ChainMap[str, Any]", variable + # has type "DeepChainMap[str, Any]") [assignment] + self.scope = self.scope.new_child( # type: ignore[assignment] + (global_dict or frame.f_globals).copy() + ) if not isinstance(local_dict, Scope): - self.scope = self.scope.new_child((local_dict or frame.f_locals).copy()) + # pandas\core\computation\scope.py:134: error: Incompatible + # types in assignment (expression has type "ChainMap[str, + # Any]", variable has type "DeepChainMap[str, Any]") + # [assignment] + self.scope = self.scope.new_child( # type: ignore[assignment] + (local_dict or frame.f_locals).copy() + ) finally: del frame # assumes that resolvers are going from outermost scope to inner if isinstance(local_dict, Scope): - resolvers += tuple(local_dict.resolvers.maps) + # pandas\core\computation\scope.py:140: error: Cannot determine + # type of 'resolvers' [has-type] + resolvers += tuple(local_dict.resolvers.maps) # type: ignore[has-type] self.resolvers = DeepChainMap(*resolvers) self.temps = {} @@ -224,7 +238,9 @@ def swapkey(self, old_key: str, new_key: str, new_value=None): for mapping in maps: if old_key in mapping: - mapping[new_key] = new_value + # pandas\core\computation\scope.py:228: error: Unsupported + # target for indexed assignment ("Mapping[Any, Any]") [index] + mapping[new_key] = new_value # type: ignore[index] return def _get_vars(self, stack, scopes: List[str]): @@ -243,7 +259,11 @@ def _get_vars(self, stack, scopes: List[str]): for scope, (frame, _, _, _, _, _) in variables: try: d = getattr(frame, "f_" + scope) - self.scope = self.scope.new_child(d) + # pandas\core\computation\scope.py:247: error: Incompatible + # types in assignment (expression has type "ChainMap[str, + # Any]", variable has type "DeepChainMap[str, Any]") + # [assignment] + self.scope = self.scope.new_child(d) # type: ignore[assignment] finally: # won't remove it, but DECREF it # in Py3 this probably isn't necessary since frame won't be @@ -310,5 +330,16 @@ def full_scope(self): vars : DeepChainMap All variables in this scope. """ - maps = [self.temps] + self.resolvers.maps + self.scope.maps + # pandas\core\computation\scope.py:314: error: Unsupported operand + # types for + ("List[Dict[Any, Any]]" and "List[Mapping[Any, Any]]") + # [operator] + + # pandas\core\computation\scope.py:314: error: Unsupported operand + # types for + ("List[Dict[Any, Any]]" and "List[Mapping[str, Any]]") + # [operator] + maps = ( + [self.temps] + + self.resolvers.maps # type: ignore[operator] + + self.scope.maps # type: ignore[operator] + ) return DeepChainMap(*maps) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index bfb633ae55095..80743f8cc924b 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3859,7 +3859,12 @@ def reindexer(value): value, len(self.index), infer_dtype ) else: - value = cast_scalar_to_array(len(self.index), value) + # pandas\core\frame.py:3827: error: Argument 1 to + # "cast_scalar_to_array" has incompatible type "int"; expected + # "Tuple[Any, ...]" [arg-type] + value = cast_scalar_to_array( + len(self.index), value # type: ignore[arg-type] + ) value = maybe_cast_to_datetime(value, infer_dtype) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 02fa7308e7ee8..8470ef7ba5efb 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -10706,7 +10706,9 @@ def _add_numeric_operations(cls): def any(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): return NDFrame.any(self, axis, bool_only, skipna, level, **kwargs) - cls.any = any + # pandas\core\generic.py:10725: error: Cannot assign to a method + # [assignment] + cls.any = any # type: ignore[assignment] @doc( _bool_doc, @@ -10721,7 +10723,14 @@ def any(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): return NDFrame.all(self, axis, bool_only, skipna, level, **kwargs) - cls.all = all + # pandas\core\generic.py:10719: error: Cannot assign to a method + # [assignment] + + # pandas\core\generic.py:10719: error: Incompatible types in assignment + # (expression has type "Callable[[Iterable[object]], bool]", variable + # has type "Callable[[NDFrame, Any, Any, Any, Any, KwArg(Any)], Any]") + # [assignment] + cls.all = all # type: ignore[assignment] @doc( desc="Return the mean absolute deviation of the values " @@ -10736,7 +10745,9 @@ def all(self, axis=0, bool_only=None, skipna=True, level=None, **kwargs): def mad(self, axis=None, skipna=None, level=None): return NDFrame.mad(self, axis, skipna, level) - cls.mad = mad + # pandas\core\generic.py:10736: error: Cannot assign to a method + # [assignment] + cls.mad = mad # type: ignore[assignment] @doc( _num_ddof_doc, @@ -10758,7 +10769,9 @@ def sem( ): return NDFrame.sem(self, axis, skipna, level, ddof, numeric_only, **kwargs) - cls.sem = sem + # pandas\core\generic.py:10758: error: Cannot assign to a method + # [assignment] + cls.sem = sem # type: ignore[assignment] @doc( _num_ddof_doc, @@ -10779,7 +10792,9 @@ def var( ): return NDFrame.var(self, axis, skipna, level, ddof, numeric_only, **kwargs) - cls.var = var + # pandas\core\generic.py:10779: error: Cannot assign to a method + # [assignment] + cls.var = var # type: ignore[assignment] @doc( _num_ddof_doc, @@ -10801,7 +10816,9 @@ def std( ): return NDFrame.std(self, axis, skipna, level, ddof, numeric_only, **kwargs) - cls.std = std + # pandas\core\generic.py:10801: error: Cannot assign to a method + # [assignment] + cls.std = std # type: ignore[assignment] @doc( _cnum_doc, @@ -10815,7 +10832,9 @@ def std( def cummin(self, axis=None, skipna=True, *args, **kwargs): return NDFrame.cummin(self, axis, skipna, *args, **kwargs) - cls.cummin = cummin + # pandas\core\generic.py:10815: error: Cannot assign to a method + # [assignment] + cls.cummin = cummin # type: ignore[assignment] @doc( _cnum_doc, @@ -10829,7 +10848,9 @@ def cummin(self, axis=None, skipna=True, *args, **kwargs): def cummax(self, axis=None, skipna=True, *args, **kwargs): return NDFrame.cummax(self, axis, skipna, *args, **kwargs) - cls.cummax = cummax + # pandas\core\generic.py:10829: error: Cannot assign to a method + # [assignment] + cls.cummax = cummax # type: ignore[assignment] @doc( _cnum_doc, @@ -10843,7 +10864,9 @@ def cummax(self, axis=None, skipna=True, *args, **kwargs): def cumsum(self, axis=None, skipna=True, *args, **kwargs): return NDFrame.cumsum(self, axis, skipna, *args, **kwargs) - cls.cumsum = cumsum + # pandas\core\generic.py:10843: error: Cannot assign to a method + # [assignment] + cls.cumsum = cumsum # type: ignore[assignment] @doc( _cnum_doc, @@ -10857,7 +10880,9 @@ def cumsum(self, axis=None, skipna=True, *args, **kwargs): def cumprod(self, axis=None, skipna=True, *args, **kwargs): return NDFrame.cumprod(self, axis, skipna, *args, **kwargs) - cls.cumprod = cumprod + # pandas\core\generic.py:10857: error: Cannot assign to a method + # [assignment] + cls.cumprod = cumprod # type: ignore[assignment] @doc( _num_doc, @@ -10883,7 +10908,9 @@ def sum( self, axis, skipna, level, numeric_only, min_count, **kwargs ) - cls.sum = sum + # pandas\core\generic.py:10883: error: Cannot assign to a method + # [assignment] + cls.sum = sum # type: ignore[assignment] @doc( _num_doc, @@ -10908,7 +10935,9 @@ def prod( self, axis, skipna, level, numeric_only, min_count, **kwargs ) - cls.prod = prod + # pandas\core\generic.py:10908: error: Cannot assign to a method + # [assignment] + cls.prod = prod # type: ignore[assignment] cls.product = prod @doc( @@ -10924,7 +10953,9 @@ def prod( def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.mean(self, axis, skipna, level, numeric_only, **kwargs) - cls.mean = mean + # pandas\core\generic.py:10924: error: Cannot assign to a method + # [assignment] + cls.mean = mean # type: ignore[assignment] @doc( _num_doc, @@ -10939,7 +10970,9 @@ def mean(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): def skew(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.skew(self, axis, skipna, level, numeric_only, **kwargs) - cls.skew = skew + # pandas\core\generic.py:10939: error: Cannot assign to a method + # [assignment] + cls.skew = skew # type: ignore[assignment] @doc( _num_doc, @@ -10957,7 +10990,9 @@ def skew(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): def kurt(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.kurt(self, axis, skipna, level, numeric_only, **kwargs) - cls.kurt = kurt + # pandas\core\generic.py:10957: error: Cannot assign to a method + # [assignment] + cls.kurt = kurt # type: ignore[assignment] cls.kurtosis = kurt @doc( @@ -10975,7 +11010,9 @@ def median( ): return NDFrame.median(self, axis, skipna, level, numeric_only, **kwargs) - cls.median = median + # pandas\core\generic.py:10975: error: Cannot assign to a method + # [assignment] + cls.median = median # type: ignore[assignment] @doc( _num_doc, @@ -10992,7 +11029,9 @@ def median( def max(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.max(self, axis, skipna, level, numeric_only, **kwargs) - cls.max = max + # pandas\core\generic.py:10992: error: Cannot assign to a method + # [assignment] + cls.max = max # type: ignore[assignment] @doc( _num_doc, @@ -11009,7 +11048,9 @@ def max(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): def min(self, axis=None, skipna=None, level=None, numeric_only=None, **kwargs): return NDFrame.min(self, axis, skipna, level, numeric_only, **kwargs) - cls.min = min + # pandas\core\generic.py:11009: error: Cannot assign to a method + # [assignment] + cls.min = min # type: ignore[assignment] @doc(Rolling) def rolling( @@ -11115,34 +11156,38 @@ def _inplace_method(self, other, op): return self def __iadd__(self, other): - return self._inplace_method(other, type(self).__add__) + return self._inplace_method(other, type(self).__add__) # type: ignore[operator] def __isub__(self, other): - return self._inplace_method(other, type(self).__sub__) + return self._inplace_method(other, type(self).__sub__) # type: ignore[operator] def __imul__(self, other): - return self._inplace_method(other, type(self).__mul__) + return self._inplace_method(other, type(self).__mul__) # type: ignore[operator] def __itruediv__(self, other): - return self._inplace_method(other, type(self).__truediv__) + return self._inplace_method( + other, type(self).__truediv__ # type: ignore[operator] + ) def __ifloordiv__(self, other): - return self._inplace_method(other, type(self).__floordiv__) + return self._inplace_method( + other, type(self).__floordiv__ # type: ignore[operator] + ) def __imod__(self, other): - return self._inplace_method(other, type(self).__mod__) + return self._inplace_method(other, type(self).__mod__) # type: ignore[operator] def __ipow__(self, other): - return self._inplace_method(other, type(self).__pow__) + return self._inplace_method(other, type(self).__pow__) # type: ignore[operator] def __iand__(self, other): - return self._inplace_method(other, type(self).__and__) + return self._inplace_method(other, type(self).__and__) # type: ignore[operator] def __ior__(self, other): - return self._inplace_method(other, type(self).__or__) + return self._inplace_method(other, type(self).__or__) # type: ignore[operator] def __ixor__(self, other): - return self._inplace_method(other, type(self).__xor__) + return self._inplace_method(other, type(self).__xor__) # type: ignore[operator] # ---------------------------------------------------------------------- # Misc methods diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py index 8e278dc81a8cc..f205226c03a53 100644 --- a/pandas/core/groupby/base.py +++ b/pandas/core/groupby/base.py @@ -49,7 +49,9 @@ def _gotitem(self, key, ndim, subset=None): """ # create a new object to prevent aliasing if subset is None: - subset = self.obj + # pandas\core\groupby\base.py:52: error: "GotItemMixin" has no + # attribute "obj" [attr-defined] + subset = self.obj # type: ignore[attr-defined] # we need to make a shallow copy of ourselves # with the same groupby @@ -57,11 +59,25 @@ def _gotitem(self, key, ndim, subset=None): # Try to select from a DataFrame, falling back to a Series try: - groupby = self._groupby[key] + # pandas\core\groupby\base.py:60: error: "GotItemMixin" has no + # attribute "_groupby" [attr-defined] + groupby = self._groupby[key] # type: ignore[attr-defined] except IndexError: - groupby = self._groupby + # pandas\core\groupby\base.py:62: error: "GotItemMixin" has no + # attribute "_groupby" [attr-defined] + groupby = self._groupby # type: ignore[attr-defined] - self = type(self)(subset, groupby=groupby, parent=self, **kwargs) + # pandas\core\groupby\base.py:64: error: Too many arguments for + # "GotItemMixin" [call-arg] + + # pandas\core\groupby\base.py:64: error: Unexpected keyword argument + # "groupby" for "GotItemMixin" [call-arg] + + # pandas\core\groupby\base.py:64: error: Unexpected keyword argument + # "parent" for "GotItemMixin" [call-arg] + self = type(self)( + subset, groupby=groupby, parent=self, **kwargs # type: ignore[call-arg] + ) self._reset_cache() if subset.ndim == 2 and (is_scalar(key) and key in subset or is_list_like(key)): self._selection = key diff --git a/pandas/core/groupby/grouper.py b/pandas/core/groupby/grouper.py index ff5379567f090..e8af9da30a298 100644 --- a/pandas/core/groupby/grouper.py +++ b/pandas/core/groupby/grouper.py @@ -307,7 +307,10 @@ def _get_grouper(self, obj, validate: bool = True): a tuple of binner, grouper, obj (possibly sorted) """ self._set_grouper(obj) - self.grouper, _, self.obj = get_grouper( + # pandas\core\groupby\grouper.py:310: error: Value of type variable + # "FrameOrSeries" of "get_grouper" cannot be "Optional[Any]" + # [type-var] + self.grouper, _, self.obj = get_grouper( # type: ignore[type-var] self.obj, [self.key], axis=self.axis, @@ -345,7 +348,9 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False): if getattr(self.grouper, "name", None) == key and isinstance( obj, ABCSeries ): - ax = self._grouper.take(obj.index) + # pandas\core\groupby\grouper.py:348: error: Item "None" of + # "Optional[Any]" has no attribute "take" [union-attr] + ax = self._grouper.take(obj.index) # type: ignore[union-attr] else: if key not in obj._info_axis: raise KeyError(f"The grouper name {key} is not found") @@ -379,7 +384,9 @@ def _set_grouper(self, obj: FrameOrSeries, sort: bool = False): @property def groups(self): - return self.grouper.groups + # pandas\core\groupby\grouper.py:382: error: Item "None" of + # "Optional[Any]" has no attribute "groups" [union-attr] + return self.grouper.groups # type: ignore[union-attr] def __repr__(self) -> str: attrs_list = ( diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 1be979b1b899c..859c26a40e50d 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -324,7 +324,9 @@ def _format_attrs(self): "categories", ibase.default_pprint(self.categories, max_seq_items=max_categories), ), - ("ordered", self.ordered), + # pandas\core\indexes\category.py:315: error: "CategoricalIndex" + # has no attribute "ordered" [attr-defined] + ("ordered", self.ordered), # type: ignore[attr-defined] ] if self.name is not None: attrs.append(("name", ibase.default_pprint(self.name))) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 2cb66557b3bab..40a6086f69f85 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -745,7 +745,11 @@ def intersection(self, other, sort=False): start = right[0] if end < start: - result = type(self)(data=[], dtype=self.dtype, freq=self.freq) + # pandas\core\indexes\datetimelike.py:758: error: Unexpected + # keyword argument "freq" for "DatetimeTimedeltaMixin" [call-arg] + result = type(self)( + data=[], dtype=self.dtype, freq=self.freq # type: ignore[call-arg] + ) else: lslice = slice(*left.slice_locs(start, end)) left_chunk = left._values[lslice] @@ -874,7 +878,11 @@ def _union(self, other, sort): i8self = Int64Index._simple_new(self.asi8) i8other = Int64Index._simple_new(other.asi8) i8result = i8self._union(i8other, sort=sort) - result = type(self)(i8result, dtype=self.dtype, freq="infer") + # pandas\core\indexes\datetimelike.py:887: error: Unexpected + # keyword argument "freq" for "DatetimeTimedeltaMixin" [call-arg] + result = type(self)( + i8result, dtype=self.dtype, freq="infer" # type: ignore[call-arg] + ) return result # -------------------------------------------------------------------- diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index aa16dc9752565..2739806a0f338 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -811,7 +811,9 @@ def slice_indexer(self, start=None, end=None, step=None, kind=None): end_casted = self._maybe_cast_slice_bound(end, "right", kind) mask = (self <= end_casted) & mask - indexer = mask.nonzero()[0][::step] + # pandas\core\indexes\datetimes.py:764: error: "bool" has no + # attribute "nonzero" [attr-defined] + indexer = mask.nonzero()[0][::step] # type: ignore[attr-defined] if len(indexer) == len(self): return slice(None) else: diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index 921c7aac2c85b..3103c27b35d74 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -220,7 +220,9 @@ def __getitem__(self, key): if result.ndim == 1: return type(self)(result, name=self.name) # Unpack to ndarray for MPL compat - result = result._data + # pandas\core\indexes\extension.py:220: error: "ExtensionArray" has + # no attribute "_data" [attr-defined] + result = result._data # type: ignore[attr-defined] # Includes cases where we get a 2D ndarray back for MPL compat deprecate_ndim_indexing(result) diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index 65e71a6109a5a..5a3f2b0853c4f 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -1449,7 +1449,9 @@ def _set_names(self, names, level=None, validate=True): raise TypeError( f"{type(self).__name__}.name must be a hashable type" ) - self._names[lev] = name + # pandas\core\indexes\multi.py:1448: error: Cannot determine type + # of '__setitem__' [has-type] + self._names[lev] = name # type: ignore[has-type] # If .levels has been accessed, the names in our cache will be stale. self._reset_cache() @@ -3506,8 +3508,13 @@ def intersection(self, other, sort=False): if uniq_tuples is None: other_uniq = set(rvals) seen = set() + # pandas\core\indexes\multi.py:3503: error: "add" of "set" does not + # return a value [func-returns-value] uniq_tuples = [ - x for x in lvals if x in other_uniq and not (x in seen or seen.add(x)) + x + for x in lvals + if x in other_uniq + and not (x in seen or seen.add(x)) # type: ignore[func-returns-value] ] if sort is None: diff --git a/pandas/core/resample.py b/pandas/core/resample.py index 78d217c4688b6..fccedd75c4531 100644 --- a/pandas/core/resample.py +++ b/pandas/core/resample.py @@ -94,7 +94,10 @@ def __init__(self, obj, groupby=None, axis=0, kind=None, **kwargs): self.as_index = True self.exclusions = set() self.binner = None - self.grouper = None + # pandas\core\resample.py:96: error: Incompatible types in assignment + # (expression has type "None", variable has type "BaseGrouper") + # [assignment] + self.grouper = None # type: ignore[assignment] if self.groupby is not None: self.groupby._set_grouper(self._convert_obj(obj), sort=True) @@ -410,14 +413,21 @@ def _apply_loffset(self, result): result : Series or DataFrame the result of resample """ + # pandas\core\resample.py:409: error: Cannot determine type of + # 'loffset' [has-type] needs_offset = ( - isinstance(self.loffset, (DateOffset, timedelta, np.timedelta64)) + isinstance( + self.loffset, # type: ignore[has-type] + (DateOffset, timedelta, np.timedelta64), + ) and isinstance(result.index, DatetimeIndex) and len(result.index) > 0 ) if needs_offset: - result.index = result.index + self.loffset + # pandas\core\resample.py:415: error: Cannot determine type of + # 'loffset' [has-type] + result.index = result.index + self.loffset # type: ignore[has-type] self.loffset = None return result @@ -852,7 +862,9 @@ def std(self, ddof=1, *args, **kwargs): Standard deviation of values within each group. """ nv.validate_resampler_func("std", args, kwargs) - return self._downsample("std", ddof=ddof) + # pandas\core\resample.py:850: error: Unexpected keyword argument + # "ddof" for "_downsample" [call-arg] + return self._downsample("std", ddof=ddof) # type: ignore[call-arg] def var(self, ddof=1, *args, **kwargs): """ @@ -869,7 +881,9 @@ def var(self, ddof=1, *args, **kwargs): Variance of values within each group. """ nv.validate_resampler_func("var", args, kwargs) - return self._downsample("var", ddof=ddof) + # pandas\core\resample.py:867: error: Unexpected keyword argument + # "ddof" for "_downsample" [call-arg] + return self._downsample("var", ddof=ddof) # type: ignore[call-arg] @doc(GroupBy.size) def size(self): @@ -927,7 +941,12 @@ def quantile(self, q=0.5, **kwargs): Return a DataFrame, where the coulmns are groupby columns, and the values are its quantiles. """ - return self._downsample("quantile", q=q, **kwargs) + # pandas\core\resample.py:920: error: Unexpected keyword argument "q" + # for "_downsample" [call-arg] + + # pandas\core\resample.py:920: error: Too many arguments for + # "_downsample" [call-arg] + return self._downsample("quantile", q=q, **kwargs) # type: ignore[call-arg] # downsample methods @@ -979,7 +998,9 @@ def __init__(self, obj, *args, **kwargs): for attr in self._attributes: setattr(self, attr, kwargs.get(attr, getattr(parent, attr))) - super().__init__(None) + # pandas\core\resample.py:972: error: Too many arguments for "__init__" + # of "object" [call-arg] + super().__init__(None) # type: ignore[call-arg] self._groupby = groupby self._groupby.mutated = True self._groupby.grouper.mutated = True @@ -1044,7 +1065,12 @@ def _downsample(self, how, **kwargs): # do we have a regular frequency if ax.freq is not None or ax.inferred_freq is not None: - if len(self.grouper.binlabels) > len(ax) and how is None: + # pandas\core\resample.py:1037: error: "BaseGrouper" has no + # attribute "binlabels" [attr-defined] + if ( + len(self.grouper.binlabels) > len(ax) # type: ignore[attr-defined] + and how is None + ): # let's do an asfreq return self.asfreq() diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index aa883d518f8d1..d49e834fedb2d 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -965,7 +965,10 @@ def _get_merge_keys(self): """ left_keys = [] right_keys = [] - join_names = [] + # pandas\core\reshape\merge.py:966: error: Need type annotation for + # 'join_names' (hint: "join_names: List[<type>] = ...") + # [var-annotated] + join_names = [] # type: ignore[var-annotated] right_drop = [] left_drop = [] diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 03c61c3ed8376..dd30bf37793d0 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -755,7 +755,10 @@ def __init__( self.mode = mode def __fspath__(self): - return stringify_path(self.path) + # pandas\io\excel\_base.py:744: error: Argument 1 to "stringify_path" + # has incompatible type "Optional[Any]"; expected "Union[str, Path, + # IO[Any], IOBase]" [arg-type] + return stringify_path(self.path) # type: ignore[arg-type] def _get_sheet_name(self, sheet_name): if sheet_name is None: diff --git a/pandas/io/formats/console.py b/pandas/io/formats/console.py index 50e69f7e8b435..ab9c9fe995008 100644 --- a/pandas/io/formats/console.py +++ b/pandas/io/formats/console.py @@ -69,7 +69,9 @@ def check_main(): return not hasattr(main, "__file__") or get_option("mode.sim_interactive") try: - return __IPYTHON__ or check_main() + # pandas\io\formats\console.py:72: error: Name '__IPYTHON__' is not + # defined [name-defined] + return __IPYTHON__ or check_main() # type: ignore[name-defined] except NameError: return check_main() @@ -83,7 +85,9 @@ def in_ipython_frontend(): bool """ try: - ip = get_ipython() + # pandas\io\formats\console.py:86: error: Name 'get_ipython' is not + # defined [name-defined] + ip = get_ipython() # type: ignore[name-defined] return "zmq" in str(type(ip)).lower() except NameError: pass diff --git a/pandas/io/formats/excel.py b/pandas/io/formats/excel.py index 5013365896fb2..9793f7a1e4613 100644 --- a/pandas/io/formats/excel.py +++ b/pandas/io/formats/excel.py @@ -590,10 +590,17 @@ def _format_header_regular(self): colnames = self.columns if has_aliases: - if len(self.header) != len(self.columns): + # pandas\io\formats\excel.py:593: error: Argument 1 to "len" + # has incompatible type "Union[Sequence[Optional[Hashable]], + # bool]"; expected "Sized" [arg-type] + if len(self.header) != len(self.columns): # type: ignore[arg-type] + # pandas\io\formats\excel.py:595: error: Argument 1 to + # "len" has incompatible type + # "Union[Sequence[Optional[Hashable]], bool]"; expected + # "Sized" [arg-type] raise ValueError( - f"Writing {len(self.columns)} cols but got {len(self.header)} " - "aliases" + f"Writing {len(self.columns)} " # type: ignore[arg-type] + f"cols but got {len(self.header)} aliases" ) else: colnames = self.header @@ -615,7 +622,10 @@ def _format_header(self): "" ] * len(self.columns) if reduce(lambda x, y: x and y, map(lambda x: x != "", row)): - gen2 = ( + # pandas\io\formats\excel.py:618: error: Incompatible types in + # assignment (expression has type "Generator[ExcelCell, None, + # None]", variable has type "Tuple[]") [assignment] + gen2 = ( # type: ignore[assignment] ExcelCell(self.rowcounter, colindex, val, self.header_style) for colindex, val in enumerate(row) ) @@ -805,7 +815,12 @@ def write( if isinstance(writer, ExcelWriter): need_save = False else: - writer = ExcelWriter(stringify_path(writer), engine=engine) + # pandas\io\formats\excel.py:808: error: Cannot instantiate + # abstract class 'ExcelWriter' with abstract attributes 'engine', + # 'save', 'supported_extensions' and 'write_cells' [abstract] + writer = ExcelWriter( # type: ignore[abstract] + stringify_path(writer), engine=engine + ) need_save = True formatted_cells = self.get_formatted_cells() diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index 43e76d0aef490..5b69ef4eba26e 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -1342,7 +1342,16 @@ def _value_formatter( def base_formatter(v): assert float_format is not None # for mypy - return float_format(value=v) if notna(v) else self.na_rep + # pandas\io\formats\format.py:1411: error: "str" not callable + # [operator] + + # pandas\io\formats\format.py:1411: error: Unexpected keyword + # argument "value" for "__call__" of "EngFormatter" [call-arg] + return ( + float_format(value=v) # type: ignore[operator,call-arg] + if notna(v) + else self.na_rep + ) else: diff --git a/pandas/io/parsers.py b/pandas/io/parsers.py index e4895d280c241..5725e2304e1d2 100644 --- a/pandas/io/parsers.py +++ b/pandas/io/parsers.py @@ -851,7 +851,10 @@ def _get_options_with_defaults(self, engine): options[argname] = value if engine == "python-fwf": - for argname, default in _fwf_defaults.items(): + # pandas\io\parsers.py:907: error: Incompatible types in assignment + # (expression has type "object", variable has type "Union[int, str, + # None]") [assignment] + for argname, default in _fwf_defaults.items(): # type: ignore[assignment] options[argname] = kwds.get(argname, default) return options @@ -1035,9 +1038,18 @@ def __next__(self): def _make_engine(self, engine="c"): mapping = { - "c": CParserWrapper, - "python": PythonParser, - "python-fwf": FixedWidthFieldParser, + # pandas\io\parsers.py:1099: error: Dict entry 0 has incompatible + # type "str": "Type[CParserWrapper]"; expected "str": + # "Type[ParserBase]" [dict-item] + "c": CParserWrapper, # type: ignore[dict-item] + # pandas\io\parsers.py:1100: error: Dict entry 1 has incompatible + # type "str": "Type[PythonParser]"; expected "str": + # "Type[ParserBase]" [dict-item] + "python": PythonParser, # type: ignore[dict-item] + # pandas\io\parsers.py:1101: error: Dict entry 2 has incompatible + # type "str": "Type[FixedWidthFieldParser]"; expected "str": + # "Type[ParserBase]" [dict-item] + "python-fwf": FixedWidthFieldParser, # type: ignore[dict-item] } try: klass = mapping[engine] @@ -1394,7 +1406,9 @@ def _validate_parse_dates_presence(self, columns: List[str]) -> None: ) def close(self): - self.handles.close() + # pandas\io\parsers.py:1409: error: "ParserBase" has no attribute + # "handles" [attr-defined] + self.handles.close() # type: ignore[attr-defined] @property def _has_complex_date_col(self): @@ -1490,7 +1504,9 @@ def _maybe_dedup_names(self, names): # would be nice! if self.mangle_dupe_cols: names = list(names) # so we can index - counts = defaultdict(int) + # pandas\io\parsers.py:1559: error: Need type annotation for + # 'counts' [var-annotated] + counts = defaultdict(int) # type: ignore[var-annotated] is_potential_mi = _is_potential_multi_index(names, self.index_col) for i, col in enumerate(names): @@ -1535,7 +1551,9 @@ def _make_index(self, data, alldata, columns, indexnamerow=False): # add names for the index if indexnamerow: coffset = len(indexnamerow) - len(columns) - index = index.set_names(indexnamerow[:coffset]) + # pandas\io\parsers.py:1604: error: Item "None" of "Optional[Any]" + # has no attribute "set_names" [union-attr] + index = index.set_names(indexnamerow[:coffset]) # type: ignore[union-attr] # maybe create a mi on the columns columns = self._maybe_make_multi_index_columns(columns, self.col_names) @@ -1609,7 +1627,9 @@ def _agg_index(self, index, try_parse_dates=True) -> Index: col_na_fvalues = set() if isinstance(self.na_values, dict): - col_name = self.index_names[i] + # pandas\io\parsers.py:1678: error: Value of type + # "Optional[Any]" is not indexable [index] + col_name = self.index_names[i] # type: ignore[index] if col_name is not None: col_na_values, col_na_fvalues = _get_na_values( col_name, self.na_values, self.na_fvalues, self.keep_default_na @@ -1840,7 +1860,30 @@ def __init__(self, src, **kwds): kwds.pop("memory_map", None) kwds.pop("compression", None) if self.handles.is_mmap and hasattr(self.handles.handle, "mmap"): - self.handles.handle = self.handles.handle.mmap + # pandas\io\parsers.py:1861: error: Item "IO[Any]" of + # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, + # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + + # pandas\io\parsers.py:1861: error: Item "RawIOBase" of + # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, + # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + + # pandas\io\parsers.py:1861: error: Item "BufferedIOBase" of + # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, + # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + + # pandas\io\parsers.py:1861: error: Item "TextIOBase" of + # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, + # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + + # pandas\io\parsers.py:1861: error: Item "TextIOWrapper" of + # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, + # TextIOWrapper, mmap]" has no attribute "mmap" [union-attr] + + # pandas\io\parsers.py:1861: error: Item "mmap" of "Union[IO[Any], + # RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap]" has + # no attribute "mmap" [union-attr] + self.handles.handle = self.handles.handle.mmap # type: ignore[union-attr] # #2442 kwds["allow_leading_cols"] = self.index_col is not False @@ -1924,7 +1967,12 @@ def __init__(self, src, **kwds): self.index_names = index_names if self._reader.header is None and not passed_names: - self.index_names = [None] * len(self.index_names) + # pandas\io\parsers.py:1997: error: Argument 1 to "len" has + # incompatible type "Optional[Any]"; expected "Sized" + # [arg-type] + self.index_names = [None] * len( + self.index_names # type: ignore[arg-type] + ) self._implicit_index = self._reader.leading_cols > 0 @@ -1956,14 +2004,20 @@ def _set_noconvert_columns(self): usecols = self.names[:] else: # Usecols is empty. - usecols = None + + # pandas\io\parsers.py:2030: error: Incompatible types in + # assignment (expression has type "None", variable has type + # "List[Any]") [assignment] + usecols = None # type: ignore[assignment] def _set(x): if usecols is not None and is_integer(x): x = usecols[x] if not is_integer(x): - x = names.index(x) + # pandas\io\parsers.py:2037: error: Item "None" of + # "Optional[Any]" has no attribute "index" [union-attr] + x = names.index(x) # type: ignore[union-attr] self._reader.set_noconvert(x) @@ -2057,7 +2111,11 @@ def read(self, nrows=None): data = sorted(data.items()) # ugh, mutation - names = list(self.orig_names) + + # pandas\io\parsers.py:2131: error: Argument 1 to "list" has + # incompatible type "Optional[Any]"; expected "Iterable[Any]" + # [arg-type] + names = list(self.orig_names) # type: ignore[arg-type] names = self._maybe_dedup_names(names) if self.usecols is not None: @@ -2391,7 +2449,11 @@ def _read(): reader = _read() - self.data = reader + # pandas\io\parsers.py:2427: error: Incompatible types in assignment + # (expression has type "_reader", variable has type "Union[IO[Any], + # RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, mmap, None]") + # [assignment] + self.data = reader # type: ignore[assignment] def read(self, rows=None): try: @@ -2405,7 +2467,10 @@ def read(self, rows=None): # done with first read, next time raise StopIteration self._first_chunk = False - columns = list(self.orig_names) + # pandas\io\parsers.py:2480: error: Argument 1 to "list" has + # incompatible type "Optional[Any]"; expected "Iterable[Any]" + # [arg-type] + columns = list(self.orig_names) # type: ignore[arg-type] if not len(content): # pragma: no cover # DataFrame with the right metadata, even though it's length 0 names = self._maybe_dedup_names(self.orig_names) @@ -2453,7 +2518,9 @@ def _exclude_implicit_index(self, alldata): # legacy def get_chunk(self, size=None): if size is None: - size = self.chunksize + # pandas\io\parsers.py:2528: error: "PythonParser" has no attribute + # "chunksize" [attr-defined] + size = self.chunksize # type: ignore[attr-defined] return self.read(rows=size) def _convert_data(self, data): @@ -2462,8 +2529,15 @@ def _clean_mapping(mapping): """converts col numbers to names""" clean = {} for col, v in mapping.items(): - if isinstance(col, int) and col not in self.orig_names: - col = self.orig_names[col] + # pandas\io\parsers.py:2537: error: Unsupported right operand + # type for in ("Optional[Any]") [operator] + if ( + isinstance(col, int) + and col not in self.orig_names # type: ignore[operator] + ): + # pandas\io\parsers.py:2538: error: Value of type + # "Optional[Any]" is not indexable [index] + col = self.orig_names[col] # type: ignore[index] clean[col] = v return clean @@ -2483,8 +2557,15 @@ def _clean_mapping(mapping): na_value = self.na_values[col] na_fvalue = self.na_fvalues[col] - if isinstance(col, int) and col not in self.orig_names: - col = self.orig_names[col] + # pandas\io\parsers.py:2558: error: Unsupported right operand + # type for in ("Optional[Any]") [operator] + if ( + isinstance(col, int) + and col not in self.orig_names # type: ignore[operator] + ): + # pandas\io\parsers.py:2559: error: Value of type + # "Optional[Any]" is not indexable [index] + col = self.orig_names[col] # type: ignore[index] clean_na_values[col] = na_value clean_na_fvalues[col] = na_fvalue @@ -2505,7 +2586,10 @@ def _infer_columns(self): names = self.names num_original_columns = 0 clear_buffer = True - unnamed_cols = set() + # pandas\io\parsers.py:2580: error: Need type annotation for + # 'unnamed_cols' (hint: "unnamed_cols: Set[<type>] = ...") + # [var-annotated] + unnamed_cols = set() # type: ignore[var-annotated] if self.header is not None: header = self.header @@ -2519,7 +2603,9 @@ def _infer_columns(self): have_mi_columns = False header = [header] - columns = [] + # pandas\io\parsers.py:2594: error: Need type annotation for + # 'columns' (hint: "columns: List[<type>] = ...") [var-annotated] + columns = [] # type: ignore[var-annotated] for level, hr in enumerate(header): try: line = self._buffered_line() @@ -2564,7 +2650,9 @@ def _infer_columns(self): this_columns.append(c) if not have_mi_columns and self.mangle_dupe_cols: - counts = defaultdict(int) + # pandas\io\parsers.py:2639: error: Need type annotation + # for 'counts' [var-annotated] + counts = defaultdict(int) # type: ignore[var-annotated] for i, col in enumerate(this_columns): cur_count = counts[col] @@ -2588,10 +2676,16 @@ def _infer_columns(self): if lc != unnamed_count and lc - ic > unnamed_count: clear_buffer = False - this_columns = [None] * lc + # pandas\io\parsers.py:2663: error: List item 0 has + # incompatible type "None"; expected "str" + # [list-item] + this_columns = [None] * lc # type: ignore[list-item] self.buf = [self.buf[-1]] - columns.append(this_columns) + # pandas\io\parsers.py:2666: error: Argument 1 to "append" of + # "list" has incompatible type "List[str]"; expected + # "List[None]" [arg-type] + columns.append(this_columns) # type: ignore[arg-type] unnamed_cols.update({this_columns[i] for i in this_unnamed_cols}) if len(columns) == 1: @@ -2636,9 +2730,19 @@ def _infer_columns(self): if not names: if self.prefix: - columns = [[f"{self.prefix}{i}" for i in range(ncols)]] + # pandas\io\parsers.py:2711: error: List comprehension has + # incompatible type List[str]; expected List[None] [misc] + columns = [ + [ + f"{self.prefix}{i}" # type: ignore[misc] + for i in range(ncols) + ] + ] else: - columns = [list(range(ncols))] + # pandas\io\parsers.py:2713: error: Argument 1 to "list" + # has incompatible type "range"; expected "Iterable[None]" + # [arg-type] + columns = [list(range(ncols))] # type: ignore[arg-type] columns = self._handle_usecols(columns, columns[0]) else: if self.usecols is None or len(names) >= num_original_columns: @@ -2790,7 +2894,10 @@ def _next_line(self): else: while self.skipfunc(self.pos): self.pos += 1 - next(self.data) + # pandas\io\parsers.py:2865: error: Argument 1 to "next" has + # incompatible type "Optional[Any]"; expected "Iterator[Any]" + # [arg-type] + next(self.data) # type: ignore[arg-type] while True: orig_line = self._next_iter_line(row_num=self.pos + 1) @@ -2851,7 +2958,10 @@ def _next_iter_line(self, row_num): row_num : The row number of the line being parsed. """ try: - return next(self.data) + # pandas\io\parsers.py:2926: error: Argument 1 to "next" has + # incompatible type "Optional[Any]"; expected "Iterator[Any]" + # [arg-type] + return next(self.data) # type: ignore[arg-type] except csv.Error as e: if self.warn_bad_lines or self.error_bad_lines: msg = str(e) @@ -3084,12 +3194,19 @@ def _rows_to_cols(self, content): for i, a in enumerate(zipped_content) if ( i < len(self.index_col) - or i - len(self.index_col) in self._col_indices + # pandas\io\parsers.py:3159: error: Unsupported right + # operand type for in ("Optional[Any]") [operator] + or i - len(self.index_col) # type: ignore[operator] + in self._col_indices ) ] else: zipped_content = [ - a for i, a in enumerate(zipped_content) if i in self._col_indices + # pandas\io\parsers.py:3164: error: Unsupported right + # operand type for in ("Optional[Any]") [operator] + a + for i, a in enumerate(zipped_content) + if i in self._col_indices # type: ignore[operator] ] return zipped_content @@ -3134,7 +3251,10 @@ def _get_lines(self, rows=None): try: if rows is not None: for _ in range(rows): - new_rows.append(next(self.data)) + # pandas\io\parsers.py:3209: error: Argument 1 to + # "next" has incompatible type "Optional[Any]"; + # expected "Iterator[Any]" [arg-type] + new_rows.append(next(self.data)) # type: ignore[arg-type] lines.extend(new_rows) else: rows = 0 @@ -3312,7 +3432,9 @@ def _clean_na_values(na_values, keep_default_na=True): na_values = STR_NA_VALUES else: na_values = set() - na_fvalues = set() + # pandas\io\parsers.py:3387: error: Need type annotation for + # 'na_fvalues' (hint: "na_fvalues: Set[<type>] = ...") [var-annotated] + na_fvalues = set() # type: ignore[var-annotated] elif isinstance(na_values, dict): old_na_values = na_values.copy() na_values = {} # Prevent aliasing. @@ -3329,7 +3451,12 @@ def _clean_na_values(na_values, keep_default_na=True): v = set(v) | STR_NA_VALUES na_values[k] = v - na_fvalues = {k: _floatify_na_values(v) for k, v in na_values.items()} + # pandas\io\parsers.py:3404: error: Incompatible types in assignment + # (expression has type "Dict[Any, Any]", variable has type "Set[Any]") + # [assignment] + na_fvalues = { # type: ignore[assignment] + k: _floatify_na_values(v) for k, v in na_values.items() + } else: if not is_list_like(na_values): na_values = [na_values] @@ -3370,7 +3497,10 @@ def _clean_index_names(columns, index_col, unnamed_cols): # Only clean index names that were placeholders. for i, name in enumerate(index_names): if isinstance(name, str) and name in unnamed_cols: - index_names[i] = None + # pandas\io\parsers.py:3445: error: No overload variant of + # "__setitem__" of "list" matches argument types "int", "None" + # [call-overload] + index_names[i] = None # type: ignore[call-overload] return index_names, columns, index_col @@ -3447,11 +3577,15 @@ def _stringify_na_values(na_values): result.append(f"{v}.0") result.append(str(v)) - result.append(v) + # pandas\io\parsers.py:3522: error: Argument 1 to "append" of + # "list" has incompatible type "float"; expected "str" [arg-type] + result.append(v) # type: ignore[arg-type] except (TypeError, ValueError, OverflowError): pass try: - result.append(int(x)) + # pandas\io\parsers.py:3526: error: Argument 1 to "append" of + # "list" has incompatible type "int"; expected "str" [arg-type] + result.append(int(x)) # type: ignore[arg-type] except (TypeError, ValueError, OverflowError): pass return set(result) @@ -3622,7 +3756,11 @@ def __init__(self, f, **kwds): PythonParser.__init__(self, f, **kwds) def _make_reader(self, f): - self.data = FixedWidthReader( + # pandas\io\parsers.py:3730: error: Incompatible types in assignment + # (expression has type "FixedWidthReader", variable has type + # "Union[IO[Any], RawIOBase, BufferedIOBase, TextIOBase, TextIOWrapper, + # mmap, None]") [assignment] + self.data = FixedWidthReader( # type: ignore[assignment] f, self.colspecs, self.delimiter, diff --git a/pandas/plotting/_matplotlib/core.py b/pandas/plotting/_matplotlib/core.py index 6c9924e0ada79..2501d84de4459 100644 --- a/pandas/plotting/_matplotlib/core.py +++ b/pandas/plotting/_matplotlib/core.py @@ -577,8 +577,20 @@ def _make_legend(self): if self.legend: if self.legend == "reverse": - self.legend_handles = reversed(self.legend_handles) - self.legend_labels = reversed(self.legend_labels) + # pandas\plotting\_matplotlib\core.py:578: error: + # Incompatible types in assignment (expression has type + # "Iterator[Any]", variable has type "List[Any]") + # [assignment] + self.legend_handles = reversed( # type: ignore[assignment] + self.legend_handles + ) + # pandas\plotting\_matplotlib\core.py:579: error: + # Incompatible types in assignment (expression has type + # "Iterator[Optional[Hashable]]", variable has type + # "List[Optional[Hashable]]") [assignment] + self.legend_labels = reversed( # type: ignore[assignment] + self.legend_labels + ) handles += self.legend_handles labels += self.legend_labels @@ -1101,7 +1113,11 @@ def _make_plot(self): it = self._iter_data(data=data, keep_index=True) else: x = self._get_xticks(convert_period=True) - plotf = self._plot + # pandas\plotting\_matplotlib\core.py:1100: error: Incompatible + # types in assignment (expression has type "Callable[[Any, Any, + # Any, Any, Any, Any, KwArg(Any)], Any]", variable has type + # "Callable[[Any, Any, Any, Any, KwArg(Any)], Any]") [assignment] + plotf = self._plot # type: ignore[assignment] it = self._iter_data() stacking_id = self._get_stacking_id() @@ -1547,7 +1563,10 @@ def blank_labeler(label, value): if labels is not None: blabels = [blank_labeler(l, value) for l, value in zip(labels, y)] else: - blabels = None + # pandas\plotting\_matplotlib\core.py:1546: error: Incompatible + # types in assignment (expression has type "None", variable has + # type "List[Any]") [assignment] + blabels = None # type: ignore[assignment] results = ax.pie(y, labels=blabels, **kwds) if kwds.get("autopct", None) is not None: diff --git a/pandas/plotting/_misc.py b/pandas/plotting/_misc.py index 6e473bf5b182c..58f44104b99d6 100644 --- a/pandas/plotting/_misc.py +++ b/pandas/plotting/_misc.py @@ -530,7 +530,9 @@ def reset(self): ------- None """ - self.__init__() + # pandas\plotting\_misc.py:533: error: Cannot access "__init__" + # directly [misc] + self.__init__() # type: ignore[misc] def _get_canonical_key(self, key): return self._ALIASES.get(key, key) diff --git a/setup.cfg b/setup.cfg index b1f423c12ebf4..c83a83d599f6c 100644 --- a/setup.cfg +++ b/setup.cfg @@ -114,10 +114,11 @@ skip_glob = env, skip = pandas/__init__.py [mypy] -ignore_missing_imports=True -no_implicit_optional=True -check_untyped_defs=True -strict_equality=True +platform = linux-64 +ignore_missing_imports = True +no_implicit_optional = True +check_untyped_defs = True +strict_equality = True warn_redundant_casts = True warn_unused_ignores = True show_error_codes = True @@ -125,86 +126,8 @@ show_error_codes = True [mypy-pandas.tests.*] check_untyped_defs=False -[mypy-pandas._testing] -check_untyped_defs=False - [mypy-pandas._version] check_untyped_defs=False -[mypy-pandas.core.apply] -check_untyped_defs=False - -[mypy-pandas.core.arrays.datetimelike] -check_untyped_defs=False - -[mypy-pandas.core.arrays.string_] -check_untyped_defs=False - -[mypy-pandas.core.base] -check_untyped_defs=False - -[mypy-pandas.core.computation.expr] -check_untyped_defs=False - -[mypy-pandas.core.computation.ops] -check_untyped_defs=False - -[mypy-pandas.core.computation.scope] -check_untyped_defs=False - -[mypy-pandas.core.frame] -check_untyped_defs=False - -[mypy-pandas.core.generic] -check_untyped_defs=False - -[mypy-pandas.core.groupby.base] -check_untyped_defs=False - -[mypy-pandas.core.groupby.grouper] -check_untyped_defs=False - -[mypy-pandas.core.indexes.category] -check_untyped_defs=False - -[mypy-pandas.core.indexes.datetimelike] -check_untyped_defs=False - -[mypy-pandas.core.indexes.datetimes] -check_untyped_defs=False - -[mypy-pandas.core.indexes.extension] -check_untyped_defs=False - -[mypy-pandas.core.indexes.multi] -check_untyped_defs=False - -[mypy-pandas.core.resample] -check_untyped_defs=False - -[mypy-pandas.core.reshape.merge] -check_untyped_defs=False - [mypy-pandas.io.clipboard] check_untyped_defs=False - -[mypy-pandas.io.excel._base] -check_untyped_defs=False - -[mypy-pandas.io.formats.console] -check_untyped_defs=False - -[mypy-pandas.io.formats.excel] -check_untyped_defs=False - -[mypy-pandas.io.formats.format] -check_untyped_defs=False - -[mypy-pandas.io.parsers] -check_untyped_defs=False - -[mypy-pandas.plotting._matplotlib.core] -check_untyped_defs=False - -[mypy-pandas.plotting._misc] -check_untyped_defs=False
@jbrockmendel has recently addressed many of the modules that were not previously checked. There are now many less modules outstanding. There has been a concern in the past that if we add ignores, the issues may not be addressed and sit in the codebase. (from previous experience with other linting tools) There are however pros to including the ignores. The issues are visible to people working on the relevant code and when reviewing the code. **Also as mypy will be checking the relevant modules, PRs changing these modules will have additional static checking on ci and the chance of regression/errors is likely reduced.** IMO the pros always outweighed the cons, but now that there are less ignores involved (admittedly the number is still not trivial), I think it is appropriate to reconsider this approach. One caveat, NumPy types currently resolve to `Any` and we have not yet discussed how we will 'switch' to using NumPy types #36092. (reverting to using `check_untyped_defs=False` on some modules could make the switch more managable) Another possible upside, is in the review of typing PRs to fix these issues. Reviewers of typing PRs cannot see explicitly see why changes are being made and a typical reviewer is normally suspicious of any changes to the codebase. This can lead to long review cycles of typing PRs. I'm not sure if having the resolved mypy errors in the diff will help, but if the hypothesis is correct could be an argument for following a similar approach for resolving the numerous errors that will be reported once NumPy types no longer resolve to `Any`
https://api.github.com/repos/pandas-dev/pandas/pulls/37556
2020-11-01T11:27:00Z
2020-11-09T12:51:09Z
2020-11-09T12:51:09Z
2020-11-09T13:21:17Z
Fixed the documentation for pandas.DataFrame.set_index inplace parameter
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ba2f11c87369f..a1c17c2ecfc32 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -4525,7 +4525,7 @@ def set_index( append : bool, default False Whether to append columns to existing index. inplace : bool, default False - Modify the DataFrame in place (do not create a new object). + If True, modifies the DataFrame in place (do not create a new object). verify_integrity : bool, default False Check the new index for duplicates. Otherwise defer the check until necessary. Setting to False will improve the performance of this
Fixed the documentation for `pandas.DataFrame.set_index` 's `inplace` parameter. Added proper explanation for True case.
https://api.github.com/repos/pandas-dev/pandas/pulls/37555
2020-11-01T06:33:52Z
2020-11-17T17:27:37Z
2020-11-17T17:27:37Z
2020-11-17T17:27:47Z
REF: simplify Index.take, MultiIndex.take
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 48dcdfb3ecfff..3d23d454c6a58 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -733,44 +733,36 @@ def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs): if kwargs: nv.validate_take(tuple(), kwargs) indices = ensure_platform_int(indices) - if self._can_hold_na: - taken = self._assert_take_fillable( - self._values, - indices, - allow_fill=allow_fill, - fill_value=fill_value, - na_value=self._na_value, - ) - else: - if allow_fill and fill_value is not None: - cls_name = type(self).__name__ - raise ValueError( - f"Unable to fill values because {cls_name} cannot contain NA" - ) - taken = self._values.take(indices) + allow_fill = self._maybe_disallow_fill(allow_fill, fill_value, indices) + + # Note: we discard fill_value and use self._na_value, only relevant + # in the case where allow_fill is True and fill_value is not None + taken = algos.take( + self._values, indices, allow_fill=allow_fill, fill_value=self._na_value + ) return self._shallow_copy(taken) - def _assert_take_fillable( - self, values, indices, allow_fill=True, fill_value=None, na_value=np.nan - ): + def _maybe_disallow_fill(self, allow_fill: bool, fill_value, indices) -> bool: """ - Internal method to handle NA filling of take. + We only use pandas-style take when allow_fill is True _and_ + fill_value is not None. """ - indices = ensure_platform_int(indices) - - # only fill if we are passing a non-None fill_value if allow_fill and fill_value is not None: - if (indices < -1).any(): + # only fill if we are passing a non-None fill_value + if self._can_hold_na: + if (indices < -1).any(): + raise ValueError( + "When allow_fill=True and fill_value is not None, " + "all indices must be >= -1" + ) + else: + cls_name = type(self).__name__ raise ValueError( - "When allow_fill=True and fill_value is not None, " - "all indices must be >= -1" + f"Unable to fill values because {cls_name} cannot contain NA" ) - taken = algos.take( - values, indices, allow_fill=allow_fill, fill_value=na_value - ) else: - taken = algos.take(values, indices, allow_fill=False, fill_value=na_value) - return taken + allow_fill = False + return allow_fill _index_shared_docs[ "repeat" diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index bdd3afe747d1d..33304e3fd1916 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -2018,29 +2018,13 @@ def __getitem__(self, key): def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs): nv.validate_take(tuple(), kwargs) indices = ensure_platform_int(indices) - taken = self._assert_take_fillable( - self.codes, - indices, - allow_fill=allow_fill, - fill_value=fill_value, - na_value=-1, - ) - return MultiIndex( - levels=self.levels, codes=taken, names=self.names, verify_integrity=False - ) - def _assert_take_fillable( - self, values, indices, allow_fill=True, fill_value=None, na_value=None - ): - """ Internal method to handle NA filling of take """ # only fill if we are passing a non-None fill_value - if allow_fill and fill_value is not None: - if (indices < -1).any(): - msg = ( - "When allow_fill=True and fill_value is not None, " - "all indices must be >= -1" - ) - raise ValueError(msg) + allow_fill = self._maybe_disallow_fill(allow_fill, fill_value, indices) + + na_value = -1 + + if allow_fill: taken = [lab.take(indices) for lab in self.codes] mask = indices == -1 if mask.any(): @@ -2052,7 +2036,10 @@ def _assert_take_fillable( taken = masked else: taken = [lab.take(indices) for lab in self.codes] - return taken + + return MultiIndex( + levels=self.levels, codes=taken, names=self.names, verify_integrity=False + ) def append(self, other): """
https://api.github.com/repos/pandas-dev/pandas/pulls/37551
2020-11-01T01:29:42Z
2020-11-02T00:27:06Z
2020-11-02T00:27:06Z
2020-11-02T00:28:09Z
TST/REF: collect base tests by method
diff --git a/pandas/tests/base/test_drop_duplicates.py b/pandas/tests/base/test_drop_duplicates.py deleted file mode 100644 index 8cde7aae5df05..0000000000000 --- a/pandas/tests/base/test_drop_duplicates.py +++ /dev/null @@ -1,31 +0,0 @@ -from datetime import datetime - -import numpy as np -import pytest - -import pandas as pd -import pandas._testing as tm - - -@pytest.mark.parametrize("keep", ["first", "last", False]) -def test_drop_duplicates_series_vs_dataframe(keep): - # GH 14192 - df = pd.DataFrame( - { - "a": [1, 1, 1, "one", "one"], - "b": [2, 2, np.nan, np.nan, np.nan], - "c": [3, 3, np.nan, np.nan, "three"], - "d": [1, 2, 3, 4, 4], - "e": [ - datetime(2015, 1, 1), - datetime(2015, 1, 1), - datetime(2015, 2, 1), - pd.NaT, - pd.NaT, - ], - } - ) - for column in df.columns: - dropped_frame = df[[column]].drop_duplicates(keep=keep) - dropped_series = df[column].drop_duplicates(keep=keep) - tm.assert_frame_equal(dropped_frame, dropped_series.to_frame()) diff --git a/pandas/tests/base/test_misc.py b/pandas/tests/base/test_misc.py index 298f8ca4f0f73..8d5bda6291747 100644 --- a/pandas/tests/base/test_misc.py +++ b/pandas/tests/base/test_misc.py @@ -5,15 +5,10 @@ from pandas.compat import IS64, PYPY -from pandas.core.dtypes.common import ( - is_categorical_dtype, - is_datetime64_dtype, - is_datetime64tz_dtype, - is_object_dtype, -) +from pandas.core.dtypes.common import is_categorical_dtype, is_object_dtype import pandas as pd -from pandas import DataFrame, Index, IntervalIndex, Series +from pandas import DataFrame, Index, Series @pytest.mark.parametrize( @@ -42,54 +37,6 @@ def test_binary_ops_docstring(klass, op_name, op): assert expected_str in getattr(klass, "r" + op_name).__doc__ -def test_none_comparison(series_with_simple_index): - series = series_with_simple_index - if isinstance(series.index, IntervalIndex): - # IntervalIndex breaks on "series[0] = np.nan" below - pytest.skip("IntervalIndex doesn't support assignment") - if len(series) < 1: - pytest.skip("Test doesn't make sense on empty data") - - # bug brought up by #1079 - # changed from TypeError in 0.17.0 - series[0] = np.nan - - # noinspection PyComparisonWithNone - result = series == None # noqa - assert not result.iat[0] - assert not result.iat[1] - - # noinspection PyComparisonWithNone - result = series != None # noqa - assert result.iat[0] - assert result.iat[1] - - result = None == series # noqa - assert not result.iat[0] - assert not result.iat[1] - - result = None != series # noqa - assert result.iat[0] - assert result.iat[1] - - if is_datetime64_dtype(series.dtype) or is_datetime64tz_dtype(series.dtype): - # Following DatetimeIndex (and Timestamp) convention, - # inequality comparisons with Series[datetime64] raise - msg = "Invalid comparison" - with pytest.raises(TypeError, match=msg): - None > series - with pytest.raises(TypeError, match=msg): - series > None - else: - result = None > series - assert not result.iat[0] - assert not result.iat[1] - - result = series < None - assert not result.iat[0] - assert not result.iat[1] - - def test_ndarray_compat_properties(index_or_series_obj): obj = index_or_series_obj diff --git a/pandas/tests/frame/methods/test_drop_duplicates.py b/pandas/tests/frame/methods/test_drop_duplicates.py index cebec215a0d9d..79b152b677dfd 100644 --- a/pandas/tests/frame/methods/test_drop_duplicates.py +++ b/pandas/tests/frame/methods/test_drop_duplicates.py @@ -1,9 +1,10 @@ +from datetime import datetime import re import numpy as np import pytest -from pandas import DataFrame +from pandas import DataFrame, NaT import pandas._testing as tm @@ -434,3 +435,27 @@ def test_drop_duplicates_null_in_object_column(nulls_fixture): df = DataFrame([[1, nulls_fixture], [2, "a"]], dtype=object) result = df.drop_duplicates() tm.assert_frame_equal(result, df) + + +@pytest.mark.parametrize("keep", ["first", "last", False]) +def test_drop_duplicates_series_vs_dataframe(keep): + # GH#14192 + df = DataFrame( + { + "a": [1, 1, 1, "one", "one"], + "b": [2, 2, np.nan, np.nan, np.nan], + "c": [3, 3, np.nan, np.nan, "three"], + "d": [1, 2, 3, 4, 4], + "e": [ + datetime(2015, 1, 1), + datetime(2015, 1, 1), + datetime(2015, 2, 1), + NaT, + NaT, + ], + } + ) + for column in df.columns: + dropped_frame = df[[column]].drop_duplicates(keep=keep) + dropped_series = df[column].drop_duplicates(keep=keep) + tm.assert_frame_equal(dropped_frame, dropped_series.to_frame()) diff --git a/pandas/tests/frame/methods/test_to_dict_of_blocks.py b/pandas/tests/frame/methods/test_to_dict_of_blocks.py index 436e70fbb0e56..0257a5d43170f 100644 --- a/pandas/tests/frame/methods/test_to_dict_of_blocks.py +++ b/pandas/tests/frame/methods/test_to_dict_of_blocks.py @@ -1,6 +1,7 @@ import numpy as np -from pandas import DataFrame +from pandas import DataFrame, MultiIndex +import pandas._testing as tm from pandas.core.arrays import PandasArray @@ -50,3 +51,17 @@ def test_to_dict_of_blocks_item_cache(): assert df.loc[0, "b"] == "foo" assert df["b"] is ser + + +def test_set_change_dtype_slice(): + # GH#8850 + cols = MultiIndex.from_tuples([("1st", "a"), ("2nd", "b"), ("3rd", "c")]) + df = DataFrame([[1.0, 2, 3], [4.0, 5, 6]], columns=cols) + df["2nd"] = df["2nd"] * 2.0 + + blocks = df._to_dict_of_blocks() + assert sorted(blocks.keys()) == ["float64", "int64"] + tm.assert_frame_equal( + blocks["float64"], DataFrame([[1.0, 4.0], [4.0, 10.0]], columns=cols[:2]) + ) + tm.assert_frame_equal(blocks["int64"], DataFrame([[3], [6]], columns=cols[2:])) diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 8ee84803339df..bddc50a3cbcc1 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -8,7 +8,7 @@ from pandas._libs.internals import BlockPlacement import pandas as pd -from pandas import Categorical, DataFrame, DatetimeIndex, Index, MultiIndex, Series +from pandas import Categorical, DataFrame, DatetimeIndex, Index, Series import pandas._testing as tm import pandas.core.algorithms as algos from pandas.core.arrays import DatetimeArray, SparseArray, TimedeltaArray @@ -1152,20 +1152,6 @@ def test_missing_unicode_key(): df.loc[:, "\u05d0"] # should not raise UnicodeEncodeError -def test_set_change_dtype_slice(): - # GH#8850 - cols = MultiIndex.from_tuples([("1st", "a"), ("2nd", "b"), ("3rd", "c")]) - df = DataFrame([[1.0, 2, 3], [4.0, 5, 6]], columns=cols) - df["2nd"] = df["2nd"] * 2.0 - - blocks = df._to_dict_of_blocks() - assert sorted(blocks.keys()) == ["float64", "int64"] - tm.assert_frame_equal( - blocks["float64"], DataFrame([[1.0, 4.0], [4.0, 10.0]], columns=cols[:2]) - ) - tm.assert_frame_equal(blocks["int64"], DataFrame([[3], [6]], columns=cols[2:])) - - def test_single_block_manager_fastpath_deprecated(): # GH#33092 ser = Series(range(3)) diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index ae6a4df8ba699..4920796f661fb 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -7,8 +7,18 @@ from pandas._libs.tslibs import IncompatibleFrequency +from pandas.core.dtypes.common import is_datetime64_dtype, is_datetime64tz_dtype + import pandas as pd -from pandas import Categorical, Index, Series, bdate_range, date_range, isna +from pandas import ( + Categorical, + Index, + IntervalIndex, + Series, + bdate_range, + date_range, + isna, +) import pandas._testing as tm from pandas.core import nanops, ops @@ -779,3 +789,51 @@ def test_binop_maybe_preserve_name(self, datetime_series): def test_scalarop_preserve_name(self, datetime_series): result = datetime_series * 2 assert result.name == datetime_series.name + + +def test_none_comparison(series_with_simple_index): + series = series_with_simple_index + if isinstance(series.index, IntervalIndex): + # IntervalIndex breaks on "series[0] = np.nan" below + pytest.skip("IntervalIndex doesn't support assignment") + if len(series) < 1: + pytest.skip("Test doesn't make sense on empty data") + + # bug brought up by #1079 + # changed from TypeError in 0.17.0 + series[0] = np.nan + + # noinspection PyComparisonWithNone + result = series == None # noqa + assert not result.iat[0] + assert not result.iat[1] + + # noinspection PyComparisonWithNone + result = series != None # noqa + assert result.iat[0] + assert result.iat[1] + + result = None == series # noqa + assert not result.iat[0] + assert not result.iat[1] + + result = None != series # noqa + assert result.iat[0] + assert result.iat[1] + + if is_datetime64_dtype(series.dtype) or is_datetime64tz_dtype(series.dtype): + # Following DatetimeIndex (and Timestamp) convention, + # inequality comparisons with Series[datetime64] raise + msg = "Invalid comparison" + with pytest.raises(TypeError, match=msg): + None > series + with pytest.raises(TypeError, match=msg): + series > None + else: + result = None > series + assert not result.iat[0] + assert not result.iat[1] + + result = series < None + assert not result.iat[0] + assert not result.iat[1]
https://api.github.com/repos/pandas-dev/pandas/pulls/37549
2020-10-31T22:35:44Z
2020-11-02T00:23:35Z
2020-11-02T00:23:35Z
2020-11-02T00:27:05Z
CLN: de-duplicate recode_for_categories
diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 499bb364c48a1..79d933c4c1619 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -83,7 +83,9 @@ def func(self, other): if not self.ordered and not self.categories.equals(other.categories): # both unordered and different order - other_codes = _get_codes_for_values(other, self.categories) + other_codes = recode_for_categories( + other.codes, other.categories, self.categories, copy=False + ) else: other_codes = other._codes @@ -354,9 +356,7 @@ def __init__( dtype = CategoricalDtype(categories, dtype.ordered) elif is_categorical_dtype(values.dtype): - old_codes = ( - values._values.codes if isinstance(values, ABCSeries) else values.codes - ) + old_codes = extract_array(values).codes codes = recode_for_categories( old_codes, values.dtype.categories, dtype.categories ) @@ -1706,17 +1706,9 @@ def _validate_listlike(self, target: ArrayLike) -> np.ndarray: # Indexing on codes is more efficient if categories are the same, # so we can apply some optimizations based on the degree of # dtype-matching. - if self.categories.equals(target.categories): - # We use the same codes, so can go directly to the engine - codes = target.codes - elif self.is_dtype_equal(target): - # We have the same categories up to a reshuffling of codes. - codes = recode_for_categories( - target.codes, target.categories, self.categories - ) - else: - code_indexer = self.categories.get_indexer(target.categories) - codes = take_1d(code_indexer, target.codes, fill_value=-1) + codes = recode_for_categories( + target.codes, target.categories, self.categories, copy=False + ) else: codes = self.categories.get_indexer(target) @@ -2472,9 +2464,11 @@ def _delegate_method(self, name, *args, **kwargs): # utility routines -def _get_codes_for_values(values, categories): +def _get_codes_for_values(values, categories) -> np.ndarray: """ utility routine to turn values into codes given the specified categories + + If `values` is known to be a Categorical, use recode_for_categories instead. """ dtype_equal = is_dtype_equal(values.dtype, categories.dtype) @@ -2504,7 +2498,9 @@ def _get_codes_for_values(values, categories): return coerce_indexer_dtype(t.lookup(vals), cats) -def recode_for_categories(codes: np.ndarray, old_categories, new_categories): +def recode_for_categories( + codes: np.ndarray, old_categories, new_categories, copy: bool = True +) -> np.ndarray: """ Convert a set of codes for to a new set of categories @@ -2512,6 +2508,8 @@ def recode_for_categories(codes: np.ndarray, old_categories, new_categories): ---------- codes : np.ndarray old_categories, new_categories : Index + copy: bool, default True + Whether to copy if the codes are unchanged. Returns ------- @@ -2527,14 +2525,19 @@ def recode_for_categories(codes: np.ndarray, old_categories, new_categories): """ if len(old_categories) == 0: # All null anyway, so just retain the nulls - return codes.copy() + if copy: + return codes.copy() + return codes elif new_categories.equals(old_categories): # Same categories, so no need to actually recode - return codes.copy() + if copy: + return codes.copy() + return codes + indexer = coerce_indexer_dtype( new_categories.get_indexer(old_categories), new_categories ) - new_codes = take_1d(indexer, codes.copy(), fill_value=-1) + new_codes = take_1d(indexer, codes, fill_value=-1) return new_codes
Step towards figuring out the small differences between Categorical's _validate_foo methods
https://api.github.com/repos/pandas-dev/pandas/pulls/37548
2020-10-31T22:32:38Z
2020-11-02T00:24:18Z
2020-11-02T00:24:18Z
2020-11-02T00:26:48Z
ENH: Improve error reporting for wrong merge cols
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 690e6b8f725ad..bb8c059d70b60 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -231,6 +231,7 @@ Other enhancements - :class:`Window` now supports all Scipy window types in ``win_type`` with flexible keyword argument support (:issue:`34556`) - :meth:`testing.assert_index_equal` now has a ``check_order`` parameter that allows indexes to be checked in an order-insensitive manner (:issue:`37478`) - :func:`read_csv` supports memory-mapping for compressed files (:issue:`37621`) +- Improve error reporting for :meth:`DataFrame.merge()` when invalid merge column definitions were given (:issue:`16228`) .. _whatsnew_120.api_breaking.python: diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 978597e3c7686..aa883d518f8d1 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -1203,11 +1203,9 @@ def _validate_specification(self): if self.left_index and self.right_index: self.left_on, self.right_on = (), () elif self.left_index: - if self.right_on is None: - raise MergeError("Must pass right_on or right_index=True") + raise MergeError("Must pass right_on or right_index=True") elif self.right_index: - if self.left_on is None: - raise MergeError("Must pass left_on or left_index=True") + raise MergeError("Must pass left_on or left_index=True") else: # use the common columns common_cols = self.left.columns.intersection(self.right.columns) @@ -1228,8 +1226,19 @@ def _validate_specification(self): 'Can only pass argument "on" OR "left_on" ' 'and "right_on", not a combination of both.' ) + if self.left_index or self.right_index: + raise MergeError( + 'Can only pass argument "on" OR "left_index" ' + 'and "right_index", not a combination of both.' + ) self.left_on = self.right_on = self.on elif self.left_on is not None: + if self.left_index: + raise MergeError( + 'Can only pass argument "left_on" OR "left_index" not both.' + ) + if not self.right_index and self.right_on is None: + raise MergeError('Must pass "right_on" OR "right_index".') n = len(self.left_on) if self.right_index: if len(self.left_on) != self.right.index.nlevels: @@ -1239,6 +1248,12 @@ def _validate_specification(self): ) self.right_on = [None] * n elif self.right_on is not None: + if self.right_index: + raise MergeError( + 'Can only pass argument "right_on" OR "right_index" not both.' + ) + if not self.left_index and self.left_on is None: + raise MergeError('Must pass "left_on" OR "left_index".') n = len(self.right_on) if self.left_index: if len(self.right_on) != self.left.index.nlevels: diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index a58372040c7f3..999b827fe0571 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -2283,3 +2283,57 @@ def test_merge_join_categorical_multiindex(): expected = expected.drop(["Cat", "Int"], axis=1) result = a.join(b, on=["Cat1", "Int1"]) tm.assert_frame_equal(expected, result) + + +@pytest.mark.parametrize("func", ["merge", "merge_asof"]) +@pytest.mark.parametrize( + ("kwargs", "err_msg"), + [ + ({"left_on": "a", "left_index": True}, ["left_on", "left_index"]), + ({"right_on": "a", "right_index": True}, ["right_on", "right_index"]), + ], +) +def test_merge_join_cols_error_reporting_duplicates(func, kwargs, err_msg): + # GH: 16228 + left = DataFrame({"a": [1, 2], "b": [3, 4]}) + right = DataFrame({"a": [1, 1], "c": [5, 6]}) + msg = rf'Can only pass argument "{err_msg[0]}" OR "{err_msg[1]}" not both\.' + with pytest.raises(MergeError, match=msg): + getattr(pd, func)(left, right, **kwargs) + + +@pytest.mark.parametrize("func", ["merge", "merge_asof"]) +@pytest.mark.parametrize( + ("kwargs", "err_msg"), + [ + ({"left_on": "a"}, ["right_on", "right_index"]), + ({"right_on": "a"}, ["left_on", "left_index"]), + ], +) +def test_merge_join_cols_error_reporting_missing(func, kwargs, err_msg): + # GH: 16228 + left = DataFrame({"a": [1, 2], "b": [3, 4]}) + right = DataFrame({"a": [1, 1], "c": [5, 6]}) + msg = rf'Must pass "{err_msg[0]}" OR "{err_msg[1]}"\.' + with pytest.raises(MergeError, match=msg): + getattr(pd, func)(left, right, **kwargs) + + +@pytest.mark.parametrize("func", ["merge", "merge_asof"]) +@pytest.mark.parametrize( + "kwargs", + [ + {"right_index": True}, + {"left_index": True}, + ], +) +def test_merge_join_cols_error_reporting_on_and_index(func, kwargs): + # GH: 16228 + left = DataFrame({"a": [1, 2], "b": [3, 4]}) + right = DataFrame({"a": [1, 1], "c": [5, 6]}) + msg = ( + r'Can only pass argument "on" OR "left_index" ' + r'and "right_index", not a combination of both\.' + ) + with pytest.raises(MergeError, match=msg): + getattr(pd, func)(left, right, on="a", **kwargs)
- [x] closes #16228 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Fixed error reporting when double conditions are given. Additionally I found, that something like ``` left = DataFrame({"a": [1, 2], "b": [3, 4]}) right = DataFrame({"a": [1, 1], "c": [5, 6]}) pd.merge(left, right, right_on="a") ``` raised an uncontrolled error: ``` Traceback (most recent call last): File "/home/developer/.config/JetBrains/PyCharm2020.2/scratches/scratch_4.py", line 25, in <module> print(pd.merge(left, right, right_on="a")) File "/home/developer/PycharmProjects/pandas/pandas/core/reshape/merge.py", line 72, in merge op = _MergeOperation( File "/home/developer/PycharmProjects/pandas/pandas/core/reshape/merge.py", line 643, in __init__ self._validate_specification() File "/home/developer/PycharmProjects/pandas/pandas/core/reshape/merge.py", line 1247, in _validate_specification if len(self.right_on) != len(self.left_on): TypeError: object of type 'NoneType' has no len() ```
https://api.github.com/repos/pandas-dev/pandas/pulls/37547
2020-10-31T22:05:53Z
2020-11-08T03:08:00Z
2020-11-08T03:08:00Z
2020-11-08T12:06:18Z
ENH: Add dtype argument to read_sql_query (GH10285)
diff --git a/doc/source/whatsnew/v1.3.0.rst b/doc/source/whatsnew/v1.3.0.rst index 65bfd8289fe3d..5ddf68cad8baf 100644 --- a/doc/source/whatsnew/v1.3.0.rst +++ b/doc/source/whatsnew/v1.3.0.rst @@ -43,6 +43,7 @@ Other enhancements - Added ``end`` and ``end_day`` options for ``origin`` in :meth:`DataFrame.resample` (:issue:`37804`) - Improve error message when ``usecols`` and ``names`` do not match for :func:`read_csv` and ``engine="c"`` (:issue:`29042`) - Improved consistency of error message when passing an invalid ``win_type`` argument in :class:`Window` (:issue:`15969`) +- :func:`pandas.read_sql_query` now accepts a ``dtype`` argument to cast the columnar data from the SQL database based on user input (:issue:`10285`) .. --------------------------------------------------------------------------- diff --git a/pandas/_typing.py b/pandas/_typing.py index c79942c48509e..64452bf337361 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -71,13 +71,6 @@ ] Timezone = Union[str, tzinfo] -# other - -Dtype = Union[ - "ExtensionDtype", str, np.dtype, Type[Union[str, float, int, complex, bool, object]] -] -DtypeObj = Union[np.dtype, "ExtensionDtype"] - # FrameOrSeriesUnion means either a DataFrame or a Series. E.g. # `def func(a: FrameOrSeriesUnion) -> FrameOrSeriesUnion: ...` means that if a Series # is passed in, either a Series or DataFrame is returned, and if a DataFrame is passed @@ -100,6 +93,14 @@ JSONSerializable = Optional[Union[PythonScalar, List, Dict]] Axes = Collection +# dtypes +Dtype = Union[ + "ExtensionDtype", str, np.dtype, Type[Union[str, float, int, complex, bool, object]] +] +# DtypeArg specifies all allowable dtypes in a functions its dtype argument +DtypeArg = Union[Dtype, Dict[Label, Dtype]] +DtypeObj = Union[np.dtype, "ExtensionDtype"] + # For functions like rename that convert one label to another Renamer = Union[Mapping[Label, Any], Callable[[Label], Label]] diff --git a/pandas/io/sql.py b/pandas/io/sql.py index a6708896f4f2e..0ad9140f2a757 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -13,6 +13,7 @@ import numpy as np import pandas._libs.lib as lib +from pandas._typing import DtypeArg from pandas.core.dtypes.common import is_datetime64tz_dtype, is_dict_like, is_list_like from pandas.core.dtypes.dtypes import DatetimeTZDtype @@ -132,10 +133,14 @@ def _wrap_result( index_col=None, coerce_float: bool = True, parse_dates=None, + dtype: Optional[DtypeArg] = None, ): """Wrap result set of query in a DataFrame.""" frame = DataFrame.from_records(data, columns=columns, coerce_float=coerce_float) + if dtype: + frame = frame.astype(dtype) + frame = _parse_date_columns(frame, parse_dates) if index_col is not None: @@ -308,6 +313,7 @@ def read_sql_query( params=None, parse_dates=None, chunksize: None = None, + dtype: Optional[DtypeArg] = None, ) -> DataFrame: ... @@ -321,6 +327,7 @@ def read_sql_query( params=None, parse_dates=None, chunksize: int = 1, + dtype: Optional[DtypeArg] = None, ) -> Iterator[DataFrame]: ... @@ -333,6 +340,7 @@ def read_sql_query( params=None, parse_dates=None, chunksize: Optional[int] = None, + dtype: Optional[DtypeArg] = None, ) -> Union[DataFrame, Iterator[DataFrame]]: """ Read SQL query into a DataFrame. @@ -371,6 +379,9 @@ def read_sql_query( chunksize : int, default None If specified, return an iterator where `chunksize` is the number of rows to include in each chunk. + dtype : Type name or dict of columns + Data type for data or columns. E.g. np.float64 or + {‘a’: np.float64, ‘b’: np.int32, ‘c’: ‘Int64’} Returns ------- @@ -394,6 +405,7 @@ def read_sql_query( coerce_float=coerce_float, parse_dates=parse_dates, chunksize=chunksize, + dtype=dtype, ) @@ -1307,6 +1319,7 @@ def _query_iterator( index_col=None, coerce_float=True, parse_dates=None, + dtype: Optional[DtypeArg] = None, ): """Return generator through chunked result set""" while True: @@ -1320,6 +1333,7 @@ def _query_iterator( index_col=index_col, coerce_float=coerce_float, parse_dates=parse_dates, + dtype=dtype, ) def read_query( @@ -1330,6 +1344,7 @@ def read_query( parse_dates=None, params=None, chunksize: Optional[int] = None, + dtype: Optional[DtypeArg] = None, ): """ Read SQL query into a DataFrame. @@ -1361,6 +1376,11 @@ def read_query( chunksize : int, default None If specified, return an iterator where `chunksize` is the number of rows to include in each chunk. + dtype : Type name or dict of columns + Data type for data or columns. E.g. np.float64 or + {‘a’: np.float64, ‘b’: np.int32, ‘c’: ‘Int64’} + + .. versionadded:: 1.3.0 Returns ------- @@ -1385,6 +1405,7 @@ def read_query( index_col=index_col, coerce_float=coerce_float, parse_dates=parse_dates, + dtype=dtype, ) else: data = result.fetchall() @@ -1394,6 +1415,7 @@ def read_query( index_col=index_col, coerce_float=coerce_float, parse_dates=parse_dates, + dtype=dtype, ) return frame @@ -1799,6 +1821,7 @@ def _query_iterator( index_col=None, coerce_float: bool = True, parse_dates=None, + dtype: Optional[DtypeArg] = None, ): """Return generator through chunked result set""" while True: @@ -1815,6 +1838,7 @@ def _query_iterator( index_col=index_col, coerce_float=coerce_float, parse_dates=parse_dates, + dtype=dtype, ) def read_query( @@ -1825,6 +1849,7 @@ def read_query( params=None, parse_dates=None, chunksize: Optional[int] = None, + dtype: Optional[DtypeArg] = None, ): args = _convert_params(sql, params) @@ -1839,6 +1864,7 @@ def read_query( index_col=index_col, coerce_float=coerce_float, parse_dates=parse_dates, + dtype=dtype, ) else: data = self._fetchall_as_list(cursor) @@ -1850,6 +1876,7 @@ def read_query( index_col=index_col, coerce_float=coerce_float, parse_dates=parse_dates, + dtype=dtype, ) return frame diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 9df8ff9e8ee06..fdd42ec0cc5ab 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -937,6 +937,27 @@ def test_multiindex_roundtrip(self): ) tm.assert_frame_equal(df, result, check_index_type=True) + @pytest.mark.parametrize( + "dtype", + [ + None, + int, + float, + {"A": int, "B": float}, + ], + ) + def test_dtype_argument(self, dtype): + # GH10285 Add dtype argument to read_sql_query + df = DataFrame([[1.2, 3.4], [5.6, 7.8]], columns=["A", "B"]) + df.to_sql("test_dtype_argument", self.conn) + + expected = df.astype(dtype) + result = sql.read_sql_query( + "SELECT A, B FROM test_dtype_argument", con=self.conn, dtype=dtype + ) + + tm.assert_frame_equal(result, expected) + def test_integer_col_names(self): df = DataFrame([[1, 2], [3, 4]], columns=[0, 1]) sql.to_sql(df, "test_frame_integer_col_names", self.conn, if_exists="replace")
- [x] closes #10285 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37546
2020-10-31T21:44:46Z
2020-12-23T23:28:23Z
2020-12-23T23:28:23Z
2020-12-23T23:50:52Z
REF: Categorical.is_dtype_equal -> categories_match_up_to_permutation
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 6f137302d4994..8a092cb6e36db 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -340,6 +340,7 @@ Deprecations - :meth:`Index.ravel` returning a ``np.ndarray`` is deprecated, in the future this will return a view on the same index (:issue:`19956`) - Deprecate use of strings denoting units with 'M', 'Y' or 'y' in :func:`~pandas.to_timedelta` (:issue:`36666`) - :class:`Index` methods ``&``, ``|``, and ``^`` behaving as the set operations :meth:`Index.intersection`, :meth:`Index.union`, and :meth:`Index.symmetric_difference`, respectively, are deprecated and in the future will behave as pointwise boolean operations matching :class:`Series` behavior. Use the named set methods instead (:issue:`36758`) +- :meth:`Categorical.is_dtype_equal` and :meth:`CategoricalIndex.is_dtype_equal` are deprecated, will be removed in a future version (:issue:`37545`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 03f66ff82ad75..13fd0c5df1229 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -78,7 +78,7 @@ def func(self, other): # the same (maybe up to ordering, depending on ordered) msg = "Categoricals can only be compared if 'categories' are the same." - if not self.is_dtype_equal(other): + if not self._categories_match_up_to_permutation(other): raise TypeError(msg) if not self.ordered and not self.categories.equals(other.categories): @@ -1874,11 +1874,12 @@ def _validate_setitem_value(self, value): # require identical categories set if isinstance(value, Categorical): - if not is_dtype_equal(self, value): + if not is_dtype_equal(self.dtype, value.dtype): raise ValueError( "Cannot set a Categorical with another, " "without identical categories" ) + # is_dtype_equal implies categories_match_up_to_permutation new_codes = self._validate_listlike(value) value = Categorical.from_codes(new_codes, dtype=self.dtype) @@ -2112,7 +2113,7 @@ def equals(self, other: object) -> bool: """ if not isinstance(other, Categorical): return False - elif self.is_dtype_equal(other): + elif self._categories_match_up_to_permutation(other): other_codes = self._validate_listlike(other) return np.array_equal(self._codes, other_codes) return False @@ -2125,7 +2126,7 @@ def _concat_same_type(self, to_concat): # ------------------------------------------------------------------ - def is_dtype_equal(self, other): + def _categories_match_up_to_permutation(self, other: "Categorical") -> bool: """ Returns True if categoricals are the same dtype same categories, and same ordered @@ -2138,8 +2139,17 @@ def is_dtype_equal(self, other): ------- bool """ + return hash(self.dtype) == hash(other.dtype) + + def is_dtype_equal(self, other) -> bool: + warn( + "Categorical.is_dtype_equal is deprecated and will be removed " + "in a future version", + FutureWarning, + stacklevel=2, + ) try: - return hash(self.dtype) == hash(other.dtype) + return self._categories_match_up_to_permutation(other) except (AttributeError, TypeError): return False diff --git a/pandas/core/dtypes/concat.py b/pandas/core/dtypes/concat.py index 60fd959701821..99dc01ef421d1 100644 --- a/pandas/core/dtypes/concat.py +++ b/pandas/core/dtypes/concat.py @@ -296,7 +296,7 @@ def _maybe_unwrap(x): raise TypeError("dtype of categories must be the same") ordered = False - if all(first.is_dtype_equal(other) for other in to_union[1:]): + if all(first._categories_match_up_to_permutation(other) for other in to_union[1:]): # identical categories - fastpath categories = first.categories ordered = first.ordered diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 2f2836519d847..8cbd0d83c78d7 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -255,7 +255,7 @@ def _is_dtype_compat(self, other) -> Categorical: """ if is_categorical_dtype(other): other = extract_array(other) - if not other.is_dtype_equal(self): + if not other._categories_match_up_to_permutation(self): raise TypeError( "categories must match existing categories when appending" ) diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 5012be593820e..d82b1474ff3e0 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -1083,7 +1083,7 @@ def _maybe_coerce_merge_keys(self): # if either left or right is a categorical # then the must match exactly in categories & ordered if lk_is_cat and rk_is_cat: - if lk.is_dtype_equal(rk): + if lk._categories_match_up_to_permutation(rk): continue elif lk_is_cat or rk_is_cat: diff --git a/pandas/tests/arrays/categorical/test_dtypes.py b/pandas/tests/arrays/categorical/test_dtypes.py index 47ce9cb4089f9..deafa22a6e8eb 100644 --- a/pandas/tests/arrays/categorical/test_dtypes.py +++ b/pandas/tests/arrays/categorical/test_dtypes.py @@ -8,34 +8,45 @@ class TestCategoricalDtypes: - def test_is_equal_dtype(self): + def test_is_dtype_equal_deprecated(self): + # GH#37545 + c1 = Categorical(list("aabca"), categories=list("abc"), ordered=False) + + with tm.assert_produces_warning(FutureWarning): + c1.is_dtype_equal(c1) + + def test_categories_match_up_to_permutation(self): # test dtype comparisons between cats c1 = Categorical(list("aabca"), categories=list("abc"), ordered=False) c2 = Categorical(list("aabca"), categories=list("cab"), ordered=False) c3 = Categorical(list("aabca"), categories=list("cab"), ordered=True) - assert c1.is_dtype_equal(c1) - assert c2.is_dtype_equal(c2) - assert c3.is_dtype_equal(c3) - assert c1.is_dtype_equal(c2) - assert not c1.is_dtype_equal(c3) - assert not c1.is_dtype_equal(Index(list("aabca"))) - assert not c1.is_dtype_equal(c1.astype(object)) - assert c1.is_dtype_equal(CategoricalIndex(c1)) - assert c1.is_dtype_equal(CategoricalIndex(c1, categories=list("cab"))) - assert not c1.is_dtype_equal(CategoricalIndex(c1, ordered=True)) + assert c1._categories_match_up_to_permutation(c1) + assert c2._categories_match_up_to_permutation(c2) + assert c3._categories_match_up_to_permutation(c3) + assert c1._categories_match_up_to_permutation(c2) + assert not c1._categories_match_up_to_permutation(c3) + assert not c1._categories_match_up_to_permutation(Index(list("aabca"))) + assert not c1._categories_match_up_to_permutation(c1.astype(object)) + assert c1._categories_match_up_to_permutation(CategoricalIndex(c1)) + assert c1._categories_match_up_to_permutation( + CategoricalIndex(c1, categories=list("cab")) + ) + assert not c1._categories_match_up_to_permutation( + CategoricalIndex(c1, ordered=True) + ) # GH 16659 s1 = Series(c1) s2 = Series(c2) s3 = Series(c3) - assert c1.is_dtype_equal(s1) - assert c2.is_dtype_equal(s2) - assert c3.is_dtype_equal(s3) - assert c1.is_dtype_equal(s2) - assert not c1.is_dtype_equal(s3) - assert not c1.is_dtype_equal(s1.astype(object)) + assert c1._categories_match_up_to_permutation(s1) + assert c2._categories_match_up_to_permutation(s2) + assert c3._categories_match_up_to_permutation(s3) + assert c1._categories_match_up_to_permutation(s2) + assert not c1._categories_match_up_to_permutation(s3) + assert not c1._categories_match_up_to_permutation(s1.astype(object)) def test_set_dtype_same(self): c = Categorical(["a", "b", "c"]) diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index bb2860b88b288..a58372040c7f3 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -1707,8 +1707,8 @@ def test_other_columns(self, left, right): tm.assert_series_equal(result, expected) # categories are preserved - assert left.X.values.is_dtype_equal(merged.X.values) - assert right.Z.values.is_dtype_equal(merged.Z.values) + assert left.X.values._categories_match_up_to_permutation(merged.X.values) + assert right.Z.values._categories_match_up_to_permutation(merged.Z.values) @pytest.mark.parametrize( "change", @@ -1725,7 +1725,7 @@ def test_dtype_on_merged_different(self, change, join_type, left, right): X = change(right.X.astype("object")) right = right.assign(X=X) assert is_categorical_dtype(left.X.values.dtype) - # assert not left.X.values.is_dtype_equal(right.X.values) + # assert not left.X.values._categories_match_up_to_permutation(right.X.values) merged = pd.merge(left, right, on="X", how=join_type)
- [ ] closes #xxxx - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry There are too many notions of CategoricalDtype equality. This gives a clearer name to one of them.
https://api.github.com/repos/pandas-dev/pandas/pulls/37545
2020-10-31T21:21:37Z
2020-11-02T22:39:27Z
2020-11-02T22:39:27Z
2020-11-02T22:48:23Z
DOC Add note about virtualenv and conda
diff --git a/doc/source/development/contributing.rst b/doc/source/development/contributing.rst index b281c7cfc7d39..08d8451127732 100644 --- a/doc/source/development/contributing.rst +++ b/doc/source/development/contributing.rst @@ -837,8 +837,14 @@ to run its checks by running:: without having to have done ``pre-commit install`` beforehand. -Note that if you have conflicting installations of ``virtualenv``, then you may get an -error - see `here <https://github.com/pypa/virtualenv/issues/1875>`_. +.. note:: + + If you have conflicting installations of ``virtualenv``, then you may get an + error - see `here <https://github.com/pypa/virtualenv/issues/1875>`_. + + Also, due to a `bug in virtualenv <https://github.com/pypa/virtualenv/issues/1986>`_, + you may run into issues if you're using conda. To solve this, you can downgrade + ``virtualenv`` to version ``20.0.33``. Backwards compatibility ~~~~~~~~~~~~~~~~~~~~~~~
xref https://github.com/pandas-dev/pandas/pull/37023#issuecomment-716591356
https://api.github.com/repos/pandas-dev/pandas/pulls/37542
2020-10-31T19:33:36Z
2020-10-31T20:39:04Z
2020-10-31T20:39:04Z
2020-10-31T20:39:14Z
REF: make EA reductions, nanops funcs keyword-only
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index 7c850ffedfcab..690bd9bc9704b 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -545,6 +545,7 @@ ExtensionArray - Fixed bug where ``astype()`` with equal dtype and ``copy=False`` would return a new object (:issue:`284881`) - Fixed bug when applying a NumPy ufunc with multiple outputs to a :class:`pandas.arrays.IntegerArray` returning None (:issue:`36913`) - Fixed an inconsistency in :class:`PeriodArray`'s ``__init__`` signature to those of :class:`DatetimeArray` and :class:`TimedeltaArray` (:issue:`37289`) +- Reductions for :class:`BooleanArray`, :class:`Categorical`, :class:`DatetimeArray`, :class:`FloatingArray`, :class:`IntegerArray`, :class:`PeriodArray`, :class:`TimedeltaArray`, and :class:`PandasArray` are now keyword-only methods (:issue:`37541`) Other ^^^^^ diff --git a/pandas/core/arrays/boolean.py b/pandas/core/arrays/boolean.py index b46e70f5a936d..028a0c4684aef 100644 --- a/pandas/core/arrays/boolean.py +++ b/pandas/core/arrays/boolean.py @@ -424,7 +424,7 @@ def _values_for_argsort(self) -> np.ndarray: data[self._mask] = -1 return data - def any(self, skipna: bool = True, **kwargs): + def any(self, *, skipna: bool = True, **kwargs): """ Return whether any element is True. @@ -492,7 +492,7 @@ def any(self, skipna: bool = True, **kwargs): else: return self.dtype.na_value - def all(self, skipna: bool = True, **kwargs): + def all(self, *, skipna: bool = True, **kwargs): """ Return whether all elements are True. diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 499bb364c48a1..53e5d95907bde 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -1945,7 +1945,7 @@ def _reverse_indexer(self) -> Dict[Hashable, np.ndarray]: # Reductions @deprecate_kwarg(old_arg_name="numeric_only", new_arg_name="skipna") - def min(self, skipna=True, **kwargs): + def min(self, *, skipna=True, **kwargs): """ The minimum value of the object. @@ -1981,7 +1981,7 @@ def min(self, skipna=True, **kwargs): return self.categories[pointer] @deprecate_kwarg(old_arg_name="numeric_only", new_arg_name="skipna") - def max(self, skipna=True, **kwargs): + def max(self, *, skipna=True, **kwargs): """ The maximum value of the object. diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index 1184464e967af..f8a609fb0cabe 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1245,7 +1245,7 @@ def __isub__(self, other): # -------------------------------------------------------------- # Reductions - def min(self, axis=None, skipna=True, *args, **kwargs): + def min(self, *, axis=None, skipna=True, **kwargs): """ Return the minimum value of the Array or minimum along an axis. @@ -1256,7 +1256,7 @@ def min(self, axis=None, skipna=True, *args, **kwargs): Index.min : Return the minimum value in an Index. Series.min : Return the minimum value in a Series. """ - nv.validate_min(args, kwargs) + nv.validate_min((), kwargs) nv.validate_minmax_axis(axis, self.ndim) if is_period_dtype(self.dtype): @@ -1276,7 +1276,7 @@ def min(self, axis=None, skipna=True, *args, **kwargs): return self._box_func(result) return self._from_backing_data(result) - def max(self, axis=None, skipna=True, *args, **kwargs): + def max(self, *, axis=None, skipna=True, **kwargs): """ Return the maximum value of the Array or maximum along an axis. @@ -1289,7 +1289,7 @@ def max(self, axis=None, skipna=True, *args, **kwargs): """ # TODO: skipna is broken with max. # See https://github.com/pandas-dev/pandas/issues/24265 - nv.validate_max(args, kwargs) + nv.validate_max((), kwargs) nv.validate_minmax_axis(axis, self.ndim) if is_period_dtype(self.dtype): @@ -1309,7 +1309,7 @@ def max(self, axis=None, skipna=True, *args, **kwargs): return self._box_func(result) return self._from_backing_data(result) - def mean(self, skipna=True, axis: Optional[int] = 0): + def mean(self, *, skipna=True, axis: Optional[int] = 0): """ Return the mean value of the Array. @@ -1350,8 +1350,8 @@ def mean(self, skipna=True, axis: Optional[int] = 0): return self._box_func(result) return self._from_backing_data(result) - def median(self, axis: Optional[int] = None, skipna: bool = True, *args, **kwargs): - nv.validate_median(args, kwargs) + def median(self, *, axis: Optional[int] = None, skipna: bool = True, **kwargs): + nv.validate_median((), kwargs) if axis is not None and abs(axis) >= self.ndim: raise ValueError("abs(axis) must be less than ndim") diff --git a/pandas/core/arrays/floating.py b/pandas/core/arrays/floating.py index 02f434342191f..4cfaae23e4389 100644 --- a/pandas/core/arrays/floating.py +++ b/pandas/core/arrays/floating.py @@ -439,19 +439,19 @@ def _cmp_method(self, other, op): return BooleanArray(result, mask) - def sum(self, skipna=True, min_count=0, **kwargs): + def sum(self, *, skipna=True, min_count=0, **kwargs): nv.validate_sum((), kwargs) return super()._reduce("sum", skipna=skipna, min_count=min_count) - def prod(self, skipna=True, min_count=0, **kwargs): + def prod(self, *, skipna=True, min_count=0, **kwargs): nv.validate_prod((), kwargs) return super()._reduce("prod", skipna=skipna, min_count=min_count) - def min(self, skipna=True, **kwargs): + def min(self, *, skipna=True, **kwargs): nv.validate_min((), kwargs) return super()._reduce("min", skipna=skipna) - def max(self, skipna=True, **kwargs): + def max(self, *, skipna=True, **kwargs): nv.validate_max((), kwargs) return super()._reduce("max", skipna=skipna) diff --git a/pandas/core/arrays/integer.py b/pandas/core/arrays/integer.py index e53276369a46f..e3d19e53e4517 100644 --- a/pandas/core/arrays/integer.py +++ b/pandas/core/arrays/integer.py @@ -603,19 +603,19 @@ def _arith_method(self, other, op): return self._maybe_mask_result(result, mask, other, op_name) - def sum(self, skipna=True, min_count=0, **kwargs): + def sum(self, *, skipna=True, min_count=0, **kwargs): nv.validate_sum((), kwargs) return super()._reduce("sum", skipna=skipna, min_count=min_count) - def prod(self, skipna=True, min_count=0, **kwargs): + def prod(self, *, skipna=True, min_count=0, **kwargs): nv.validate_prod((), kwargs) return super()._reduce("prod", skipna=skipna, min_count=min_count) - def min(self, skipna=True, **kwargs): + def min(self, *, skipna=True, **kwargs): nv.validate_min((), kwargs) return super()._reduce("min", skipna=skipna) - def max(self, skipna=True, **kwargs): + def max(self, *, skipna=True, **kwargs): nv.validate_max((), kwargs) return super()._reduce("max", skipna=skipna) diff --git a/pandas/core/arrays/numpy_.py b/pandas/core/arrays/numpy_.py index 810a2ce0cfde5..cd48f6cbc8170 100644 --- a/pandas/core/arrays/numpy_.py +++ b/pandas/core/arrays/numpy_.py @@ -271,77 +271,83 @@ def _values_for_factorize(self) -> Tuple[np.ndarray, int]: # ------------------------------------------------------------------------ # Reductions - def any(self, axis=None, out=None, keepdims=False, skipna=True): + def any(self, *, axis=None, out=None, keepdims=False, skipna=True): nv.validate_any((), dict(out=out, keepdims=keepdims)) return nanops.nanany(self._ndarray, axis=axis, skipna=skipna) - def all(self, axis=None, out=None, keepdims=False, skipna=True): + def all(self, *, axis=None, out=None, keepdims=False, skipna=True): nv.validate_all((), dict(out=out, keepdims=keepdims)) return nanops.nanall(self._ndarray, axis=axis, skipna=skipna) - def min(self, skipna: bool = True, **kwargs) -> Scalar: + def min(self, *, skipna: bool = True, **kwargs) -> Scalar: nv.validate_min((), kwargs) result = masked_reductions.min( values=self.to_numpy(), mask=self.isna(), skipna=skipna ) return result - def max(self, skipna: bool = True, **kwargs) -> Scalar: + def max(self, *, skipna: bool = True, **kwargs) -> Scalar: nv.validate_max((), kwargs) result = masked_reductions.max( values=self.to_numpy(), mask=self.isna(), skipna=skipna ) return result - def sum(self, axis=None, skipna=True, min_count=0, **kwargs) -> Scalar: + def sum(self, *, axis=None, skipna=True, min_count=0, **kwargs) -> Scalar: nv.validate_sum((), kwargs) return nanops.nansum( self._ndarray, axis=axis, skipna=skipna, min_count=min_count ) - def prod(self, axis=None, skipna=True, min_count=0, **kwargs) -> Scalar: + def prod(self, *, axis=None, skipna=True, min_count=0, **kwargs) -> Scalar: nv.validate_prod((), kwargs) return nanops.nanprod( self._ndarray, axis=axis, skipna=skipna, min_count=min_count ) - def mean(self, axis=None, dtype=None, out=None, keepdims=False, skipna=True): + def mean(self, *, axis=None, dtype=None, out=None, keepdims=False, skipna=True): nv.validate_mean((), dict(dtype=dtype, out=out, keepdims=keepdims)) return nanops.nanmean(self._ndarray, axis=axis, skipna=skipna) def median( - self, axis=None, out=None, overwrite_input=False, keepdims=False, skipna=True + self, *, axis=None, out=None, overwrite_input=False, keepdims=False, skipna=True ): nv.validate_median( (), dict(out=out, overwrite_input=overwrite_input, keepdims=keepdims) ) return nanops.nanmedian(self._ndarray, axis=axis, skipna=skipna) - def std(self, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True): + def std( + self, *, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True + ): nv.validate_stat_ddof_func( (), dict(dtype=dtype, out=out, keepdims=keepdims), fname="std" ) return nanops.nanstd(self._ndarray, axis=axis, skipna=skipna, ddof=ddof) - def var(self, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True): + def var( + self, *, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True + ): nv.validate_stat_ddof_func( (), dict(dtype=dtype, out=out, keepdims=keepdims), fname="var" ) return nanops.nanvar(self._ndarray, axis=axis, skipna=skipna, ddof=ddof) - def sem(self, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True): + def sem( + self, *, axis=None, dtype=None, out=None, ddof=1, keepdims=False, skipna=True + ): nv.validate_stat_ddof_func( (), dict(dtype=dtype, out=out, keepdims=keepdims), fname="sem" ) return nanops.nansem(self._ndarray, axis=axis, skipna=skipna, ddof=ddof) - def kurt(self, axis=None, dtype=None, out=None, keepdims=False, skipna=True): + def kurt(self, *, axis=None, dtype=None, out=None, keepdims=False, skipna=True): nv.validate_stat_ddof_func( (), dict(dtype=dtype, out=out, keepdims=keepdims), fname="kurt" ) return nanops.nankurt(self._ndarray, axis=axis, skipna=skipna) - def skew(self, axis=None, dtype=None, out=None, keepdims=False, skipna=True): + def skew(self, *, axis=None, dtype=None, out=None, keepdims=False, skipna=True): nv.validate_stat_ddof_func( (), dict(dtype=dtype, out=out, keepdims=keepdims), fname="skew" ) diff --git a/pandas/core/arrays/timedeltas.py b/pandas/core/arrays/timedeltas.py index c948291f29aeb..0d9d257810674 100644 --- a/pandas/core/arrays/timedeltas.py +++ b/pandas/core/arrays/timedeltas.py @@ -370,6 +370,7 @@ def __iter__(self): def sum( self, + *, axis=None, dtype=None, out=None, diff --git a/pandas/core/nanops.py b/pandas/core/nanops.py index fdf27797db3ab..8e917bb770247 100644 --- a/pandas/core/nanops.py +++ b/pandas/core/nanops.py @@ -97,7 +97,11 @@ def __call__(self, alt: F) -> F: @functools.wraps(alt) def f( - values: np.ndarray, axis: Optional[int] = None, skipna: bool = True, **kwds + values: np.ndarray, + *, + axis: Optional[int] = None, + skipna: bool = True, + **kwds, ): if len(self.kwargs) > 0: for k, v in self.kwargs.items(): @@ -404,6 +408,7 @@ def _na_for_min_count( def nanany( values: np.ndarray, + *, axis: Optional[int] = None, skipna: bool = True, mask: Optional[np.ndarray] = None, @@ -441,6 +446,7 @@ def nanany( def nanall( values: np.ndarray, + *, axis: Optional[int] = None, skipna: bool = True, mask: Optional[np.ndarray] = None, @@ -479,6 +485,7 @@ def nanall( @disallow("M8") def nansum( values: np.ndarray, + *, axis: Optional[int] = None, skipna: bool = True, min_count: int = 0, @@ -550,6 +557,7 @@ def _mask_datetimelike_result( @bottleneck_switch() def nanmean( values: np.ndarray, + *, axis: Optional[int] = None, skipna: bool = True, mask: Optional[np.ndarray] = None, @@ -618,7 +626,7 @@ def nanmean( @bottleneck_switch() -def nanmedian(values, axis=None, skipna=True, mask=None): +def nanmedian(values, *, axis=None, skipna=True, mask=None): """ Parameters ---------- @@ -766,7 +774,7 @@ def _get_counts_nanvar( @bottleneck_switch(ddof=1) -def nanstd(values, axis=None, skipna=True, ddof=1, mask=None): +def nanstd(values, *, axis=None, skipna=True, ddof=1, mask=None): """ Compute the standard deviation along given axis while ignoring NaNs @@ -806,7 +814,7 @@ def nanstd(values, axis=None, skipna=True, ddof=1, mask=None): @disallow("M8", "m8") @bottleneck_switch(ddof=1) -def nanvar(values, axis=None, skipna=True, ddof=1, mask=None): +def nanvar(values, *, axis=None, skipna=True, ddof=1, mask=None): """ Compute the variance along given axis while ignoring NaNs @@ -876,6 +884,7 @@ def nanvar(values, axis=None, skipna=True, ddof=1, mask=None): @disallow("M8", "m8") def nansem( values: np.ndarray, + *, axis: Optional[int] = None, skipna: bool = True, ddof: int = 1, @@ -910,14 +919,14 @@ def nansem( """ # This checks if non-numeric-like data is passed with numeric_only=False # and raises a TypeError otherwise - nanvar(values, axis, skipna, ddof=ddof, mask=mask) + nanvar(values, axis=axis, skipna=skipna, ddof=ddof, mask=mask) mask = _maybe_get_mask(values, skipna, mask) if not is_float_dtype(values.dtype): values = values.astype("f8") count, _ = _get_counts_nanvar(values.shape, mask, axis, ddof, values.dtype) - var = nanvar(values, axis, skipna, ddof=ddof) + var = nanvar(values, axis=axis, skipna=skipna, ddof=ddof) return np.sqrt(var) / np.sqrt(count) @@ -926,6 +935,7 @@ def _nanminmax(meth, fill_value_typ): @bottleneck_switch(name="nan" + meth) def reduction( values: np.ndarray, + *, axis: Optional[int] = None, skipna: bool = True, mask: Optional[np.ndarray] = None, @@ -965,6 +975,7 @@ def reduction( @disallow("O") def nanargmax( values: np.ndarray, + *, axis: Optional[int] = None, skipna: bool = True, mask: Optional[np.ndarray] = None, @@ -1009,6 +1020,7 @@ def nanargmax( @disallow("O") def nanargmin( values: np.ndarray, + *, axis: Optional[int] = None, skipna: bool = True, mask: Optional[np.ndarray] = None, @@ -1053,6 +1065,7 @@ def nanargmin( @disallow("M8", "m8") def nanskew( values: np.ndarray, + *, axis: Optional[int] = None, skipna: bool = True, mask: Optional[np.ndarray] = None, @@ -1137,6 +1150,7 @@ def nanskew( @disallow("M8", "m8") def nankurt( values: np.ndarray, + *, axis: Optional[int] = None, skipna: bool = True, mask: Optional[np.ndarray] = None, @@ -1230,6 +1244,7 @@ def nankurt( @disallow("M8", "m8") def nanprod( values: np.ndarray, + *, axis: Optional[int] = None, skipna: bool = True, min_count: int = 0, @@ -1409,7 +1424,7 @@ def _zero_out_fperr(arg): @disallow("M8", "m8") def nancorr( - a: np.ndarray, b: np.ndarray, method="pearson", min_periods: Optional[int] = None + a: np.ndarray, b: np.ndarray, *, method="pearson", min_periods: Optional[int] = None ): """ a, b: ndarrays @@ -1466,6 +1481,7 @@ def func(a, b): def nancov( a: np.ndarray, b: np.ndarray, + *, min_periods: Optional[int] = None, ddof: Optional[int] = 1, ): @@ -1581,6 +1597,7 @@ def _nanpercentile_1d( def nanpercentile( values: np.ndarray, q, + *, axis: int, na_value, mask: np.ndarray, @@ -1609,7 +1626,13 @@ def nanpercentile( if values.dtype.kind in ["m", "M"]: # need to cast to integer to avoid rounding errors in numpy result = nanpercentile( - values.view("i8"), q, axis, na_value.view("i8"), mask, ndim, interpolation + values.view("i8"), + q=q, + axis=axis, + na_value=na_value.view("i8"), + mask=mask, + ndim=ndim, + interpolation=interpolation, ) # Note: we have to do do `astype` and not view because in general we @@ -1638,7 +1661,7 @@ def nanpercentile( return np.percentile(values, q, axis=axis, interpolation=interpolation) -def na_accum_func(values: ArrayLike, accum_func, skipna: bool) -> ArrayLike: +def na_accum_func(values: ArrayLike, accum_func, *, skipna: bool) -> ArrayLike: """ Cumulative function with skipna support.
https://api.github.com/repos/pandas-dev/pandas/pulls/37541
2020-10-31T19:30:48Z
2020-11-01T00:02:14Z
2020-11-01T00:02:14Z
2020-11-01T00:03:02Z
CI Move unwanted typing checks to pre-commit
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index b0f35087dc922..0c1e4e330c903 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -119,6 +119,36 @@ repos: entry: python scripts/validate_unwanted_patterns.py --validation-type="private_function_across_module" types: [python] exclude: ^(asv_bench|pandas/tests|doc)/ + - id: FrameOrSeriesUnion + name: Check for use of Union[Series, DataFrame] instead of FrameOrSeriesUnion alias + entry: Union\[.*(Series.*DataFrame|DataFrame.*Series).*\] + language: pygrep + types: [python] + exclude: ^pandas/_typing\.py$ + - id: type-not-class + name: Check for use of foo.__class__ instead of type(foo) + entry: \.__class__ + language: pygrep + files: \.(py|pyx)$ + - id: unwanted-typing + name: Check for use of comment-based annotation syntax and missing error codes + entry: | + (?x) + \#\ type:\ (?!ignore)| + \#\ type:\s?ignore(?!\[) + language: pygrep + types: [python] + - id: no-os-remove + name: Check code for instances of os.remove + entry: os\.remove + language: pygrep + types: [python] + files: ^pandas/tests/ + exclude: | + (?x)^ + pandas/tests/io/excel/test_writers\.py| + pandas/tests/io/pytables/common\.py| + pandas/tests/io/pytables/test_store\.py$ - repo: https://github.com/asottile/yesqa rev: v1.2.2 hooks: diff --git a/ci/code_checks.sh b/ci/code_checks.sh index 7c48905135f89..b5d63e259456b 100755 --- a/ci/code_checks.sh +++ b/ci/code_checks.sh @@ -122,29 +122,6 @@ if [[ -z "$CHECK" || "$CHECK" == "patterns" ]]; then RET=$(($RET + $?)) ; echo $MSG "DONE" # ------------------------------------------------------------------------- - # Type annotations - - MSG='Check for use of comment-based annotation syntax' ; echo $MSG - invgrep -R --include="*.py" -P '# type: (?!ignore)' pandas - RET=$(($RET + $?)) ; echo $MSG "DONE" - - MSG='Check for missing error codes with # type: ignore' ; echo $MSG - invgrep -R --include="*.py" -P '# type:\s?ignore(?!\[)' pandas - RET=$(($RET + $?)) ; echo $MSG "DONE" - - MSG='Check for use of Union[Series, DataFrame] instead of FrameOrSeriesUnion alias' ; echo $MSG - invgrep -R --include="*.py" --exclude=_typing.py -E 'Union\[.*(Series.*DataFrame|DataFrame.*Series).*\]' pandas - RET=$(($RET + $?)) ; echo $MSG "DONE" - - # ------------------------------------------------------------------------- - MSG='Check for use of foo.__class__ instead of type(foo)' ; echo $MSG - invgrep -R --include=*.{py,pyx} '\.__class__' pandas - RET=$(($RET + $?)) ; echo $MSG "DONE" - - MSG='Check code for instances of os.remove' ; echo $MSG - invgrep -R --include="*.py*" --exclude "common.py" --exclude "test_writers.py" --exclude "test_store.py" -E "os\.remove" pandas/tests/ - RET=$(($RET + $?)) ; echo $MSG "DONE" - MSG='Check for inconsistent use of pandas namespace in tests' ; echo $MSG for class in "Series" "DataFrame" "Index" "MultiIndex" "Timestamp" "Timedelta" "TimedeltaIndex" "DatetimeIndex" "Categorical"; do check_namespace ${class} diff --git a/scripts/validate_unwanted_patterns.py b/scripts/validate_unwanted_patterns.py index 7b648a589bc61..9c58a55cb907e 100755 --- a/scripts/validate_unwanted_patterns.py +++ b/scripts/validate_unwanted_patterns.py @@ -474,7 +474,7 @@ def main( sys.exit( main( - function=globals().get(args.validation_type), # type: ignore + function=globals().get(args.validation_type), source_path=args.paths, output_format=args.format, )
There's still some grep-based checks left, but running doctests / running mypy can stay in code_checks
https://api.github.com/repos/pandas-dev/pandas/pulls/37539
2020-10-31T18:03:26Z
2020-11-04T11:01:26Z
2020-11-04T11:01:26Z
2020-11-04T11:03:01Z
Backport PR #37520 on branch 1.1.x (DOC: Start v1.1.5 release notes)
diff --git a/doc/source/whatsnew/index.rst b/doc/source/whatsnew/index.rst index b8abc71ca64a2..ae9228b04f44b 100644 --- a/doc/source/whatsnew/index.rst +++ b/doc/source/whatsnew/index.rst @@ -16,6 +16,7 @@ Version 1.1 .. toctree:: :maxdepth: 2 + v1.1.5 v1.1.4 v1.1.3 v1.1.2 diff --git a/doc/source/whatsnew/v1.1.4.rst b/doc/source/whatsnew/v1.1.4.rst index fb8687b8ba42c..6353dbfafc9f1 100644 --- a/doc/source/whatsnew/v1.1.4.rst +++ b/doc/source/whatsnew/v1.1.4.rst @@ -52,4 +52,4 @@ Bug fixes Contributors ~~~~~~~~~~~~ -.. contributors:: v1.1.3..v1.1.4|HEAD +.. contributors:: v1.1.3..v1.1.4 diff --git a/doc/source/whatsnew/v1.1.5.rst b/doc/source/whatsnew/v1.1.5.rst new file mode 100644 index 0000000000000..cf728d94b2a55 --- /dev/null +++ b/doc/source/whatsnew/v1.1.5.rst @@ -0,0 +1,36 @@ +.. _whatsnew_115: + +What's new in 1.1.5 (??) +------------------------ + +These are the changes in pandas 1.1.5. See :ref:`release` for a full changelog +including other versions of pandas. + +{{ header }} + +.. --------------------------------------------------------------------------- + +.. _whatsnew_115.regressions: + +Fixed regressions +~~~~~~~~~~~~~~~~~ +- +- + +.. --------------------------------------------------------------------------- + +.. _whatsnew_115.bug_fixes: + +Bug fixes +~~~~~~~~~ +- +- + +.. --------------------------------------------------------------------------- + +.. _whatsnew_115.contributors: + +Contributors +~~~~~~~~~~~~ + +.. contributors:: v1.1.4..v1.1.5|HEAD
Backport PR #37520: DOC: Start v1.1.5 release notes
https://api.github.com/repos/pandas-dev/pandas/pulls/37537
2020-10-31T15:13:59Z
2020-10-31T18:25:26Z
2020-10-31T18:25:26Z
2020-10-31T18:25:26Z
BUG: error raise when column contains percentage
diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index bbdcd183f65e1..d34175b9c4feb 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -748,6 +748,7 @@ I/O - Bumped minimum xarray version to 0.12.3 to avoid reference to the removed ``Panel`` class (:issue:`27101`) - :meth:`DataFrame.to_csv` was re-opening file-like handles that also implement ``os.PathLike`` (:issue:`38125`) - Bug in the conversion of a sliced ``pyarrow.Table`` with missing values to a DataFrame (:issue:`38525`) +- Bug in :func:`read_sql_table` raising a ``sqlalchemy.exc.OperationalError`` when column names contained a percentage sign (:issue:`37517`) Period ^^^^^^ diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 836c16c109b57..a6708896f4f2e 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -1237,9 +1237,7 @@ def run_transaction(self): def execute(self, *args, **kwargs): """Simple passthrough to SQLAlchemy connectable""" - return self.connectable.execution_options(no_parameters=True).execute( - *args, **kwargs - ) + return self.connectable.execution_options().execute(*args, **kwargs) def read_table( self, diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 4442d47c9f535..9df8ff9e8ee06 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -1205,6 +1205,15 @@ def test_query_by_select_obj(self): all_names = set(iris_df["Name"]) assert all_names == {"Iris-setosa"} + def test_column_with_percentage(self): + # GH 37157 + df = DataFrame({"A": [0, 1, 2], "%_variation": [3, 4, 5]}) + df.to_sql("test_column_percentage", self.conn, index=False) + + res = sql.read_sql_table("test_column_percentage", self.conn) + + tm.assert_frame_equal(res, df) + class _EngineToConnMixin: """
- [x] closes #37157 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37534
2020-10-31T13:44:42Z
2020-12-22T13:57:18Z
2020-12-22T13:57:17Z
2020-12-22T16:50:06Z
TYP: obj in aggregation.py
diff --git a/pandas/_typing.py b/pandas/_typing.py index 2244be1b61fc6..a0578b49d5ecc 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -35,8 +35,11 @@ from pandas.core.arrays.base import ExtensionArray # noqa: F401 from pandas.core.frame import DataFrame from pandas.core.generic import NDFrame # noqa: F401 + from pandas.core.groupby.generic import DataFrameGroupBy, SeriesGroupBy from pandas.core.indexes.base import Index + from pandas.core.resample import Resampler from pandas.core.series import Series + from pandas.core.window.rolling import BaseWindow from pandas.io.formats.format import EngFormatter @@ -115,6 +118,14 @@ List[AggFuncTypeBase], AggFuncTypeDict, ] +AggObjType = Union[ + "Series", + "DataFrame", + "SeriesGroupBy", + "DataFrameGroupBy", + "BaseWindow", + "Resampler", +] # for arbitrary kwargs passed during reading/writing files diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py index ffc3283152687..c64f0bd71cf84 100644 --- a/pandas/core/aggregation.py +++ b/pandas/core/aggregation.py @@ -24,6 +24,7 @@ AggFuncType, AggFuncTypeBase, AggFuncTypeDict, + AggObjType, Axis, FrameOrSeries, FrameOrSeriesUnion, @@ -530,7 +531,7 @@ def transform_str_or_callable( def aggregate( - obj, + obj: AggObjType, arg: AggFuncType, *args, **kwargs, @@ -580,7 +581,7 @@ def aggregate( def agg_list_like( - obj, + obj: AggObjType, arg: List[AggFuncTypeBase], _axis: int, ) -> FrameOrSeriesUnion: @@ -672,7 +673,7 @@ def agg_list_like( def agg_dict_like( - obj, + obj: AggObjType, arg: AggFuncTypeDict, _axis: int, ) -> FrameOrSeriesUnion:
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37532
2020-10-31T02:25:13Z
2020-10-31T23:21:04Z
2020-10-31T23:21:04Z
2020-12-06T14:04:51Z
CLN/TYP: Alias for aggregation dictionary argument
diff --git a/pandas/_typing.py b/pandas/_typing.py index a9177106535fc..2244be1b61fc6 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -109,12 +109,14 @@ # types of `func` kwarg for DataFrame.aggregate and Series.aggregate AggFuncTypeBase = Union[Callable, str] +AggFuncTypeDict = Dict[Label, Union[AggFuncTypeBase, List[AggFuncTypeBase]]] AggFuncType = Union[ AggFuncTypeBase, List[AggFuncTypeBase], - Dict[Label, Union[AggFuncTypeBase, List[AggFuncTypeBase]]], + AggFuncTypeDict, ] + # for arbitrary kwargs passed during reading/writing files StorageOptions = Optional[Dict[str, Any]] diff --git a/pandas/core/aggregation.py b/pandas/core/aggregation.py index 639b5f31835d1..ffc3283152687 100644 --- a/pandas/core/aggregation.py +++ b/pandas/core/aggregation.py @@ -23,6 +23,7 @@ from pandas._typing import ( AggFuncType, AggFuncTypeBase, + AggFuncTypeDict, Axis, FrameOrSeries, FrameOrSeriesUnion, @@ -442,7 +443,7 @@ def transform( func = {col: func for col in obj} if is_dict_like(func): - func = cast(Dict[Label, Union[AggFuncTypeBase, List[AggFuncTypeBase]]], func) + func = cast(AggFuncTypeDict, func) return transform_dict_like(obj, func, *args, **kwargs) # func is either str or callable @@ -466,7 +467,7 @@ def transform( def transform_dict_like( obj: FrameOrSeries, - func: Dict[Label, Union[AggFuncTypeBase, List[AggFuncTypeBase]]], + func: AggFuncTypeDict, *args, **kwargs, ): @@ -560,7 +561,7 @@ def aggregate( if isinstance(arg, str): return obj._try_aggregate_string_function(arg, *args, **kwargs), None elif is_dict_like(arg): - arg = cast(Dict[Label, Union[AggFuncTypeBase, List[AggFuncTypeBase]]], arg) + arg = cast(AggFuncTypeDict, arg) return agg_dict_like(obj, arg, _axis), True elif is_list_like(arg): # we require a list, but not an 'str' @@ -672,7 +673,7 @@ def agg_list_like( def agg_dict_like( obj, - arg: Dict[Label, Union[AggFuncTypeBase, List[AggFuncTypeBase]]], + arg: AggFuncTypeDict, _axis: int, ) -> FrameOrSeriesUnion: """ @@ -701,7 +702,7 @@ def agg_dict_like( # eg. {'A' : ['mean']}, normalize all to # be list-likes if any(is_aggregator(x) for x in arg.values()): - new_arg: Dict[Label, Union[AggFuncTypeBase, List[AggFuncTypeBase]]] = {} + new_arg: AggFuncTypeDict = {} for k, v in arg.items(): if not isinstance(v, (tuple, list, dict)): new_arg[k] = [v]
- [ ] closes #xxxx - [ ] tests added / passed - [ ] passes `black pandas` - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/37531
2020-10-31T02:11:29Z
2020-10-31T15:36:33Z
2020-10-31T15:36:33Z
2020-12-06T14:04:50Z
REF: share delete, putmask, insert between ndarray-backed EA indexes
diff --git a/pandas/core/arrays/_mixins.py b/pandas/core/arrays/_mixins.py index 726ca0ce4d776..3eb4615f1fe3e 100644 --- a/pandas/core/arrays/_mixins.py +++ b/pandas/core/arrays/_mixins.py @@ -44,6 +44,10 @@ def _box_func(self, x): """ return x + def _validate_insert_value(self, value): + # used by NDArrayBackedExtensionIndex.insert + raise AbstractMethodError(self) + # ------------------------------------------------------------------------ def take( diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index fb0e710921a5f..c137509a2cd2d 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -27,7 +27,7 @@ from pandas.core.construction import extract_array import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs, maybe_extract_name -from pandas.core.indexes.extension import ExtensionIndex, inherit_names +from pandas.core.indexes.extension import NDArrayBackedExtensionIndex, inherit_names import pandas.core.missing as missing from pandas.core.ops import get_op_result_name @@ -66,7 +66,7 @@ typ="method", overwrite=True, ) -class CategoricalIndex(ExtensionIndex, accessor.PandasDelegate): +class CategoricalIndex(NDArrayBackedExtensionIndex, accessor.PandasDelegate): """ Index based on an underlying :class:`Categorical`. @@ -425,17 +425,6 @@ def where(self, cond, other=None): cat = Categorical(values, dtype=self.dtype) return type(self)._simple_new(cat, name=self.name) - def putmask(self, mask, value): - try: - code_value = self._data._validate_where_value(value) - except (TypeError, ValueError): - return self.astype(object).putmask(mask, value) - - codes = self._data._ndarray.copy() - np.putmask(codes, mask, code_value) - cat = self._data._from_backing_data(codes) - return type(self)._simple_new(cat, name=self.name) - def reindex(self, target, method=None, level=None, limit=None, tolerance=None): """ Create index with target's values (move/add/delete values as necessary) @@ -665,44 +654,6 @@ def map(self, mapper): mapped = self._values.map(mapper) return Index(mapped, name=self.name) - def delete(self, loc): - """ - Make new Index with passed location(-s) deleted - - Returns - ------- - new_index : Index - """ - codes = np.delete(self.codes, loc) - cat = self._data._from_backing_data(codes) - return type(self)._simple_new(cat, name=self.name) - - def insert(self, loc: int, item): - """ - Make new Index inserting new item at location. Follows - Python list.append semantics for negative values - - Parameters - ---------- - loc : int - item : object - - Returns - ------- - new_index : Index - - Raises - ------ - ValueError if the item is not in the categories - - """ - code = self._data._validate_insert_value(item) - - codes = self.codes - codes = np.concatenate((codes[:loc], [code], codes[loc:])) - cat = self._data._from_backing_data(codes) - return type(self)._simple_new(cat, name=self.name) - def _concat(self, to_concat, name): # if calling index is category, don't check dtype of others codes = np.concatenate([self._is_dtype_compat(c).codes for c in to_concat]) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index 25c6de3d255e3..751eafaa0d78e 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -33,7 +33,7 @@ import pandas.core.indexes.base as ibase from pandas.core.indexes.base import Index, _index_shared_docs from pandas.core.indexes.extension import ( - ExtensionIndex, + NDArrayBackedExtensionIndex, inherit_names, make_wrapped_arith_op, ) @@ -82,7 +82,7 @@ def wrapper(left, right): cache=True, ) @inherit_names(["mean", "asi8", "freq", "freqstr"], DatetimeLikeArrayMixin) -class DatetimeIndexOpsMixin(ExtensionIndex): +class DatetimeIndexOpsMixin(NDArrayBackedExtensionIndex): """ Common ops mixin to support a unified interface datetimelike Index. """ @@ -191,7 +191,7 @@ def take(self, indices, axis=0, allow_fill=True, fill_value=None, **kwargs): maybe_slice = lib.maybe_indices_to_slice(indices, len(self)) - result = ExtensionIndex.take( + result = NDArrayBackedExtensionIndex.take( self, indices, axis, allow_fill, fill_value, **kwargs ) if isinstance(maybe_slice, slice): @@ -496,17 +496,6 @@ def where(self, cond, other=None): arr = self._data._from_backing_data(result) return type(self)._simple_new(arr, name=self.name) - def putmask(self, mask, value): - try: - value = self._data._validate_where_value(value) - except (TypeError, ValueError): - return self.astype(object).putmask(mask, value) - - result = self._data._ndarray.copy() - np.putmask(result, mask, value) - arr = self._data._from_backing_data(result) - return type(self)._simple_new(arr, name=self.name) - def _summary(self, name=None) -> str: """ Return a summarized representation. @@ -575,41 +564,30 @@ def shift(self, periods=1, freq=None): # -------------------------------------------------------------------- # List-like Methods - def delete(self, loc): - new_i8s = np.delete(self.asi8, loc) - + def _get_delete_freq(self, loc: int): + """ + Find the `freq` for self.delete(loc). + """ freq = None if is_period_dtype(self.dtype): freq = self.freq - elif is_integer(loc): - if loc in (0, -len(self), -1, len(self) - 1): - freq = self.freq - else: - if is_list_like(loc): - loc = lib.maybe_indices_to_slice( - np.asarray(loc, dtype=np.intp), len(self) - ) - if isinstance(loc, slice) and loc.step in (1, None): - if loc.start in (0, None) or loc.stop in (len(self), None): + elif self.freq is not None: + if is_integer(loc): + if loc in (0, -len(self), -1, len(self) - 1): freq = self.freq + else: + if is_list_like(loc): + loc = lib.maybe_indices_to_slice( + np.asarray(loc, dtype=np.intp), len(self) + ) + if isinstance(loc, slice) and loc.step in (1, None): + if loc.start in (0, None) or loc.stop in (len(self), None): + freq = self.freq + return freq - arr = type(self._data)._simple_new(new_i8s, dtype=self.dtype, freq=freq) - return type(self)._simple_new(arr, name=self.name) - - def insert(self, loc: int, item): + def _get_insert_freq(self, loc, item): """ - Make new Index inserting new item at location - - Parameters - ---------- - loc : int - item : object - if not either a Python datetime or a numpy integer-like, returned - Index dtype will be object rather than datetime. - - Returns - ------- - new_index : Index + Find the `freq` for self.insert(loc, item). """ value = self._data._validate_insert_value(item) item = self._data._box_func(value) @@ -630,14 +608,20 @@ def insert(self, loc: int, item): # Adding a single item to an empty index may preserve freq if self.freq.is_on_offset(item): freq = self.freq + return freq - arr = self._data + @doc(NDArrayBackedExtensionIndex.delete) + def delete(self, loc): + result = super().delete(loc) + result._data._freq = self._get_delete_freq(loc) + return result - new_values = np.concatenate([arr._ndarray[:loc], [value], arr._ndarray[loc:]]) - new_arr = self._data._from_backing_data(new_values) - new_arr._freq = freq + @doc(NDArrayBackedExtensionIndex.insert) + def insert(self, loc: int, item): + result = super().insert(loc, item) - return type(self)._simple_new(new_arr, name=self.name) + result._data._freq = self._get_insert_freq(loc, item) + return result # -------------------------------------------------------------------- # Join/Set Methods diff --git a/pandas/core/indexes/extension.py b/pandas/core/indexes/extension.py index 4da1a43468b57..1f26ceaf2d1b7 100644 --- a/pandas/core/indexes/extension.py +++ b/pandas/core/indexes/extension.py @@ -13,6 +13,7 @@ from pandas.core.dtypes.generic import ABCDataFrame, ABCSeries from pandas.core.arrays import ExtensionArray +from pandas.core.arrays._mixins import NDArrayBackedExtensionArray from pandas.core.indexers import deprecate_ndim_indexing from pandas.core.indexes.base import Index from pandas.core.ops import get_op_result_name @@ -281,3 +282,59 @@ def astype(self, dtype, copy=True): @cache_readonly def _isnan(self) -> np.ndarray: return self._data.isna() + + +class NDArrayBackedExtensionIndex(ExtensionIndex): + """ + Index subclass for indexes backed by NDArrayBackedExtensionArray. + """ + + _data: NDArrayBackedExtensionArray + + def delete(self, loc): + """ + Make new Index with passed location(-s) deleted + + Returns + ------- + new_index : Index + """ + new_vals = np.delete(self._data._ndarray, loc) + arr = self._data._from_backing_data(new_vals) + return type(self)._simple_new(arr, name=self.name) + + def insert(self, loc: int, item): + """ + Make new Index inserting new item at location. Follows + Python list.append semantics for negative values. + + Parameters + ---------- + loc : int + item : object + + Returns + ------- + new_index : Index + + Raises + ------ + ValueError if the item is not valid for this dtype. + """ + arr = self._data + code = arr._validate_insert_value(item) + + new_vals = np.concatenate((arr._ndarray[:loc], [code], arr._ndarray[loc:])) + new_arr = arr._from_backing_data(new_vals) + return type(self)._simple_new(new_arr, name=self.name) + + def putmask(self, mask, value): + try: + value = self._data._validate_where_value(value) + except (TypeError, ValueError): + return self.astype(object).putmask(mask, value) + + new_values = self._data._ndarray.copy() + np.putmask(new_values, mask, value) + new_arr = self._data._from_backing_data(new_values) + return type(self)._simple_new(new_arr, name=self.name) diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 7f0dc2426eba7..2a268e0003490 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -872,7 +872,7 @@ def where(self, cond, other=None): other = self._na_value values = np.where(cond, self._values, other) result = IntervalArray(values) - return self._shallow_copy(result) + return type(self)._simple_new(result, name=self.name) def delete(self, loc): """
https://api.github.com/repos/pandas-dev/pandas/pulls/37529
2020-10-31T01:27:09Z
2020-10-31T17:14:09Z
2020-10-31T17:14:09Z
2020-10-31T18:09:02Z
BUG: isin incorrectly casting ints to datetimes
diff --git a/asv_bench/benchmarks/series_methods.py b/asv_bench/benchmarks/series_methods.py index 3b65bccd48aee..2db46abca119c 100644 --- a/asv_bench/benchmarks/series_methods.py +++ b/asv_bench/benchmarks/series_methods.py @@ -2,7 +2,7 @@ import numpy as np -from pandas import NaT, Series, date_range +from pandas import Categorical, NaT, Series, date_range from .pandas_vb_common import tm @@ -36,6 +36,28 @@ def time_isin(self, dtypes): self.s.isin(self.values) +class IsInDatetime64: + def setup(self): + dti = date_range( + start=datetime(2015, 10, 26), end=datetime(2016, 1, 1), freq="50s" + ) + self.ser = Series(dti) + self.subset = self.ser._values[::3] + self.cat_subset = Categorical(self.subset) + + def time_isin(self): + self.ser.isin(self.subset) + + def time_isin_cat_values(self): + self.ser.isin(self.cat_subset) + + def time_isin_mismatched_dtype(self): + self.ser.isin([1, 2]) + + def time_isin_empty(self): + self.ser.isin([]) + + class IsInFloat64: def setup(self): self.small = Series([1, 2], dtype=np.float64) diff --git a/doc/source/whatsnew/v1.2.0.rst b/doc/source/whatsnew/v1.2.0.rst index bc5229d4b4296..0222fe306585f 100644 --- a/doc/source/whatsnew/v1.2.0.rst +++ b/doc/source/whatsnew/v1.2.0.rst @@ -538,6 +538,9 @@ Datetimelike - Bug in :meth:`DatetimeArray.shift` incorrectly allowing ``fill_value`` with a mismatched timezone (:issue:`37299`) - Bug in adding a :class:`BusinessDay` with nonzero ``offset`` to a non-scalar other (:issue:`37457`) - Bug in :func:`to_datetime` with a read-only array incorrectly raising (:issue:`34857`) +- Bug in :meth:`Series.isin` with ``datetime64[ns]`` dtype and :meth:`DatetimeIndex.isin` incorrectly casting integers to datetimes (:issue:`36621`) +- Bug in :meth:`Series.isin` with ``datetime64[ns]`` dtype and :meth:`DatetimeIndex.isin` failing to consider timezone-aware and timezone-naive datetimes as always different (:issue:`35728`) +- Bug in :meth:`Series.isin` with ``PeriodDtype`` dtype and :meth:`PeriodIndex.isin` failing to consider arguments with different ``PeriodDtype`` as always different (:issue:`37528`) Timedelta ^^^^^^^^^ diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index ca878d3293c57..be091314e6c25 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -430,6 +430,12 @@ def isin(comps: AnyArrayLike, values: AnyArrayLike) -> np.ndarray: # handle categoricals return cast("Categorical", comps).isin(values) + if needs_i8_conversion(comps): + # Dispatch to DatetimeLikeIndexMixin.isin + from pandas import Index + + return Index(comps).isin(values) + comps, dtype = _ensure_data(comps) values, _ = _ensure_data(values, dtype=dtype) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index f0b37b810b28a..48db6051b186d 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -491,12 +491,40 @@ def isin(self, values, level=None): if level is not None: self._validate_index_level(level) + if not hasattr(values, "dtype"): + values = np.asarray(values) + + if values.dtype.kind in ["f", "i", "u", "c"]: + # TODO: de-duplicate with equals, validate_comparison_value + return np.zeros(self.shape, dtype=bool) + if not isinstance(values, type(self)): + inferrable = [ + "timedelta", + "timedelta64", + "datetime", + "datetime64", + "date", + "period", + ] + if values.dtype == object: + inferred = lib.infer_dtype(values, skipna=False) + if inferred not in inferrable: + if "mixed" in inferred: + return self.astype(object).isin(values) + return np.zeros(self.shape, dtype=bool) + try: values = type(self)(values) except ValueError: return self.astype(object).isin(values) + try: + self._data._check_compatible_with(values) + except (TypeError, ValueError): + # Includes tzawareness mismatch and IncompatibleFrequencyError + return np.zeros(self.shape, dtype=bool) + return algorithms.isin(self.asi8, values.asi8) @Appender(Index.where.__doc__) diff --git a/pandas/tests/series/methods/test_isin.py b/pandas/tests/series/methods/test_isin.py index 86ea2b2f02a4d..071b1f3f75f44 100644 --- a/pandas/tests/series/methods/test_isin.py +++ b/pandas/tests/series/methods/test_isin.py @@ -4,6 +4,7 @@ import pandas as pd from pandas import Series, date_range import pandas._testing as tm +from pandas.core.arrays import PeriodArray class TestSeriesIsIn: @@ -90,6 +91,60 @@ def test_isin_read_only(self): expected = Series([True, True, True]) tm.assert_series_equal(result, expected) + @pytest.mark.parametrize("dtype", [object, None]) + def test_isin_dt64_values_vs_ints(self, dtype): + # GH#36621 dont cast integers to datetimes for isin + dti = date_range("2013-01-01", "2013-01-05") + ser = Series(dti) + + comps = np.asarray([1356998400000000000], dtype=dtype) + + res = dti.isin(comps) + expected = np.array([False] * len(dti), dtype=bool) + tm.assert_numpy_array_equal(res, expected) + + res = ser.isin(comps) + tm.assert_series_equal(res, Series(expected)) + + res = pd.core.algorithms.isin(ser, comps) + tm.assert_numpy_array_equal(res, expected) + + def test_isin_tzawareness_mismatch(self): + dti = date_range("2013-01-01", "2013-01-05") + ser = Series(dti) + + other = dti.tz_localize("UTC") + + res = dti.isin(other) + expected = np.array([False] * len(dti), dtype=bool) + tm.assert_numpy_array_equal(res, expected) + + res = ser.isin(other) + tm.assert_series_equal(res, Series(expected)) + + res = pd.core.algorithms.isin(ser, other) + tm.assert_numpy_array_equal(res, expected) + + def test_isin_period_freq_mismatch(self): + dti = date_range("2013-01-01", "2013-01-05") + pi = dti.to_period("M") + ser = Series(pi) + + # We construct another PeriodIndex with the same i8 values + # but different dtype + dtype = dti.to_period("Y").dtype + other = PeriodArray._simple_new(pi.asi8, dtype=dtype) + + res = pi.isin(other) + expected = np.array([False] * len(pi), dtype=bool) + tm.assert_numpy_array_equal(res, expected) + + res = ser.isin(other) + tm.assert_series_equal(res, Series(expected)) + + res = pd.core.algorithms.isin(ser, other) + tm.assert_numpy_array_equal(res, expected) + @pytest.mark.slow def test_isin_large_series_mixed_dtypes_and_nan():
- [x] closes #36621 - [x] tests added / passed - [x] passes `black pandas` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry De-duplication in follow-up.
https://api.github.com/repos/pandas-dev/pandas/pulls/37528
2020-10-30T23:26:50Z
2020-11-22T02:12:25Z
2020-11-22T02:12:25Z
2020-11-22T02:43:22Z
TYP: use typing.final in indexes.base
diff --git a/pandas/_typing.py b/pandas/_typing.py index 2244be1b61fc6..cebebc7c2a626 100644 --- a/pandas/_typing.py +++ b/pandas/_typing.py @@ -27,6 +27,8 @@ # and use a string literal forward reference to it in subsequent types # https://mypy.readthedocs.io/en/latest/common_issues.html#import-cycles if TYPE_CHECKING: + from typing import final + from pandas._libs import Period, Timedelta, Timestamp from pandas.core.dtypes.dtypes import ExtensionDtype @@ -39,6 +41,10 @@ from pandas.core.series import Series from pandas.io.formats.format import EngFormatter +else: + # typing.final does not exist until py38 + final = lambda x: x + # array-like diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 48dcdfb3ecfff..1938722225b98 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -27,7 +27,7 @@ from pandas._libs.lib import is_datetime_array, no_default from pandas._libs.tslibs import IncompatibleFrequency, OutOfBoundsDatetime, Timestamp from pandas._libs.tslibs.timezones import tz_compare -from pandas._typing import AnyArrayLike, Dtype, DtypeObj, Label +from pandas._typing import AnyArrayLike, Dtype, DtypeObj, Label, final from pandas.compat.numpy import function as nv from pandas.errors import DuplicateLabelError, InvalidIndexError from pandas.util._decorators import Appender, cache_readonly, doc @@ -445,6 +445,7 @@ def _simple_new(cls, values, name: Label = None): def _constructor(self): return type(self) + @final def _maybe_check_unique(self): """ Check that an Index has no duplicates. @@ -465,6 +466,7 @@ def _maybe_check_unique(self): raise DuplicateLabelError(msg) + @final def _format_duplicate_message(self): """ Construct the DataFrame for a DuplicateLabelError. @@ -494,6 +496,7 @@ def _format_duplicate_message(self): # -------------------------------------------------------------------- # Index Internals Methods + @final def _get_attributes_dict(self): """ Return an attributes dict for my class. @@ -522,6 +525,7 @@ def _shallow_copy(self, values=None, name: Label = no_default): result._cache = self._cache return result + @final def is_(self, other) -> bool: """ More flexible, faster check like ``is`` but that works through views. @@ -552,12 +556,14 @@ def is_(self, other) -> bool: else: return self._id is other._id + @final def _reset_identity(self) -> None: """ Initializes or resets ``_id`` attribute with new object. """ self._id = _Identity(object()) + @final def _cleanup(self): self._engine.clear_mapping() @@ -617,6 +623,7 @@ def dtype(self): """ return self._data.dtype + @final def ravel(self, order="C"): """ Return an ndarray of the flattened values of the underlying data. @@ -871,9 +878,11 @@ def copy( new_index = new_index.astype(dtype) return new_index + @final def __copy__(self, **kwargs): return self.copy(**kwargs) + @final def __deepcopy__(self, memo=None): """ Parameters @@ -1242,6 +1251,7 @@ def name(self, value): maybe_extract_name(value, None, type(self)) self._name = value + @final def _validate_names(self, name=None, names=None, deep: bool = False) -> List[Label]: """ Handles the quirks of having a singular 'name' parameter for general @@ -1304,6 +1314,7 @@ def _set_names(self, values, level=None): names = property(fset=_set_names, fget=_get_names) + @final def set_names(self, names, level=None, inplace: bool = False): """ Set Index or MultiIndex name. @@ -1449,6 +1460,7 @@ def _sort_levels_monotonic(self): """ return self + @final def _validate_index_level(self, level): """ Validate index level. @@ -1550,6 +1562,7 @@ def _get_level_values(self, level): get_level_values = _get_level_values + @final def droplevel(self, level=0): """ Return index with requested level(s) removed. @@ -1649,6 +1662,7 @@ def _get_grouper_for_level(self, mapper, level=None): # -------------------------------------------------------------------- # Introspection Methods + @final @property def is_monotonic(self) -> bool: """ @@ -1763,6 +1777,7 @@ def has_duplicates(self) -> bool: """ return not self.is_unique + @final def is_boolean(self) -> bool: """ Check if the Index only consists of booleans. @@ -1798,6 +1813,7 @@ def is_boolean(self) -> bool: """ return self.inferred_type in ["boolean"] + @final def is_integer(self) -> bool: """ Check if the Index only consists of integers. @@ -1833,6 +1849,7 @@ def is_integer(self) -> bool: """ return self.inferred_type in ["integer"] + @final def is_floating(self) -> bool: """ Check if the Index is a floating type. @@ -1876,6 +1893,7 @@ def is_floating(self) -> bool: """ return self.inferred_type in ["floating", "mixed-integer-float", "integer-na"] + @final def is_numeric(self) -> bool: """ Check if the Index only consists of numeric data. @@ -1919,6 +1937,7 @@ def is_numeric(self) -> bool: """ return self.inferred_type in ["integer", "floating"] + @final def is_object(self) -> bool: """ Check if the Index is of the object dtype. @@ -1959,6 +1978,7 @@ def is_object(self) -> bool: """ return is_object_dtype(self.dtype) + @final def is_categorical(self) -> bool: """ Check if the Index holds categorical data. @@ -2002,6 +2022,7 @@ def is_categorical(self) -> bool: """ return self.inferred_type in ["categorical"] + @final def is_interval(self) -> bool: """ Check if the Index holds Interval objects. @@ -2035,6 +2056,7 @@ def is_interval(self) -> bool: """ return self.inferred_type in ["interval"] + @final def is_mixed(self) -> bool: """ Check if the Index holds data with mixed data types. @@ -2072,6 +2094,7 @@ def is_mixed(self) -> bool: ) return self.inferred_type in ["mixed"] + @final def holds_integer(self) -> bool: """ Whether the type is an integer type. @@ -2133,6 +2156,7 @@ def _isnan(self): return values @cache_readonly + @final def _nan_idxs(self): if self._can_hold_na: return self._isnan.nonzero()[0] @@ -2149,6 +2173,7 @@ def hasnans(self) -> bool: else: return False + @final def isna(self): """ Detect missing values. @@ -2206,6 +2231,7 @@ def isna(self): isnull = isna + @final def notna(self): """ Detect existing (non-missing) values. @@ -2333,6 +2359,7 @@ def unique(self, level=None): result = super().unique() return self._shallow_copy(result) + @final def drop_duplicates(self, keep="first"): """ Return Index with duplicate values removed. @@ -2483,15 +2510,19 @@ def __iadd__(self, other): # alias for __add__ return self + other + @final def __and__(self, other): return self.intersection(other) + @final def __or__(self, other): return self.union(other) + @final def __xor__(self, other): return self.symmetric_difference(other) + @final def __nonzero__(self): raise ValueError( f"The truth value of a {type(self).__name__} is ambiguous. " @@ -2503,6 +2534,7 @@ def __nonzero__(self): # -------------------------------------------------------------------- # Set Operation Methods + @final def _get_reconciled_name_object(self, other): """ If the result of a set operation will be self, @@ -2514,6 +2546,7 @@ def _get_reconciled_name_object(self, other): return self.rename(name) return self + @final def _union_incompatible_dtypes(self, other, sort): """ Casts this and other index to object dtype to allow the formation @@ -2554,6 +2587,7 @@ def _can_union_without_object_cast(self, other) -> bool: """ return type(self) is type(other) and is_dtype_equal(self.dtype, other.dtype) + @final def _validate_sort_keyword(self, sort): if sort not in [None, False]: raise ValueError( @@ -2690,6 +2724,7 @@ def _union(self, other, sort): return self._shallow_copy(result) + @final def _wrap_setop_result(self, other, result): if isinstance(self, (ABCDatetimeIndex, ABCTimedeltaIndex)) and isinstance( result, np.ndarray @@ -3100,6 +3135,7 @@ def _convert_tolerance(self, tolerance, target): raise ValueError("list-like tolerance size must match target index size") return tolerance + @final def _get_fill_indexer( self, target: "Index", method: str_t, limit=None, tolerance=None ) -> np.ndarray: @@ -3119,6 +3155,7 @@ def _get_fill_indexer( indexer = self._filter_indexer_tolerance(target_values, indexer, tolerance) return indexer + @final def _get_fill_indexer_searchsorted( self, target: "Index", method: str_t, limit=None ) -> np.ndarray: @@ -3152,6 +3189,7 @@ def _get_fill_indexer_searchsorted( indexer[indexer == len(self)] = -1 return indexer + @final def _get_nearest_indexer(self, target: "Index", limit, tolerance) -> np.ndarray: """ Get the indexer for the nearest index labels; requires an index with @@ -3175,6 +3213,7 @@ def _get_nearest_indexer(self, target: "Index", limit, tolerance) -> np.ndarray: indexer = self._filter_indexer_tolerance(target_values, indexer, tolerance) return indexer + @final def _filter_indexer_tolerance( self, target: Union["Index", np.ndarray, ExtensionArray], @@ -3198,6 +3237,7 @@ def _get_partial_string_timestamp_match_key(self, key): # GH#10331 return key + @final def _validate_positional_slice(self, key: slice): """ For positional indexing, a slice must have either int or None @@ -3331,6 +3371,7 @@ def _convert_list_indexer(self, keyarr): """ return None + @final def _invalid_indexer(self, form: str_t, key): """ Consistent invalid indexer message. @@ -3343,6 +3384,7 @@ def _invalid_indexer(self, form: str_t, key): # -------------------------------------------------------------------- # Reindex Methods + @final def _can_reindex(self, indexer): """ Check if we are allowing reindexing with this particular indexer. @@ -3608,6 +3650,7 @@ def join(self, other, how="left", level=None, return_indexers=False, sort=False) else: return join_index + @final def _join_multi(self, other, how, return_indexers=True): from pandas.core.indexes.multi import MultiIndex from pandas.core.reshape.merge import restore_dropped_levels_multijoin @@ -3687,6 +3730,7 @@ def _join_multi(self, other, how, return_indexers=True): return result[0], result[2], result[1] return result + @final def _join_non_unique(self, other, how="left", return_indexers=False): from pandas.core.reshape.merge import get_join_indexers @@ -4041,6 +4085,7 @@ def where(self, cond, other=None): return Index(values, dtype=dtype, name=self.name) # construction helpers + @final @classmethod def _scalar_data_error(cls, data): # We return the TypeError so that we can raise it from the constructor @@ -4050,6 +4095,7 @@ def _scalar_data_error(cls, data): f"kind, {repr(data)} was passed" ) + @final @classmethod def _string_data_error(cls, data): raise TypeError( @@ -4057,6 +4103,7 @@ def _string_data_error(cls, data): "to explicitly cast to a numeric type" ) + @final def _coerce_scalar_to_index(self, item): """ We need to coerce a scalar to a compat for our index type. @@ -4087,6 +4134,7 @@ def _validate_fill_value(self, value): """ return value + @final def _validate_scalar(self, value): """ Check that this is a scalar value that we can use for setitem-like @@ -4157,9 +4205,11 @@ def __contains__(self, key: Any) -> bool: except (OverflowError, TypeError, ValueError): return False + @final def __hash__(self): raise TypeError(f"unhashable type: {repr(type(self).__name__)}") + @final def __setitem__(self, key, value): raise TypeError("Index does not support mutable operations") @@ -4200,6 +4250,7 @@ def __getitem__(self, key): else: return result + @final def _can_hold_identifiers_and_holds_name(self, name) -> bool: """ Faster check for ``name in self`` when we know `name` is a Python @@ -4353,6 +4404,7 @@ def equals(self, other: object) -> bool: return array_equivalent(self._values, other._values) + @final def identical(self, other) -> bool: """ Similar to equals, but checks that object attributes and types are also equal. @@ -4372,6 +4424,7 @@ def identical(self, other) -> bool: and type(self) == type(other) ) + @final def asof(self, label): """ Return the label from the index, or, if not present, the previous one. @@ -4475,6 +4528,7 @@ def asof_locs(self, where, mask): return result + @final def sort_values( self, return_indexer: bool = False, @@ -4558,6 +4612,7 @@ def sort_values( else: return sorted_index + @final def sort(self, *args, **kwargs): """ Use sort_values instead. @@ -4664,6 +4719,7 @@ def argsort(self, *args, **kwargs) -> np.ndarray: return result.argsort(*args, **kwargs) + @final def get_value(self, series: "Series", key): """ Fast lookup of value from 1-dimensional ndarray. @@ -4730,6 +4786,7 @@ def _get_values_for_loc(self, series: "Series", loc, key): return series.iloc[loc] + @final def set_value(self, arr, key, value): """ Fast lookup of value from 1-dimensional ndarray. @@ -4793,6 +4850,7 @@ def get_indexer_non_unique(self, target): indexer, missing = self._engine.get_indexer_non_unique(tgt_values) return ensure_platform_int(indexer), missing + @final def get_indexer_for(self, target, **kwargs): """ Guaranteed return of an indexer even when non-unique. @@ -4820,6 +4878,7 @@ def _index_as_unique(self): """ return self.is_unique + @final def _maybe_promote(self, other: "Index"): """ When dealing with an object-dtype Index and a non-object Index, see @@ -4850,6 +4909,7 @@ def _is_comparable_dtype(self, dtype: DtypeObj) -> bool: """ return True + @final def groupby(self, values) -> PrettyDict[Hashable, np.ndarray]: """ Group the index labels by a given array of values. @@ -4919,6 +4979,7 @@ def map(self, mapper, na_action=None): return Index(new_values, **attributes) # TODO: De-duplicate with map, xref GH#32349 + @final def _transform_index(self, func, level=None) -> "Index": """ Apply function to all values found in index. @@ -5094,6 +5155,7 @@ def _maybe_cast_indexer(self, key): return com.cast_scalar_indexer(key) return key + @final def _validate_indexer(self, form: str_t, key, kind: str_t): """ If we are positional indexer, validate that we have appropriate @@ -5561,6 +5623,7 @@ def all(self): self._maybe_disable_logical_methods("all") return np.all(self.values) + @final def _maybe_disable_logical_methods(self, opname: str_t): """ raise if this Index subclass does not support any or all.
cc @simonjayhawkins this imports final conditionally following how you did it with Literal
https://api.github.com/repos/pandas-dev/pandas/pulls/37527
2020-10-30T22:42:01Z
2020-11-01T13:56:23Z
2020-11-01T13:56:23Z
2020-11-01T14:47:59Z