title
stringlengths
1
185
diff
stringlengths
0
32.2M
body
stringlengths
0
123k
url
stringlengths
57
58
created_at
stringlengths
20
20
closed_at
stringlengths
20
20
merged_at
stringlengths
20
20
updated_at
stringlengths
20
20
Backport PR #44362 on branch 1.3.x (CI: xfail tests failing on numpy dev)
diff --git a/pandas/core/arrays/sparse/scipy_sparse.py b/pandas/core/arrays/sparse/scipy_sparse.py index 7ebda1f17ba56..ef53034580112 100644 --- a/pandas/core/arrays/sparse/scipy_sparse.py +++ b/pandas/core/arrays/sparse/scipy_sparse.py @@ -122,7 +122,7 @@ def coo_to_sparse_series(A, dense_index: bool = False): Parameters ---------- - A : scipy.sparse.coo.coo_matrix + A : scipy.sparse.coo_matrix dense_index : bool, default False Returns diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index 1cc8a2df44812..181e01233b8e0 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -1204,7 +1204,7 @@ def test_to_coo(self): dtype="Sparse[int]", ) A, _, _ = ser.sparse.to_coo() - assert isinstance(A, scipy.sparse.coo.coo_matrix) + assert isinstance(A, scipy.sparse.coo_matrix) def test_non_sparse_raises(self): ser = pd.Series([1, 2, 3]) diff --git a/pandas/tests/window/moments/test_moments_rolling.py b/pandas/tests/window/moments/test_moments_rolling.py index b2e53a676b039..66b52da0f5578 100644 --- a/pandas/tests/window/moments/test_moments_rolling.py +++ b/pandas/tests/window/moments/test_moments_rolling.py @@ -558,6 +558,7 @@ def test_rolling_quantile_np_percentile(): tm.assert_almost_equal(df_quantile.values, np.array(np_percentile)) +@pytest.mark.xfail(reason="GH#44343", strict=False) @pytest.mark.parametrize("quantile", [0.0, 0.1, 0.45, 0.5, 1]) @pytest.mark.parametrize( "interpolation", ["linear", "lower", "higher", "nearest", "midpoint"]
Backport PR #44362
https://api.github.com/repos/pandas-dev/pandas/pulls/44370
2021-11-09T19:54:51Z
2021-11-09T21:23:33Z
2021-11-09T21:23:33Z
2021-11-09T21:23:37Z
TST: check compatibility with pyarrow types_mapper parameter
diff --git a/pandas/tests/arrays/masked/test_arrow_compat.py b/pandas/tests/arrays/masked/test_arrow_compat.py index 3f0a1b5d0eaf3..20eb055f14835 100644 --- a/pandas/tests/arrays/masked/test_arrow_compat.py +++ b/pandas/tests/arrays/masked/test_arrow_compat.py @@ -36,6 +36,27 @@ def test_arrow_roundtrip(data): tm.assert_frame_equal(result, df) +def test_dataframe_from_arrow_types_mapper(): + def types_mapper(arrow_type): + if pa.types.is_boolean(arrow_type): + return pd.BooleanDtype() + elif pa.types.is_integer(arrow_type): + return pd.Int64Dtype() + + bools_array = pa.array([True, None, False], type=pa.bool_()) + ints_array = pa.array([1, None, 2], type=pa.int64()) + small_ints_array = pa.array([-1, 0, 7], type=pa.int8()) + record_batch = pa.RecordBatch.from_arrays( + [bools_array, ints_array, small_ints_array], ["bools", "ints", "small_ints"] + ) + result = record_batch.to_pandas(types_mapper=types_mapper) + bools = pd.Series([True, None, False], dtype="boolean") + ints = pd.Series([1, None, 2], dtype="Int64") + small_ints = pd.Series([-1, 0, 7], dtype="Int64") + expected = pd.DataFrame({"bools": bools, "ints": ints, "small_ints": small_ints}) + tm.assert_frame_equal(result, expected) + + def test_arrow_load_from_zero_chunks(data): # GH-41040
- [x] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry Closes #44368
https://api.github.com/repos/pandas-dev/pandas/pulls/44369
2021-11-09T17:56:38Z
2021-12-01T01:26:47Z
2021-12-01T01:26:47Z
2021-12-01T16:54:07Z
CLN: split/fixturize to_datetime tests
diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 1f75bc11005bc..4867ba58838ef 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -46,6 +46,14 @@ from pandas.core.tools.datetimes import start_caching_at +@pytest.fixture(params=[True, False]) +def cache(request): + """ + cache keyword to pass to to_datetime. + """ + return request.param + + class TestTimeConversionFormats: @pytest.mark.parametrize("readonly", [True, False]) def test_to_datetime_readonly(self, readonly): @@ -57,7 +65,6 @@ def test_to_datetime_readonly(self, readonly): expected = to_datetime([]) tm.assert_index_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_format(self, cache): values = ["1/1/2000", "1/2/2000", "1/3/2000"] @@ -82,7 +89,6 @@ def test_to_datetime_format(self, cache): else: tm.assert_index_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_format_YYYYMMDD(self, cache): s = Series([19801222, 19801222] + [19810105] * 5) expected = Series([Timestamp(x) for x in s.apply(str)]) @@ -109,17 +115,18 @@ def test_to_datetime_format_YYYYMMDD(self, cache): result = to_datetime(s, format="%Y%m%d", cache=cache) tm.assert_series_equal(result, expected) + def test_to_datetime_format_YYYYMMDD_coercion(self, cache): # coercion # GH 7930 - s = Series([20121231, 20141231, 99991231]) - result = to_datetime(s, format="%Y%m%d", errors="ignore", cache=cache) + ser = Series([20121231, 20141231, 99991231]) + result = to_datetime(ser, format="%Y%m%d", errors="ignore", cache=cache) expected = Series( [datetime(2012, 12, 31), datetime(2014, 12, 31), datetime(9999, 12, 31)], dtype=object, ) tm.assert_series_equal(result, expected) - result = to_datetime(s, format="%Y%m%d", errors="coerce", cache=cache) + result = to_datetime(ser, format="%Y%m%d", errors="coerce", cache=cache) expected = Series(["20121231", "20141231", "NaT"], dtype="M8[ns]") tm.assert_series_equal(result, expected) @@ -199,7 +206,6 @@ def test_to_datetime_with_NA(self, data, format, expected): result = to_datetime(data, format=format) tm.assert_index_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_format_integer(self, cache): # GH 10178 s = Series([2000, 2001, 2002]) @@ -236,7 +242,6 @@ def test_int_to_datetime_format_YYYYMMDD_typeerror(self, int_date, expected): result = to_datetime(int_date, format="%Y%m%d", errors="ignore") assert result == expected - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_format_microsecond(self, cache): # these are locale dependent @@ -249,7 +254,6 @@ def test_to_datetime_format_microsecond(self, cache): exp = datetime.strptime(val, format) assert result == exp - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_format_time(self, cache): data = [ ["01/10/2010 15:20", "%m/%d/%Y %H:%M", Timestamp("2010-01-10 15:20")], @@ -259,6 +263,7 @@ def test_to_datetime_format_time(self, cache): "%m/%d/%Y %H:%M:%S", Timestamp("2010-01-10 13:56:01"), ] # , + # FIXME: don't leave commented-out # ['01/10/2010 08:14 PM', '%m/%d/%Y %I:%M %p', # Timestamp('2010-01-10 20:14')], # ['01/10/2010 07:40 AM', '%m/%d/%Y %I:%M %p', @@ -270,7 +275,6 @@ def test_to_datetime_format_time(self, cache): assert to_datetime(s, format=format, cache=cache) == dt @td.skip_if_has_locale - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_with_non_exact(self, cache): # GH 10834 # 8904 @@ -284,7 +288,6 @@ def test_to_datetime_with_non_exact(self, cache): ) tm.assert_series_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) def test_parse_nanoseconds_with_formula(self, cache): # GH8989 @@ -300,14 +303,15 @@ def test_parse_nanoseconds_with_formula(self, cache): result = to_datetime(v, format="%Y-%m-%d %H:%M:%S.%f", cache=cache) assert result == expected - @pytest.mark.parametrize("cache", [True, False]) - def test_to_datetime_format_weeks(self, cache): - data = [ + @pytest.mark.parametrize( + "value,fmt,expected", + [ ["2009324", "%Y%W%w", Timestamp("2009-08-13")], ["2013020", "%Y%U%w", Timestamp("2013-01-13")], - ] - for s, format, dt in data: - assert to_datetime(s, format=format, cache=cache) == dt + ], + ) + def test_to_datetime_format_weeks(self, value, fmt, expected, cache): + assert to_datetime(value, format=fmt, cache=cache) == expected @pytest.mark.parametrize( "fmt,dates,expected_dates", @@ -601,7 +605,6 @@ def test_to_datetime_today_now_unicode_bytes(self): to_datetime(["now"]) to_datetime(["today"]) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_dt64s(self, cache): in_bound_dts = [np.datetime64("2000-01-01"), np.datetime64("2000-01-02")] @@ -611,7 +614,6 @@ def test_to_datetime_dt64s(self, cache): @pytest.mark.parametrize( "dt", [np.datetime64("1000-01-01"), np.datetime64("5000-01-02")] ) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_dt64s_out_of_bounds(self, cache, dt): msg = f"Out of bounds nanosecond timestamp: {dt}" with pytest.raises(OutOfBoundsDatetime, match=msg): @@ -620,7 +622,6 @@ def test_to_datetime_dt64s_out_of_bounds(self, cache, dt): Timestamp(dt) assert to_datetime(dt, errors="coerce", cache=cache) is NaT - @pytest.mark.parametrize("cache", [True, False]) @pytest.mark.parametrize("unit", ["s", "D"]) def test_to_datetime_array_of_dt64s(self, cache, unit): # https://github.com/pandas-dev/pandas/issues/31491 @@ -659,7 +660,6 @@ def test_to_datetime_array_of_dt64s(self, cache, unit): Index([dt.item() for dt in dts_with_oob]), ) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_tz(self, cache): # xref 8260 @@ -686,7 +686,6 @@ def test_to_datetime_tz(self, cache): with pytest.raises(ValueError, match=msg): to_datetime(arr, cache=cache) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_different_offsets(self, cache): # inspired by asv timeseries.ToDatetimeNONISO8601 benchmark # see GH-26097 for more @@ -697,7 +696,6 @@ def test_to_datetime_different_offsets(self, cache): result = to_datetime(arr, cache=cache) tm.assert_index_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_tz_pytz(self, cache): # see gh-8260 us_eastern = pytz.timezone("US/Eastern") @@ -720,19 +718,16 @@ def test_to_datetime_tz_pytz(self, cache): ) tm.assert_index_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) @pytest.mark.parametrize( - "init_constructor, end_constructor, test_method", + "init_constructor, end_constructor", [ - (Index, DatetimeIndex, tm.assert_index_equal), - (list, DatetimeIndex, tm.assert_index_equal), - (np.array, DatetimeIndex, tm.assert_index_equal), - (Series, Series, tm.assert_series_equal), + (Index, DatetimeIndex), + (list, DatetimeIndex), + (np.array, DatetimeIndex), + (Series, Series), ], ) - def test_to_datetime_utc_true( - self, cache, init_constructor, end_constructor, test_method - ): + def test_to_datetime_utc_true(self, cache, init_constructor, end_constructor): # See gh-11934 & gh-6415 data = ["20100102 121314", "20100102 121315"] expected_data = [ @@ -744,14 +739,13 @@ def test_to_datetime_utc_true( init_constructor(data), format="%Y%m%d %H%M%S", utc=True, cache=cache ) expected = end_constructor(expected_data) - test_method(result, expected) + tm.assert_equal(result, expected) # Test scalar case as well for scalar, expected in zip(data, expected_data): result = to_datetime(scalar, format="%Y%m%d %H%M%S", utc=True, cache=cache) assert result == expected - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_utc_true_with_series_single_value(self, cache): # GH 15760 UTC=True with Series ts = 1.5e18 @@ -759,7 +753,6 @@ def test_to_datetime_utc_true_with_series_single_value(self, cache): expected = Series([Timestamp(ts, tz="utc")]) tm.assert_series_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_utc_true_with_series_tzaware_string(self, cache): ts = "2013-01-01 00:00:00-01:00" expected_ts = "2013-01-01 01:00:00" @@ -768,7 +761,6 @@ def test_to_datetime_utc_true_with_series_tzaware_string(self, cache): expected = Series([Timestamp(expected_ts, tz="utc")] * 3) tm.assert_series_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) @pytest.mark.parametrize( "date, dtype", [ @@ -781,7 +773,6 @@ def test_to_datetime_utc_true_with_series_datetime_ns(self, cache, date, dtype): result = to_datetime(Series([date], dtype=dtype), utc=True, cache=cache) tm.assert_series_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) @td.skip_if_no("psycopg2") def test_to_datetime_tz_psycopg2(self, cache): @@ -822,7 +813,6 @@ def test_to_datetime_tz_psycopg2(self, cache): expected = DatetimeIndex(["2000-01-01 13:00:00"], dtype="datetime64[ns, UTC]") tm.assert_index_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) def test_datetime_bool(self, cache): # GH13176 msg = r"dtype bool cannot be converted to datetime64\[ns\]" @@ -945,18 +935,6 @@ def test_to_datetime_cache(self, utc, format, constructor): tm.assert_index_equal(result, expected) - @pytest.mark.parametrize( - "listlike", - [ - (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): - # GH 29403 - assert tools.should_cache(listlike) is True - def test_to_datetime_from_deque(self): # GH 29403 result = to_datetime(deque([Timestamp("2010-06-02 09:30:00")] * 51)) @@ -1198,7 +1176,6 @@ def test_to_datetime_fixed_offset(self): class TestToDatetimeUnit: - @pytest.mark.parametrize("cache", [True, False]) def test_unit(self, cache): # GH 11758 # test proper behavior with errors @@ -1247,17 +1224,19 @@ def test_unit(self, cache): with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime(values, errors="raise", unit="s", cache=cache) + def test_to_datetime_invalid_str_not_out_of_bounds_valuerror(self, cache): # if we have a string, then we raise a ValueError # and NOT an OutOfBoundsDatetime - for val in ["foo", Timestamp("20130101")]: - try: - to_datetime(val, errors="raise", unit="s", cache=cache) - except OutOfBoundsDatetime as err: - raise AssertionError("incorrect exception raised") from err - except ValueError: - pass - - @pytest.mark.parametrize("cache", [True, False]) + + try: + to_datetime("foo", errors="raise", unit="s", cache=cache) + except OutOfBoundsDatetime as err: + raise AssertionError("incorrect exception raised") from err + except ValueError: + pass + else: + assert False, "Failed to raise ValueError" + def test_unit_consistency(self, cache): # consistency of conversions @@ -1274,7 +1253,6 @@ def test_unit_consistency(self, cache): assert result == expected assert isinstance(result, Timestamp) - @pytest.mark.parametrize("cache", [True, False]) def test_unit_with_numeric(self, cache): # GH 13180 @@ -1303,7 +1281,6 @@ def test_unit_with_numeric(self, cache): result = to_datetime(arr, errors="coerce", cache=cache) tm.assert_index_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) def test_unit_mixed(self, cache): # mixed integers/datetimes @@ -1324,7 +1301,6 @@ def test_unit_mixed(self, cache): with pytest.raises(ValueError, match=msg): to_datetime(arr, errors="raise", cache=cache) - @pytest.mark.parametrize("cache", [True, False]) def test_unit_rounding(self, cache): # GH 14156 & GH 20445: argument will incur floating point errors # but no premature rounding @@ -1332,17 +1308,105 @@ def test_unit_rounding(self, cache): expected = Timestamp("2015-06-19 19:55:31.877000192") assert result == expected - @pytest.mark.parametrize("cache", [True, False]) def test_unit_ignore_keeps_name(self, cache): # GH 21697 expected = Index([15e9] * 2, name="name") result = to_datetime(expected, errors="ignore", unit="s", cache=cache) tm.assert_index_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) - def test_dataframe(self, cache): + def test_to_datetime_errors_ignore_utc_true(self): + # GH#23758 + result = to_datetime([1], unit="s", utc=True, errors="ignore") + expected = DatetimeIndex(["1970-01-01 00:00:01"], tz="UTC") + tm.assert_index_equal(result, expected) + + # TODO: this is moved from tests.series.test_timeseries, may be redundant + def test_to_datetime_unit(self): + + epoch = 1370745748 + s1 = Series([epoch + t for t in range(20)]) + s2 = Series([epoch + t for t in range(20)]).astype(float) + + for ser in [s1, s2]: + result = to_datetime(ser, unit="s") + expected = Series( + [ + Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) + for t in range(20) + ] + ) + tm.assert_series_equal(result, expected) + + s1 = Series([epoch + t for t in range(20)] + [iNaT]) + s2 = Series([epoch + t for t in range(20)] + [iNaT]).astype(float) + s3 = Series([epoch + t for t in range(20)] + [np.nan]) + + for ser in [s1, s2, s3]: + result = to_datetime(ser, unit="s") + expected = Series( + [ + Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) + for t in range(20) + ] + + [NaT] + ) + tm.assert_series_equal(result, expected) + + def test_to_datetime_unit_fractional_seconds(self): + + # GH13834 + epoch = 1370745748 + s = Series([epoch + t for t in np.arange(0, 2, 0.25)] + [iNaT]).astype(float) + result = to_datetime(s, unit="s") + expected = Series( + [ + Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) + for t in np.arange(0, 2, 0.25) + ] + + [NaT] + ) + # GH20455 argument will incur floating point errors but no premature rounding + result = result.round("ms") + tm.assert_series_equal(result, expected) + + def test_to_datetime_unit_na_values(self): + result = to_datetime([1, 2, "NaT", NaT, np.nan], unit="D") + expected = DatetimeIndex( + [Timestamp("1970-01-02"), Timestamp("1970-01-03")] + ["NaT"] * 3 + ) + tm.assert_index_equal(result, expected) + + def test_to_datetime_unit_invalid(self): + msg = "non convertible value foo with the unit 'D'" + with pytest.raises(ValueError, match=msg): + to_datetime([1, 2, "foo"], unit="D") + msg = "cannot convert input 111111111 with the unit 'D'" + with pytest.raises(OutOfBoundsDatetime, match=msg): + to_datetime([1, 2, 111111111], unit="D") + + def test_to_timestamp_unit_coerce(self): + # coerce we can process + expected = DatetimeIndex( + [Timestamp("1970-01-02"), Timestamp("1970-01-03")] + ["NaT"] * 1 + ) + result = to_datetime([1, 2, "foo"], unit="D", errors="coerce") + tm.assert_index_equal(result, expected) - df = DataFrame( + result = to_datetime([1, 2, 111111111], unit="D", errors="coerce") + tm.assert_index_equal(result, expected) + + +class TestToDatetimeDataFrame: + @pytest.fixture(params=[True, False]) + def cache(self, request): + """ + cache keyword to pass to to_datetime. + """ + return request.param + + @pytest.fixture + def df(self): + return DataFrame( { "year": [2015, 2016], "month": [2, 3], @@ -1356,6 +1420,8 @@ def test_dataframe(self, cache): } ) + def test_dataframe(self, df, cache): + result = to_datetime( {"year": df["year"], "month": df["month"], "day": df["day"]}, cache=cache ) @@ -1377,6 +1443,7 @@ def test_dataframe(self, cache): ) tm.assert_series_equal(result, expected2) + def test_dataframe_field_aliases_column_subset(self, df, cache): # unit mappings units = [ { @@ -1404,6 +1471,7 @@ def test_dataframe(self, cache): ) tm.assert_series_equal(result, expected) + def test_dataframe_field_aliases(self, df, cache): d = { "year": "year", "month": "month", @@ -1425,10 +1493,18 @@ def test_dataframe(self, cache): ) tm.assert_series_equal(result, expected) + def test_dataframe_str_dtype(self, df, cache): # coerce back to int result = to_datetime(df.astype(str), cache=cache) + expected = Series( + [ + Timestamp("20150204 06:58:10.001002003"), + Timestamp("20160305 07:59:11.001002003"), + ] + ) tm.assert_series_equal(result, expected) + def test_dataframe_coerce(self, cache): # passing coerce df2 = DataFrame({"year": [2015, 2016], "month": [2, 20], "day": [4, 5]}) @@ -1438,10 +1514,12 @@ def test_dataframe(self, cache): ) with pytest.raises(ValueError, match=msg): to_datetime(df2, cache=cache) + result = to_datetime(df2, errors="coerce", cache=cache) expected = Series([Timestamp("20150204 00:00:00"), NaT]) tm.assert_series_equal(result, expected) + def test_dataframe_extra_keys_raisesm(self, df, cache): # extra columns msg = r"extra keys have been passed to the datetime assemblage: \[foo\]" with pytest.raises(ValueError, match=msg): @@ -1449,6 +1527,7 @@ def test_dataframe(self, cache): df2["foo"] = 1 to_datetime(df2, cache=cache) + def test_dataframe_missing_keys_raises(self, df, cache): # not enough msg = ( r"to assemble mappings requires at least that \[year, month, " @@ -1464,6 +1543,7 @@ def test_dataframe(self, cache): with pytest.raises(ValueError, match=msg): to_datetime(df[c], cache=cache) + def test_dataframe_duplicate_columns_raises(self, cache): # duplicates msg = "cannot assemble with duplicate keys" df2 = DataFrame({"year": [2015, 2016], "month": [2, 20], "day": [4, 5]}) @@ -1478,9 +1558,8 @@ def test_dataframe(self, cache): with pytest.raises(ValueError, match=msg): to_datetime(df2, cache=cache) - @pytest.mark.parametrize("cache", [True, False]) def test_dataframe_dtypes(self, cache): - # #13451 + # GH#13451 df = DataFrame({"year": [2015, 2016], "month": [2, 3], "day": [4, 5]}) # int16 @@ -1506,7 +1585,7 @@ def test_dataframe_dtypes(self, cache): to_datetime(df, cache=cache) def test_dataframe_utc_true(self): - # GH 23760 + # GH#23760 df = DataFrame({"year": [2015, 2016], "month": [2, 3], "day": [4, 5]}) result = to_datetime(df, utc=True) expected = Series( @@ -1514,94 +1593,6 @@ def test_dataframe_utc_true(self): ).dt.tz_localize("UTC") tm.assert_series_equal(result, expected) - def test_to_datetime_errors_ignore_utc_true(self): - # GH 23758 - result = to_datetime([1], unit="s", utc=True, errors="ignore") - expected = DatetimeIndex(["1970-01-01 00:00:01"], tz="UTC") - tm.assert_index_equal(result, expected) - - # TODO: this is moved from tests.series.test_timeseries, may be redundant - def test_to_datetime_unit(self): - - epoch = 1370745748 - s = Series([epoch + t for t in range(20)]) - result = to_datetime(s, unit="s") - expected = Series( - [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] - ) - tm.assert_series_equal(result, expected) - - s = Series([epoch + t for t in range(20)]).astype(float) - result = to_datetime(s, unit="s") - expected = Series( - [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] - ) - tm.assert_series_equal(result, expected) - - s = Series([epoch + t for t in range(20)] + [iNaT]) - result = to_datetime(s, unit="s") - expected = Series( - [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] - + [NaT] - ) - tm.assert_series_equal(result, expected) - - s = Series([epoch + t for t in range(20)] + [iNaT]).astype(float) - result = to_datetime(s, unit="s") - expected = Series( - [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] - + [NaT] - ) - tm.assert_series_equal(result, expected) - - # GH13834 - s = Series([epoch + t for t in np.arange(0, 2, 0.25)] + [iNaT]).astype(float) - result = to_datetime(s, unit="s") - expected = Series( - [ - Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) - for t in np.arange(0, 2, 0.25) - ] - + [NaT] - ) - # GH20455 argument will incur floating point errors but no premature rounding - result = result.round("ms") - tm.assert_series_equal(result, expected) - - s = pd.concat( - [Series([epoch + t for t in range(20)]).astype(float), Series([np.nan])], - ignore_index=True, - ) - result = to_datetime(s, unit="s") - expected = Series( - [Timestamp("2013-06-09 02:42:28") + timedelta(seconds=t) for t in range(20)] - + [NaT] - ) - tm.assert_series_equal(result, expected) - - result = to_datetime([1, 2, "NaT", NaT, np.nan], unit="D") - expected = DatetimeIndex( - [Timestamp("1970-01-02"), Timestamp("1970-01-03")] + ["NaT"] * 3 - ) - tm.assert_index_equal(result, expected) - - msg = "non convertible value foo with the unit 'D'" - with pytest.raises(ValueError, match=msg): - to_datetime([1, 2, "foo"], unit="D") - msg = "cannot convert input 111111111 with the unit 'D'" - with pytest.raises(OutOfBoundsDatetime, match=msg): - to_datetime([1, 2, 111111111], unit="D") - - # coerce we can process - expected = DatetimeIndex( - [Timestamp("1970-01-02"), Timestamp("1970-01-03")] + ["NaT"] * 1 - ) - result = to_datetime([1, 2, "foo"], unit="D", errors="coerce") - tm.assert_index_equal(result, expected) - - result = to_datetime([1, 2, 111111111], unit="D", errors="coerce") - tm.assert_index_equal(result, expected) - class TestToDatetimeMisc: def test_to_datetime_barely_out_of_bounds(self): @@ -1614,7 +1605,6 @@ def test_to_datetime_barely_out_of_bounds(self): with pytest.raises(OutOfBoundsDatetime, match=msg): to_datetime(arr) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_iso8601(self, cache): result = to_datetime(["2012-01-01 00:00:00"], cache=cache) exp = Timestamp("2012-01-01 00:00:00") @@ -1624,19 +1614,17 @@ def test_to_datetime_iso8601(self, cache): exp = Timestamp("2012-10-01") assert result[0] == exp - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_default(self, cache): rs = to_datetime("2001", cache=cache) xp = datetime(2001, 1, 1) assert rs == xp # dayfirst is essentially broken - + # FIXME: don't leave commented-out # to_datetime('01-13-2012', dayfirst=True) # pytest.raises(ValueError, to_datetime('01-13-2012', # dayfirst=True)) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_on_datetime64_series(self, cache): # #2699 s = Series(date_range("1/1/2000", periods=10)) @@ -1644,7 +1632,6 @@ def test_to_datetime_on_datetime64_series(self, cache): result = to_datetime(s, cache=cache) assert result[0] == s[0] - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_with_space_in_series(self, cache): # GH 6428 s = Series(["10/18/2006", "10/18/2008", " "]) @@ -1658,7 +1645,6 @@ def test_to_datetime_with_space_in_series(self, cache): tm.assert_series_equal(result_ignore, s) @td.skip_if_has_locale - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_with_apply(self, cache): # this is only locale tested with US/None locales # GH 5195 @@ -1681,7 +1667,6 @@ def test_to_datetime_with_apply(self, cache): ) tm.assert_series_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_types(self, cache): # empty string @@ -1701,18 +1686,19 @@ def test_to_datetime_types(self, cache): result = to_datetime("2012", cache=cache) assert result == expected + # FIXME: don't leave commented-out # array = ['2012','20120101','20120101 12:01:01'] array = ["20120101", "20120101 12:01:01"] expected = list(to_datetime(array, cache=cache)) result = [Timestamp(date_str) for date_str in array] tm.assert_almost_equal(result, expected) + # FIXME: don't leave commented-out # currently fails ### # result = Timestamp('2012') # expected = to_datetime('2012') # assert result == expected - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_unprocessable_input(self, cache): # GH 4928 # GH 21864 @@ -1724,7 +1710,6 @@ def test_to_datetime_unprocessable_input(self, cache): with pytest.raises(TypeError, match=msg): to_datetime([1, "1"], errors="raise", cache=cache) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_unhashable_input(self, cache): series = Series([["a"]] * 100) result = to_datetime(series, errors="ignore", cache=cache) @@ -1765,7 +1750,6 @@ def test_to_datetime_overflow(self): with pytest.raises(OutOfBoundsTimedelta, match=msg): date_range(start="1/1/1700", freq="B", periods=100000) - @pytest.mark.parametrize("cache", [True, False]) def test_string_na_nat_conversion(self, cache): # GH #999, #858 @@ -1846,7 +1830,6 @@ def test_string_na_nat_conversion(self, cache): "datetime64[ns]", ], ) - @pytest.mark.parametrize("cache", [True, False]) def test_dti_constructor_numpy_timeunits(self, cache, dtype): # GH 9114 base = to_datetime(["2000-01-01T00:00", "2000-01-02T00:00", "NaT"], cache=cache) @@ -1856,7 +1839,6 @@ def test_dti_constructor_numpy_timeunits(self, cache, dtype): tm.assert_index_equal(DatetimeIndex(values), base) tm.assert_index_equal(to_datetime(values, cache=cache), base) - @pytest.mark.parametrize("cache", [True, False]) def test_dayfirst(self, cache): # GH 5917 arr = ["10/02/2014", "11/02/2014", "12/02/2014"] @@ -1980,7 +1962,6 @@ def test_guess_datetime_format_for_array(self): class TestToDatetimeInferFormat: - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_infer_datetime_format_consistent_format(self, cache): s = Series(date_range("20000101", periods=50, freq="H")) @@ -2002,7 +1983,6 @@ def test_to_datetime_infer_datetime_format_consistent_format(self, cache): tm.assert_series_equal(with_format, no_infer) tm.assert_series_equal(no_infer, yes_infer) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_infer_datetime_format_inconsistent_format(self, cache): s = Series( np.array( @@ -2024,7 +2004,6 @@ def test_to_datetime_infer_datetime_format_inconsistent_format(self, cache): to_datetime(s, infer_datetime_format=True, cache=cache), ) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_infer_datetime_format_series_with_nans(self, cache): s = Series( np.array( @@ -2037,7 +2016,6 @@ def test_to_datetime_infer_datetime_format_series_with_nans(self, cache): to_datetime(s, infer_datetime_format=True, cache=cache), ) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_infer_datetime_format_series_start_with_nans(self, cache): s = Series( np.array( @@ -2086,7 +2064,6 @@ def test_infer_datetime_format_zero_tz(self, ts, zero_tz, is_utc): expected = Series([Timestamp(ts, tz=tz)]) tm.assert_series_equal(result, expected) - @pytest.mark.parametrize("cache", [True, False]) def test_to_datetime_iso8601_noleading_0s(self, cache): # GH 11871 s = Series(["2014-1-1", "2014-2-2", "2015-3-3"]) @@ -2104,7 +2081,6 @@ def test_to_datetime_iso8601_noleading_0s(self, cache): class TestDaysInMonth: # tests for issue #10154 - @pytest.mark.parametrize("cache", [True, False]) def test_day_not_in_month_coerce(self, cache): assert isna(to_datetime("2015-02-29", errors="coerce", cache=cache)) assert isna( @@ -2117,7 +2093,6 @@ def test_day_not_in_month_coerce(self, cache): to_datetime("2015-04-31", format="%Y-%m-%d", errors="coerce", cache=cache) ) - @pytest.mark.parametrize("cache", [True, False]) def test_day_not_in_month_raise(self, cache): msg = "day is out of range for month" with pytest.raises(ValueError, match=msg): @@ -2135,7 +2110,6 @@ def test_day_not_in_month_raise(self, cache): with pytest.raises(ValueError, match=msg): to_datetime("2015-04-31", errors="raise", format="%Y-%m-%d", cache=cache) - @pytest.mark.parametrize("cache", [True, False]) def test_day_not_in_month_ignore(self, cache): assert to_datetime("2015-02-29", errors="ignore", cache=cache) == "2015-02-29" assert ( @@ -2205,7 +2179,6 @@ class TestDatetimeParsingWrappers: }.items() ), ) - @pytest.mark.parametrize("cache", [True, False]) def test_parsers(self, date_str, expected, cache): # dateutil >= 2.5.0 defaults to yearfirst=True @@ -2237,7 +2210,6 @@ def test_parsers(self, date_str, expected, cache): result7 = date_range(date_str, freq="S", periods=1, yearfirst=yearfirst) assert result7 == expected - @pytest.mark.parametrize("cache", [True, False]) def test_na_values_with_cache( self, cache, unique_nulls_fixture, unique_nulls_fixture2 ): @@ -2257,7 +2229,6 @@ def test_parsers_nat(self): assert result3 is NaT assert result4 is NaT - @pytest.mark.parametrize("cache", [True, False]) def test_parsers_dayfirst_yearfirst(self, cache): # OK # 2.5.1 10-11-12 [dayfirst=0, yearfirst=0] -> 2012-10-11 00:00:00 @@ -2345,7 +2316,6 @@ def test_parsers_dayfirst_yearfirst(self, cache): assert result3 == expected assert result4 == expected - @pytest.mark.parametrize("cache", [True, False]) def test_parsers_timestring(self, cache): # must be the same as dateutil result cases = { @@ -2368,7 +2338,6 @@ def test_parsers_timestring(self, cache): assert result4 == exp_now assert result5 == exp_now - @pytest.mark.parametrize("cache", [True, False]) @pytest.mark.parametrize( "dt_string, tz, dt_string_repr", [ @@ -2564,29 +2533,44 @@ def test_arg_tz_ns_unit(self, offset, utc, exp): tm.assert_index_equal(result, expected) -@pytest.mark.parametrize( - "listlike,do_caching", - [([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], False), ([1, 1, 1, 1, 4, 5, 6, 7, 8, 9], True)], -) -def test_should_cache(listlike, do_caching): - assert ( - tools.should_cache(listlike, check_count=len(listlike), unique_share=0.7) - == do_caching +class TestShouldCache: + @pytest.mark.parametrize( + "listlike,do_caching", + [ + ([1, 2, 3, 4, 5, 6, 7, 8, 9, 0], False), + ([1, 1, 1, 1, 4, 5, 6, 7, 8, 9], True), + ], ) + def test_should_cache(self, listlike, do_caching): + assert ( + tools.should_cache(listlike, check_count=len(listlike), unique_share=0.7) + == do_caching + ) + @pytest.mark.parametrize( + "unique_share,check_count, err_message", + [ + (0.5, 11, r"check_count must be in next bounds: \[0; len\(arg\)\]"), + (10, 2, r"unique_share must be in next bounds: \(0; 1\)"), + ], + ) + def test_should_cache_errors(self, unique_share, check_count, err_message): + arg = [5] * 10 -@pytest.mark.parametrize( - "unique_share,check_count, err_message", - [ - (0.5, 11, r"check_count must be in next bounds: \[0; len\(arg\)\]"), - (10, 2, r"unique_share must be in next bounds: \(0; 1\)"), - ], -) -def test_should_cache_errors(unique_share, check_count, err_message): - arg = [5] * 10 + with pytest.raises(AssertionError, match=err_message): + tools.should_cache(arg, unique_share, check_count) - with pytest.raises(AssertionError, match=err_message): - tools.should_cache(arg, unique_share, check_count) + @pytest.mark.parametrize( + "listlike", + [ + (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): + # GH#29403 + assert tools.should_cache(listlike) is True def test_nullable_integer_to_datetime(): @@ -2624,7 +2608,7 @@ def test_na_to_datetime(nulls_fixture, klass): assert result[0] is NaT -def test_empty_string_datetime_coerce__format(): +def test_empty_string_datetime_coerce_format(): # GH13044 td = Series(["03/24/2016", "03/25/2016", ""]) format = "%m/%d/%Y"
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/44367
2021-11-09T17:49:52Z
2021-11-11T17:51:20Z
2021-11-11T17:51:20Z
2021-11-11T17:53:06Z
CI: xfail tests failing on numpy dev
diff --git a/pandas/core/arrays/sparse/scipy_sparse.py b/pandas/core/arrays/sparse/scipy_sparse.py index 3f69321ae98a6..c1b994d4bc4c7 100644 --- a/pandas/core/arrays/sparse/scipy_sparse.py +++ b/pandas/core/arrays/sparse/scipy_sparse.py @@ -181,7 +181,7 @@ def coo_to_sparse_series( Parameters ---------- - A : scipy.sparse.coo.coo_matrix + A : scipy.sparse.coo_matrix dense_index : bool, default False Returns diff --git a/pandas/tests/arrays/sparse/test_array.py b/pandas/tests/arrays/sparse/test_array.py index 96021bfa18fb7..cc48918981338 100644 --- a/pandas/tests/arrays/sparse/test_array.py +++ b/pandas/tests/arrays/sparse/test_array.py @@ -1255,7 +1255,7 @@ def test_to_coo( A, rows, cols = ss.sparse.to_coo( row_levels=(0, 1), column_levels=(2, 3), sort_labels=sort_labels ) - assert isinstance(A, scipy.sparse.coo.coo_matrix) + assert isinstance(A, scipy.sparse.coo_matrix) tm.assert_numpy_array_equal(A.toarray(), expected_A) assert rows == expected_rows assert cols == expected_cols diff --git a/pandas/tests/window/test_rolling.py b/pandas/tests/window/test_rolling.py index 0c0288b49c930..27b06e78d8ce2 100644 --- a/pandas/tests/window/test_rolling.py +++ b/pandas/tests/window/test_rolling.py @@ -1634,6 +1634,7 @@ def test_rolling_quantile_np_percentile(): tm.assert_almost_equal(df_quantile.values, np.array(np_percentile)) +@pytest.mark.xfail(reason="GH#44343", strict=False) @pytest.mark.parametrize("quantile", [0.0, 0.1, 0.45, 0.5, 1]) @pytest.mark.parametrize( "interpolation", ["linear", "lower", "higher", "nearest", "midpoint"]
- [x] ref #44343
https://api.github.com/repos/pandas-dev/pandas/pulls/44362
2021-11-08T23:09:44Z
2021-11-09T01:17:50Z
2021-11-09T01:17:50Z
2021-11-09T19:55:27Z
CLN: Removed _SAFE_NAMES_WARNING in io.sql
diff --git a/pandas/io/sql.py b/pandas/io/sql.py index 867ce52cbde6f..027bb9889202b 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -1818,12 +1818,6 @@ def _get_valid_sqlite_name(name): return '"' + uname.replace('"', '""') + '"' -_SAFE_NAMES_WARNING = ( - "The spaces in these column names will not be changed. " - "In pandas versions < 0.14, spaces were converted to underscores." -) - - class SQLiteTable(SQLTable): """ Patch the SQLTable for fallback support. @@ -1883,12 +1877,6 @@ def _create_table_setup(self): statement while the rest will be CREATE INDEX statements. """ column_names_and_types = self._get_column_names_and_types(self._sql_type_name) - - pat = re.compile(r"\s+") - column_names = [col_name for col_name, _, _ in column_names_and_types] - if any(map(pat.search, column_names)): - warnings.warn(_SAFE_NAMES_WARNING, stacklevel=find_stack_level()) - escape = _get_valid_sqlite_name create_tbl_stmts = [ diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 386f11b3dd794..52c1fc51a4c8d 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -1366,13 +1366,6 @@ def test_read_sql_delegate(self): with pytest.raises(sql.DatabaseError, match=msg): sql.read_sql("iris", self.conn) - def test_safe_names_warning(self): - # GH 6798 - df = DataFrame([[1, 2], [3, 4]], columns=["a", "b "]) # has a space - # warns on create table with spaces in names - with tm.assert_produces_warning(UserWarning): - sql.to_sql(df, "test_frame3_legacy", self.conn, index=False) - def test_get_schema2(self, test_frame1): # without providing a connection object (available for backwards comp) create_sql = sql.get_schema(test_frame1, "test")
- [x] closes #44295 - [x] tests passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them Please let me know if I should improve/change something. Thank you very much!
https://api.github.com/repos/pandas-dev/pandas/pulls/44361
2021-11-08T23:06:17Z
2021-11-14T20:24:19Z
2021-11-14T20:24:19Z
2021-11-14T20:24:29Z
TYP: changed variable hashed to combined_hashed in dtype.py
diff --git a/pandas/core/dtypes/dtypes.py b/pandas/core/dtypes/dtypes.py index 21675ca0cdc7c..e20670893f71c 100644 --- a/pandas/core/dtypes/dtypes.py +++ b/pandas/core/dtypes/dtypes.py @@ -468,12 +468,8 @@ def _hash_categories(self) -> int: # error: Incompatible types in assignment (expression has type # "List[ndarray]", variable has type "ndarray") cat_array = [cat_array] # type: ignore[assignment] - # error: Incompatible types in assignment (expression has type "ndarray", - # variable has type "int") - hashed = combine_hash_arrays( # type: ignore[assignment] - iter(cat_array), num_items=len(cat_array) - ) - return np.bitwise_xor.reduce(hashed) + combined_hashed = combine_hash_arrays(iter(cat_array), num_items=len(cat_array)) + return np.bitwise_xor.reduce(combined_hashed) @classmethod def construct_array_type(cls) -> type_t[Categorical]:
xref #37715
https://api.github.com/repos/pandas-dev/pandas/pulls/44360
2021-11-08T22:51:37Z
2021-11-09T17:16:23Z
2021-11-09T17:16:22Z
2021-11-09T21:31:52Z
Update cython version for asv conf
diff --git a/asv_bench/asv.conf.json b/asv_bench/asv.conf.json index df50f67432fbb..9ad856d5d03ed 100644 --- a/asv_bench/asv.conf.json +++ b/asv_bench/asv.conf.json @@ -39,7 +39,7 @@ // followed by the pip installed packages). "matrix": { "numpy": [], - "Cython": ["0.29.21"], + "Cython": ["0.29.24"], "matplotlib": [], "sqlalchemy": [], "scipy": [], diff --git a/environment.yml b/environment.yml index 7aa7bb0842eca..b4a8b977359cb 100644 --- a/environment.yml +++ b/environment.yml @@ -15,7 +15,7 @@ dependencies: # The compiler packages are meta-packages and install the correct compiler (activation) packages on the respective platforms. - c-compiler - cxx-compiler - - cython>=0.29.21 + - cython>=0.29.24 # code checks - black=21.5b2 diff --git a/requirements-dev.txt b/requirements-dev.txt index 6247b4e5a12b1..5673becbbe1cb 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -5,7 +5,7 @@ numpy>=1.18.5 python-dateutil>=2.8.1 pytz asv -cython>=0.29.21 +cython>=0.29.24 black==21.5b2 cpplint flake8==3.9.2
- [x] closes #44067
https://api.github.com/repos/pandas-dev/pandas/pulls/44359
2021-11-08T22:50:32Z
2021-11-09T21:24:47Z
2021-11-09T21:24:46Z
2021-11-09T21:25:00Z
ENH: Use find_stack_level in pandas.core
diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py index c31368f179ef0..07fa5799fe371 100644 --- a/pandas/core/accessor.py +++ b/pandas/core/accessor.py @@ -9,6 +9,7 @@ import warnings from pandas.util._decorators import doc +from pandas.util._exceptions import find_stack_level class DirNamesMixin: @@ -267,7 +268,7 @@ def decorator(accessor): f"{repr(name)} for type {repr(cls)} is overriding a preexisting " f"attribute with the same name.", UserWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) setattr(cls, name, CachedAccessor(name, accessor)) cls._accessors.add(name) diff --git a/pandas/core/arraylike.py b/pandas/core/arraylike.py index fe09a044566f8..11d32e8a159f3 100644 --- a/pandas/core/arraylike.py +++ b/pandas/core/arraylike.py @@ -11,6 +11,7 @@ import numpy as np from pandas._libs import lib +from pandas.util._exceptions import find_stack_level from pandas.core.construction import extract_array from pandas.core.ops import ( @@ -210,7 +211,7 @@ def _maybe_fallback(ufunc: np.ufunc, method: str, *inputs: Any, **kwargs: Any): "or align manually (eg 'df1, df2 = df1.align(df2)') before passing to " "the ufunc to obtain the future behaviour and silence this warning.", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) # keep the first dataframe of the inputs, other DataFrame/Series is diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index 9c43e3714c332..759c7fb65374d 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -390,7 +390,7 @@ def __init__( "Allowing scalars in the Categorical constructor is deprecated " "and will raise in a future version. Use `[value]` instead", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) values = [values] @@ -945,7 +945,7 @@ def set_categories( "a future version. Removing unused categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1045,7 +1045,7 @@ def rename_categories(self, new_categories, inplace=no_default): "a future version. Removing unused categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1177,7 +1177,7 @@ def add_categories(self, new_categories, inplace=no_default): "a future version. Removing unused categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1252,7 +1252,7 @@ def remove_categories(self, removals, inplace=no_default): "a future version. Removing unused categories will always " "return a new Categorical object.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1327,7 +1327,7 @@ def remove_unused_categories(self, inplace=no_default): "remove_unused_categories is deprecated and " "will be removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1884,7 +1884,7 @@ def to_dense(self) -> np.ndarray: "Categorical.to_dense is deprecated and will be removed in " "a future version. Use np.asarray(cat) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return np.asarray(self) @@ -1901,7 +1901,7 @@ def _codes(self, value: np.ndarray): "Setting the codes on a Categorical is deprecated and will raise in " "a future version. Create a new Categorical object instead", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) # GH#40606 NDArrayBacked.__init__(self, value, self.dtype) @@ -1924,7 +1924,7 @@ def take_nd(self, indexer, allow_fill: bool = False, fill_value=None): warn( "Categorical.take_nd is deprecated, use Categorical.take instead", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.take(indexer, allow_fill=allow_fill, fill_value=fill_value) @@ -2344,7 +2344,7 @@ def is_dtype_equal(self, other) -> bool: "Categorical.is_dtype_equal is deprecated and will be removed " "in a future version", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) try: return self._categories_match_up_to_permutation(other) diff --git a/pandas/core/arrays/datetimes.py b/pandas/core/arrays/datetimes.py index 4fecbe4be9681..a0a7ef3501d7f 100644 --- a/pandas/core/arrays/datetimes.py +++ b/pandas/core/arrays/datetimes.py @@ -1206,7 +1206,7 @@ def to_perioddelta(self, freq) -> TimedeltaArray: "Use `dtindex - dtindex.to_period(freq).to_timestamp()` instead.", FutureWarning, # stacklevel chosen to be correct for when called from DatetimeIndex - stacklevel=3, + stacklevel=find_stack_level(), ) from pandas.core.arrays.timedeltas import TimedeltaArray @@ -1373,7 +1373,7 @@ def weekofyear(self): "weekofyear and return an Index, you may call " "pd.Int64Index(idx.isocalendar().week)", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) week_series = self.isocalendar().week if week_series.hasnans: diff --git a/pandas/core/arrays/sparse/array.py b/pandas/core/arrays/sparse/array.py index 960544a2f89ea..c054710a01f75 100644 --- a/pandas/core/arrays/sparse/array.py +++ b/pandas/core/arrays/sparse/array.py @@ -467,7 +467,7 @@ def __init__( "loses timezone information. Cast to object before " "sparse to retain timezone information.", UserWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) data = np.asarray(data, dtype="datetime64[ns]") if fill_value is NaT: @@ -1089,7 +1089,7 @@ def searchsorted( ) -> npt.NDArray[np.intp] | np.intp: msg = "searchsorted requires high memory usage." - warnings.warn(msg, PerformanceWarning, stacklevel=2) + warnings.warn(msg, PerformanceWarning, stacklevel=find_stack_level()) if not is_scalar(v): v = np.asarray(v) v = np.asarray(v) diff --git a/pandas/core/arrays/sparse/dtype.py b/pandas/core/arrays/sparse/dtype.py index 915e13bc3bbb2..d23e217e605c7 100644 --- a/pandas/core/arrays/sparse/dtype.py +++ b/pandas/core/arrays/sparse/dtype.py @@ -16,6 +16,7 @@ type_t, ) from pandas.errors import PerformanceWarning +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.base import ( ExtensionDtype, @@ -389,7 +390,7 @@ def _get_common_dtype(self, dtypes: list[DtypeObj]) -> DtypeObj | None: f"values: '{fill_values}'. Picking the first and " "converting the rest.", PerformanceWarning, - stacklevel=6, + stacklevel=find_stack_level(), ) np_dtypes = [x.subtype if isinstance(x, SparseDtype) else x for x in dtypes] diff --git a/pandas/core/common.py b/pandas/core/common.py index 2bf925466e176..590296c4b12f5 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -36,6 +36,7 @@ Scalar, T, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.cast import construct_1d_object_array_from_listlike from pandas.core.dtypes.common import ( @@ -175,7 +176,7 @@ def cast_scalar_indexer(val, warn_float: bool = False): "Indexing with a float is deprecated, and will raise an IndexError " "in pandas 2.0. You can manually convert to an integer key instead.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) return int(val) return val diff --git a/pandas/core/computation/align.py b/pandas/core/computation/align.py index a4bd0270f9451..f14882227ddd9 100644 --- a/pandas/core/computation/align.py +++ b/pandas/core/computation/align.py @@ -16,6 +16,7 @@ import numpy as np from pandas.errors import PerformanceWarning +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.generic import ( ABCDataFrame, @@ -126,7 +127,9 @@ def _align_core(terms): f"than an order of magnitude on term {repr(terms[i].name)}, " f"by more than {ordm:.4g}; performance may suffer." ) - warnings.warn(w, category=PerformanceWarning, stacklevel=6) + warnings.warn( + w, category=PerformanceWarning, stacklevel=find_stack_level() + ) f = partial(ti.reindex, reindexer, axis=axis, copy=False) diff --git a/pandas/core/computation/eval.py b/pandas/core/computation/eval.py index 26748eadb4c85..d82cc37b90ad4 100644 --- a/pandas/core/computation/eval.py +++ b/pandas/core/computation/eval.py @@ -7,6 +7,7 @@ import warnings from pandas._libs.lib import no_default +from pandas.util._exceptions import find_stack_level from pandas.util._validators import validate_bool_kwarg from pandas.core.computation.engines import ENGINES @@ -308,7 +309,7 @@ def eval( "will be removed in a future version." ), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) exprs: list[str | BinOp] diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index 0081f8cd074b6..31c2ec8f0cbf9 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -25,6 +25,8 @@ is_text, ) +from pandas.util._exceptions import find_stack_level + # compute use_bottleneck_doc = """ @@ -373,7 +375,7 @@ def _deprecate_negative_int_max_colwidth(key): "will not be supported in future version. Instead, use None " "to not limit the column width.", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) cf.register_option( diff --git a/pandas/core/construction.py b/pandas/core/construction.py index c6f131a9daba6..e3b41f2c7b8c2 100644 --- a/pandas/core/construction.py +++ b/pandas/core/construction.py @@ -25,6 +25,7 @@ DtypeObj, ) from pandas.errors import IntCastingNaNError +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.base import ( ExtensionDtype, @@ -538,7 +539,7 @@ def sanitize_array( "if they cannot be cast losslessly (matching Series behavior). " "To retain the old behavior, use DataFrame(data).astype(dtype)", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) # GH#40110 until the deprecation is enforced, we _dont_ # ignore the dtype for DataFrame, and _do_ cast even though @@ -777,7 +778,7 @@ def _try_cast( "passed to 'DataFrame', either all columns will be cast to that " "dtype, or a TypeError will be raised.", FutureWarning, - stacklevel=7, + stacklevel=find_stack_level(), ) subarr = np.array(arr, dtype=object, copy=copy) return subarr diff --git a/pandas/core/describe.py b/pandas/core/describe.py index 2c4a340e8c8ea..8d88ce280d5c8 100644 --- a/pandas/core/describe.py +++ b/pandas/core/describe.py @@ -23,6 +23,7 @@ from pandas._libs.tslibs import Timestamp from pandas._typing import NDFrameT +from pandas.util._exceptions import find_stack_level from pandas.util._validators import validate_percentile from pandas.core.dtypes.common import ( @@ -377,7 +378,7 @@ def select_describe_func( "version of pandas. Specify `datetime_is_numeric=True` to " "silence this warning and adopt the future behavior now.", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) return describe_timestamp_as_categorical_1d elif is_timedelta64_dtype(data.dtype): diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 432074a8dd699..2c26d6f838315 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -563,7 +563,7 @@ def _maybe_promote(dtype: np.dtype, fill_value=np.nan): "dtype is deprecated. In a future version, this will be cast " "to object dtype. Pass `fill_value=Timestamp(date_obj)` instead.", FutureWarning, - stacklevel=8, + stacklevel=find_stack_level(), ) return dtype, fv elif isinstance(fill_value, str): @@ -1133,7 +1133,7 @@ def astype_nansafe( "Use .view(...) instead.", FutureWarning, # stacklevel chosen to be correct when reached via Series.astype - stacklevel=7, + stacklevel=find_stack_level(), ) if isna(arr).any(): raise ValueError("Cannot convert NaT values to integer") @@ -1155,7 +1155,7 @@ def astype_nansafe( "Use .view(...) instead.", FutureWarning, # stacklevel chosen to be correct when reached via Series.astype - stacklevel=7, + stacklevel=find_stack_level(), ) if isna(arr).any(): raise ValueError("Cannot convert NaT values to integer") @@ -1651,7 +1651,7 @@ def maybe_cast_to_datetime( "`pd.Series(values).dt.tz_localize(None)` " "instead.", FutureWarning, - stacklevel=8, + stacklevel=find_stack_level(), ) # equiv: dta.view(dtype) # Note: NOT equivalent to dta.astype(dtype) @@ -1691,7 +1691,7 @@ def maybe_cast_to_datetime( ".tz_localize('UTC').tz_convert(dtype.tz) " "or pd.Series(data.view('int64'), dtype=dtype)", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) value = dta.tz_localize("UTC").tz_convert(dtype.tz) @@ -1859,7 +1859,7 @@ def construct_2d_arraylike_from_scalar( shape = (length, width) if dtype.kind in ["m", "M"]: - value = maybe_unbox_datetimelike_tz_deprecation(value, dtype, stacklevel=4) + value = maybe_unbox_datetimelike_tz_deprecation(value, dtype) # error: Non-overlapping equality check (left operand type: "dtype[Any]", right # operand type: "Type[object]") elif dtype == object: # type: ignore[comparison-overlap] @@ -1932,9 +1932,7 @@ def construct_1d_arraylike_from_scalar( return subarr -def maybe_unbox_datetimelike_tz_deprecation( - value: Scalar, dtype: DtypeObj, stacklevel: int = 5 -): +def maybe_unbox_datetimelike_tz_deprecation(value: Scalar, dtype: DtypeObj): """ Wrap maybe_unbox_datetimelike with a check for a timezone-aware Timestamp along with a timezone-naive datetime64 dtype, which is deprecated. @@ -1963,7 +1961,7 @@ def maybe_unbox_datetimelike_tz_deprecation( "`pd.Series(values).dt.tz_localize(None)` " "instead.", FutureWarning, - stacklevel=stacklevel, + stacklevel=find_stack_level(), ) new_value = value.tz_localize(None) return maybe_unbox_datetimelike(new_value, dtype) diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 815a0a2040ddb..7ac8e6c47158c 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -22,6 +22,7 @@ ArrayLike, DtypeObj, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.base import _registry as registry from pandas.core.dtypes.dtypes import ( @@ -304,7 +305,7 @@ def is_categorical(arr) -> bool: "is_categorical is deprecated and will be removed in a future version. " "Use is_categorical_dtype instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return isinstance(arr, ABCCategorical) or is_categorical_dtype(arr) @@ -1378,7 +1379,7 @@ def is_extension_type(arr) -> bool: "'is_extension_type' is deprecated and will be removed in a future " "version. Use 'is_extension_array_dtype' instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if is_categorical_dtype(arr): diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 1f26b6d9ae6ae..b01de5dec610d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -83,6 +83,7 @@ doc, rewrite_axis_style_signature, ) +from pandas.util._exceptions import find_stack_level from pandas.util._validators import ( validate_ascending, validate_axis_style_args, @@ -643,7 +644,7 @@ def __init__( "removed in a future version. Pass " "{name: data[name] for name in data.dtype.names} instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) # a masked array @@ -1793,7 +1794,7 @@ def to_dict(self, orient: str = "dict", into=dict): warnings.warn( "DataFrame columns are not unique, some columns will be omitted.", UserWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) # GH16122 into_c = com.standardize_mapping(into) @@ -1814,7 +1815,7 @@ def to_dict(self, orient: str = "dict", into=dict): "will be used in a future version. Use one of the above " "to silence this warning.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if orient.startswith("d"): @@ -2659,7 +2660,7 @@ def to_markdown( "'showindex' is deprecated. Only 'index' will be used " "in a future version. Use 'index' to silence this warning.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) kwargs.setdefault("headers", "keys") @@ -3218,7 +3219,7 @@ def info( warnings.warn( "null_counts is deprecated. Use show_counts instead", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) show_counts = null_counts info = DataFrameInfo( @@ -3591,7 +3592,7 @@ def _getitem_bool_array(self, key): warnings.warn( "Boolean Series key will be reindexed to match DataFrame index.", UserWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) elif len(key) != len(self.index): raise ValueError( @@ -4637,7 +4638,7 @@ def lookup( "You can use DataFrame.melt and DataFrame.loc " "as a substitute." ) - warnings.warn(msg, FutureWarning, stacklevel=2) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) n = len(row_labels) if n != len(col_labels): @@ -7754,7 +7755,7 @@ def groupby( "will be removed in a future version." ), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: squeeze = False @@ -9844,7 +9845,7 @@ def count( "deprecated and will be removed in a future version. Use groupby " "instead. df.count(level=1) should use df.groupby(level=1).count().", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._count_level(level, axis=axis, numeric_only=numeric_only) @@ -9944,7 +9945,7 @@ def _reduce( "will include datetime64 and datetime64tz columns in a " "future version.", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) # Non-copy equivalent to # dt64_cols = self.dtypes.apply(is_datetime64_any_dtype) @@ -10019,7 +10020,7 @@ def _get_data() -> DataFrame: "version this will raise TypeError. Select only valid " "columns before calling the reduction.", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) return out @@ -10052,7 +10053,7 @@ def _get_data() -> DataFrame: "version this will raise TypeError. Select only valid " "columns before calling the reduction.", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) if hasattr(result, "dtype"): diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 93bf70c27f8ff..23608cf0192df 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -3647,7 +3647,7 @@ class max_speed "is_copy is deprecated and will be removed in a future version. " "'take' always returns a copy, so there is no need to specify this.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) nv.validate_take((), kwargs) @@ -3781,7 +3781,7 @@ class animal locomotion "Passing lists as key for xs is deprecated and will be removed in a " "future version. Pass key as a tuple instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if level is not None: @@ -5556,7 +5556,7 @@ def __setattr__(self, name: str, value) -> None: "created via a new attribute name - see " "https://pandas.pydata.org/pandas-docs/" "stable/indexing.html#attribute-access", - stacklevel=2, + stacklevel=find_stack_level(), ) object.__setattr__(self, name, value) @@ -7774,7 +7774,7 @@ def between_time( "`include_start` and `include_end` are deprecated in " "favour of `inclusive`.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) left = True if isinstance(include_start, lib.NoDefault) else include_start right = True if isinstance(include_end, lib.NoDefault) else include_end @@ -9190,7 +9190,7 @@ def where( "try_cast keyword is deprecated and will be removed in a " "future version.", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) return self._where(cond, other, inplace, axis, level, errors=errors) @@ -9222,7 +9222,7 @@ def mask( "try_cast keyword is deprecated and will be removed in a " "future version.", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) # see gh-21891 @@ -9415,7 +9415,7 @@ def slice_shift(self: NDFrameT, periods: int = 1, axis=0) -> NDFrameT: "and will be removed in a future version. " "You can use DataFrame/Series.shift instead." ) - warnings.warn(msg, FutureWarning, stacklevel=2) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) if periods == 0: return self @@ -9467,7 +9467,7 @@ def tshift(self: NDFrameT, periods: int = 1, freq=None, axis: Axis = 0) -> NDFra "Please use shift instead." ), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if freq is None: @@ -10282,7 +10282,7 @@ def _logical_func( "deprecated and will be removed in a future version. Use groupby " "instead. df.any(level=1) should use df.groupby(level=1).any()", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) if bool_only is not None: raise NotImplementedError( @@ -10378,7 +10378,7 @@ def _stat_function_ddof( "deprecated and will be removed in a future version. Use groupby " "instead. df.var(level=1) should use df.groupby(level=1).var().", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) return self._agg_by_level( name, axis=axis, level=level, skipna=skipna, ddof=ddof @@ -10431,7 +10431,7 @@ def _stat_function( "deprecated and will be removed in a future version. Use groupby " "instead. df.median(level=1) should use df.groupby(level=1).median().", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) return self._agg_by_level( name, axis=axis, level=level, skipna=skipna, numeric_only=numeric_only @@ -10498,7 +10498,7 @@ def _min_count_stat_function( "deprecated and will be removed in a future version. Use groupby " "instead. df.sum(level=1) should use df.groupby(level=1).sum().", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) return self._agg_by_level( name, @@ -10582,7 +10582,7 @@ def mad(self, axis=None, skipna=None, level=None): "deprecated and will be removed in a future version. Use groupby " "instead. df.mad(level=1) should use df.groupby(level=1).mad()", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) return self._agg_by_level("mad", axis=axis, level=level, skipna=skipna) @@ -10980,7 +10980,7 @@ def expanding( warnings.warn( "The `center` argument on `expanding` will be removed in the future.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: center = False diff --git a/pandas/core/groupby/generic.py b/pandas/core/groupby/generic.py index 8a330d08bef78..3c45f7263265c 100644 --- a/pandas/core/groupby/generic.py +++ b/pandas/core/groupby/generic.py @@ -37,6 +37,7 @@ Substitution, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( ensure_int64, @@ -1330,7 +1331,7 @@ def __getitem__(self, key) -> DataFrameGroupBy | SeriesGroupBy: "Indexing with multiple keys (implicitly converted to a tuple " "of keys) will be deprecated, use a list instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return super().__getitem__(key) diff --git a/pandas/core/index.py b/pandas/core/index.py index 13a687b1c27e3..00ca6f9048a40 100644 --- a/pandas/core/index.py +++ b/pandas/core/index.py @@ -1,5 +1,7 @@ import warnings +from pandas.util._exceptions import find_stack_level + from pandas.core.indexes.api import ( # noqa:F401 CategoricalIndex, DatetimeIndex, @@ -26,5 +28,5 @@ "pandas.core.index is deprecated and will be removed in a future version. " "The public classes are available in the top-level namespace.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) diff --git a/pandas/core/indexers/utils.py b/pandas/core/indexers/utils.py index b1824413512c5..41920727c50fd 100644 --- a/pandas/core/indexers/utils.py +++ b/pandas/core/indexers/utils.py @@ -399,7 +399,7 @@ def unpack_1tuple(tup): "slice is deprecated and will raise in a future " "version. Pass a tuple instead.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) return tup[0] diff --git a/pandas/core/indexes/accessors.py b/pandas/core/indexes/accessors.py index b8f4b5f9d3423..3aad1140294e5 100644 --- a/pandas/core/indexes/accessors.py +++ b/pandas/core/indexes/accessors.py @@ -8,6 +8,8 @@ import numpy as np +from pandas.util._exceptions import find_stack_level + from pandas.core.dtypes.common import ( is_categorical_dtype, is_datetime64_dtype, @@ -286,7 +288,7 @@ def weekofyear(self): "Series.dt.weekofyear and Series.dt.week have been deprecated. " "Please use Series.dt.isocalendar().week instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) week_series = self.isocalendar().week week_series.name = self.name diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 2514702b036dd..9715bf8f61f3c 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -399,7 +399,7 @@ def __new__( "'tupleize_cols' is deprecated and will raise TypeError in a " "future version. Use the specific Index subclass directly instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) from pandas.core.arrays import PandasArray @@ -632,7 +632,7 @@ def asi8(self): warnings.warn( "Index.asi8 is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return None @@ -746,7 +746,7 @@ def _get_attributes_dict(self) -> dict[str_t, Any]: "The Index._get_attributes_dict method is deprecated, and will be " "removed in a future version", DeprecationWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return {k: getattr(self, k, None) for k in self._attributes} @@ -919,7 +919,7 @@ def ravel(self, order="C"): "Index.ravel returning ndarray is deprecated; in a future version " "this will return a view on self.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if needs_i8_conversion(self.dtype): # Item "ndarray[Any, Any]" of "Union[ExtensionArray, ndarray[Any, Any]]" @@ -1191,7 +1191,7 @@ def copy( "parameter dtype is deprecated and will be removed in a future " "version. Use the astype method instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) new_index = new_index.astype(dtype) return new_index @@ -1371,7 +1371,7 @@ def to_native_types(self, slicer=None, **kwargs) -> np.ndarray: "The 'to_native_types' method is deprecated and will be removed in " "a future version. Use 'astype(str)' instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) values = self if slicer is not None: @@ -2503,7 +2503,7 @@ def is_mixed(self) -> bool: "Index.is_mixed is deprecated and will be removed in a future version. " "Check index.inferred_type directly instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.inferred_type in ["mixed"] @@ -2538,7 +2538,7 @@ def is_all_dates(self) -> bool: "Index.is_all_dates is deprecated, will be removed in a future version. " "check index.inferred_type instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._is_all_dates @@ -2905,7 +2905,7 @@ def __and__(self, other): "in the future this will be a logical operation matching " "Series.__and__. Use index.intersection(other) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.intersection(other) @@ -2916,7 +2916,7 @@ def __or__(self, other): "in the future this will be a logical operation matching " "Series.__or__. Use index.union(other) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.union(other) @@ -2927,7 +2927,7 @@ def __xor__(self, other): "in the future this will be a logical operation matching " "Series.__xor__. Use index.symmetric_difference(other) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.symmetric_difference(other) @@ -3073,7 +3073,7 @@ def union(self, other, sort=None): "object dtype. To retain the old behavior, " "use `index.astype(object).union(other)`", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) dtype = self._find_common_type_compat(other) @@ -3524,7 +3524,7 @@ def get_loc(self, key, method=None, tolerance=None): "and will raise in a future version. Use " "index.get_indexer([item], method=...) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if is_scalar(key) and isna(key) and not self.hasnans: @@ -3958,7 +3958,7 @@ def is_int(v): "and will raise TypeError in a future version. " "Use .loc with labels or .iloc with positions instead.", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) indexer = key else: @@ -4107,7 +4107,7 @@ def reindex( "reindexing with a non-unique Index is deprecated and " "will raise in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) target = self._wrap_reindex_result(target, indexer, preserve_names) @@ -4848,7 +4848,7 @@ def is_type_compatible(self, kind: str_t) -> bool: "Index.is_type_compatible is deprecated and will be removed in a " "future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return kind == self.inferred_type @@ -5485,7 +5485,7 @@ def get_value(self, series: Series, key): "get_value is deprecated and will be removed in a future version. " "Use Series[key] instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) self._check_indexing_error(key) @@ -5553,7 +5553,7 @@ def set_value(self, arr, key, value): "will be removed in a future version." ), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) loc = self._engine.get_loc(key) validate_numeric_casting(arr.dtype, value) @@ -7023,7 +7023,7 @@ def _maybe_cast_data_without_dtype( "In a future version, the Index constructor will not infer numeric " "dtypes when passed object-dtype sequences (matching Series behavior)", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) if result.dtype.kind in ["b", "c"]: return subarr @@ -7081,6 +7081,6 @@ def _maybe_try_sort(result, sort): warnings.warn( f"{err}, sort order is undefined for incomparable objects.", RuntimeWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) return result diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index e2dd5ecfde5a8..f26a24c38b19f 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -17,6 +17,7 @@ npt, ) from pandas.util._decorators import doc +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_categorical_dtype, @@ -218,7 +219,7 @@ def __new__( "deprecated and will raise in a future version. " "Use CategoricalIndex([], ...) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) data = [] @@ -431,7 +432,7 @@ def reindex( "reindexing with a non-unique Index is deprecated and will " "raise in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if len(self) and indexer is not None: @@ -506,7 +507,7 @@ def take_nd(self, *args, **kwargs): "CategoricalIndex.take_nd is deprecated, use CategoricalIndex.take " "instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.take(*args, **kwargs) diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index a0902a5fb32fe..104bce0369d37 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -36,6 +36,7 @@ cache_readonly, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_categorical_dtype, @@ -403,7 +404,7 @@ def is_type_compatible(self, kind: str) -> bool: f"{type(self).__name__}.is_type_compatible is deprecated and will be " "removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return kind in self._data._infer_matches diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 6078da3bedd8c..e283509206344 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -495,7 +495,7 @@ def to_series(self, keep_tz=lib.no_default, index=None, name=None): "is deprecated and will be removed in a future version. " "You can stop passing 'keep_tz' to silence this warning.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: warnings.warn( @@ -505,7 +505,7 @@ def to_series(self, keep_tz=lib.no_default, index=None, name=None): "can do 'idx.tz_convert(None)' before calling " "'to_series'.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: keep_tz = True @@ -752,7 +752,7 @@ def check_str_or_none(point): "with non-existing keys is deprecated and will raise a " "KeyError in a future Version.", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) indexer = mask.nonzero()[0][::step] if len(indexer) == len(self): @@ -1042,7 +1042,7 @@ def date_range( warnings.warn( "Argument `closed` is deprecated in favor of `inclusive`.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if closed is None: inclusive = "both" diff --git a/pandas/core/indexes/multi.py b/pandas/core/indexes/multi.py index fe97d61be7548..128aa8e282a0d 100644 --- a/pandas/core/indexes/multi.py +++ b/pandas/core/indexes/multi.py @@ -46,6 +46,7 @@ deprecate_nonkeyword_arguments, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.cast import coerce_indexer_dtype from pandas.core.dtypes.common import ( @@ -893,7 +894,7 @@ def set_levels( warnings.warn( "inplace is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1054,7 +1055,7 @@ def set_codes(self, codes, level=None, inplace=None, verify_integrity: bool = Tr warnings.warn( "inplace is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) else: inplace = False @@ -1166,14 +1167,14 @@ def copy( "parameter levels is deprecated and will be removed in a future " "version. Use the set_levels method instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if codes is not None: warnings.warn( "parameter codes is deprecated and will be removed in a future " "version. Use the set_codes method instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if deep: @@ -1202,7 +1203,7 @@ def copy( "parameter dtype is deprecated and will be removed in a future " "version. Use the astype method instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) new_index = new_index.astype(dtype) return new_index @@ -1802,7 +1803,7 @@ def is_lexsorted(self) -> bool: "MultiIndex.is_lexsorted is deprecated as a public function, " "users should use MultiIndex.is_monotonic_increasing instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._is_lexsorted() @@ -1846,7 +1847,7 @@ def lexsort_depth(self) -> int: "MultiIndex.is_lexsorted is deprecated as a public function, " "users should use MultiIndex.is_monotonic_increasing instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._lexsort_depth @@ -2212,7 +2213,7 @@ def drop(self, codes, level=None, errors="raise"): "dropping on a non-lexsorted multi-index " "without a level parameter may impact performance.", PerformanceWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) loc = loc.nonzero()[0] inds.extend(loc) @@ -2877,7 +2878,7 @@ def _maybe_to_slice(loc): warnings.warn( "indexing past lexsort depth may impact performance.", PerformanceWarning, - stacklevel=10, + stacklevel=find_stack_level(), ) loc = np.arange(start, stop, dtype=np.intp) @@ -3335,7 +3336,7 @@ def _update_indexer(idxr: Index, indexer: Index) -> Index: # TODO: how to handle IntervalIndex level? # (no test cases) FutureWarning, - stacklevel=7, + stacklevel=find_stack_level(), ) continue else: diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 4d8c411478993..25b43c556b812 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -21,6 +21,7 @@ cache_readonly, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.cast import astype_nansafe from pandas.core.dtypes.common import ( @@ -421,7 +422,7 @@ def asi8(self) -> npt.NDArray[np.int64]: warnings.warn( "Index.asi8 is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._values.view(self._default_dtype) diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index fd5b5bb7396af..23851eff252b4 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -25,6 +25,7 @@ DtypeObj, ) from pandas.util._decorators import doc +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_datetime64_any_dtype, @@ -346,7 +347,7 @@ def astype(self, dtype, copy: bool = True, how=lib.no_default): "will be removed in a future version. " "Use index.to_timestamp(how=how) instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: how = "start" diff --git a/pandas/core/indexes/range.py b/pandas/core/indexes/range.py index aed7a7a467db3..fdb1ee754a7e6 100644 --- a/pandas/core/indexes/range.py +++ b/pandas/core/indexes/range.py @@ -29,6 +29,7 @@ cache_readonly, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( ensure_platform_int, @@ -256,7 +257,7 @@ def _start(self) -> int: warnings.warn( self._deprecation_message.format("_start", "start"), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.start @@ -279,7 +280,7 @@ def _stop(self) -> int: warnings.warn( self._deprecation_message.format("_stop", "stop"), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.stop @@ -303,7 +304,7 @@ def _step(self) -> int: warnings.warn( self._deprecation_message.format("_step", "step"), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.step @@ -456,7 +457,7 @@ def copy( "parameter dtype is deprecated and will be removed in a future " "version. Use the astype method instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) new_index = new_index.astype(dtype) return new_index diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 669274e034905..e773bf5ffb7f4 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -16,6 +16,7 @@ InvalidIndexError, ) from pandas.util._decorators import doc +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_array_like, @@ -1381,7 +1382,7 @@ def _has_valid_setitem_indexer(self, indexer) -> bool: "a future version.\n" "consider using .loc with a DataFrame indexer for automatic alignment.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) if not isinstance(indexer, tuple): @@ -2298,7 +2299,7 @@ def convert_to_index_sliceable(obj: DataFrame, key): "and will be removed in a future version. Use `frame.loc[string]` " "instead.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) return res except (KeyError, ValueError, NotImplementedError): diff --git a/pandas/core/internals/__init__.py b/pandas/core/internals/__init__.py index 6cbaae3fe12e0..75715bdc90003 100644 --- a/pandas/core/internals/__init__.py +++ b/pandas/core/internals/__init__.py @@ -44,12 +44,14 @@ def __getattr__(name: str): import warnings + from pandas.util._exceptions import find_stack_level + if name == "CategoricalBlock": warnings.warn( "CategoricalBlock is deprecated and will be removed in a future version. " "Use ExtensionBlock instead.", DeprecationWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) from pandas.core.internals.blocks import CategoricalBlock diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 66a40b962e183..55e5b0d0439fa 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -190,7 +190,7 @@ def is_categorical(self) -> bool: "future version. Use isinstance(block.values, Categorical) " "instead. See https://github.com/pandas-dev/pandas/issues/40226", DeprecationWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return isinstance(self.values, Categorical) diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 159c20382dcfb..e6d6b561803d6 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -23,6 +23,7 @@ DtypeObj, Manager, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.cast import ( construct_1d_arraylike_from_scalar, @@ -830,7 +831,7 @@ def to_arrays( "To retain the old behavior, pass as a dictionary " "DataFrame({col: categorical, ..})", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) if columns is None: columns = default_index(len(data)) diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index b4d6e0ace4223..cb0c3e05e955f 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1192,7 +1192,7 @@ def insert(self, loc: int, item: Hashable, value: ArrayLike) -> None: "Consider joining all columns at once using pd.concat(axis=1) " "instead. To get a de-fragmented frame, use `newframe = frame.copy()`", PerformanceWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) def _insert_update_mgr_locs(self, loc) -> None: @@ -1637,7 +1637,7 @@ def __init__( "The `fastpath` keyword is deprecated and will be removed " "in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) self.axes = [axis] diff --git a/pandas/core/ops/__init__.py b/pandas/core/ops/__init__.py index ece5b21fa2f8e..540a557f7c7cc 100644 --- a/pandas/core/ops/__init__.py +++ b/pandas/core/ops/__init__.py @@ -14,6 +14,7 @@ from pandas._libs.ops_dispatch import maybe_dispatch_ufunc_to_dunder_op # noqa:F401 from pandas._typing import Level from pandas.util._decorators import Appender +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_array_like, @@ -300,7 +301,7 @@ def to_series(right): "Do `left, right = left.align(right, axis=1, copy=False)` " "before e.g. `left == right`", FutureWarning, - stacklevel=5, + stacklevel=find_stack_level(), ) left, right = left.align( diff --git a/pandas/core/reshape/melt.py b/pandas/core/reshape/melt.py index 1b217a592987f..7026e470df1c0 100644 --- a/pandas/core/reshape/melt.py +++ b/pandas/core/reshape/melt.py @@ -10,6 +10,7 @@ Appender, deprecate_kwarg, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( is_extension_array_dtype, @@ -58,7 +59,7 @@ def melt( "In the future this will raise an error, please set the 'value_name' " "parameter of DataFrame.melt to a unique name.", FutureWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) if id_vars is not None: diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index a88d1dce693f6..4dd15dd367581 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -35,6 +35,7 @@ Appender, Substitution, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.cast import find_common_type from pandas.core.dtypes.common import ( @@ -676,7 +677,7 @@ def __init__( ) # stacklevel chosen to be correct when this is reached via pd.merge # (and not DataFrame.join) - warnings.warn(msg, FutureWarning, stacklevel=3) + warnings.warn(msg, FutureWarning, stacklevel=find_stack_level()) self._validate_specification() @@ -2297,7 +2298,7 @@ def _items_overlap_with_suffix( "unexpected results. Provide 'suffixes' as a tuple instead. In the " "future a 'TypeError' will be raised.", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) to_rename = left.intersection(right) @@ -2347,7 +2348,7 @@ def renamer(x, suffix): f"Passing 'suffixes' which cause duplicate columns {set(dups)} in the " f"result is deprecated and will raise a MergeError in a future version.", FutureWarning, - stacklevel=4, + stacklevel=find_stack_level(), ) return llabels, rlabels diff --git a/pandas/core/series.py b/pandas/core/series.py index 996af80139458..b3c9167bfbbab 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -54,6 +54,7 @@ deprecate_nonkeyword_arguments, doc, ) +from pandas.util._exceptions import find_stack_level from pandas.util._validators import ( validate_ascending, validate_bool_kwarg, @@ -360,7 +361,7 @@ def __init__( "of 'float64' in a future version. Specify a dtype explicitly " "to silence this warning.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) # uncomment the line below when removing the FutureWarning # dtype = np.dtype(object) @@ -886,7 +887,7 @@ def take(self, indices, axis=0, is_copy=None, **kwargs) -> Series: "is_copy is deprecated and will be removed in a future version. " "'take' always returns a copy, so there is no need to specify this.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) nv.validate_take((), kwargs) @@ -1078,7 +1079,7 @@ def __setitem__(self, key, value) -> None: "Series. Use `series.iloc[an_int] = val` to treat the " "key as positional.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) # this is equivalent to self._values[key] = value self._mgr.setitem_inplace(key, value) @@ -1887,7 +1888,7 @@ def groupby( "will be removed in a future version." ), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) else: squeeze = False @@ -1949,7 +1950,7 @@ def count(self, level=None): "deprecated and will be removed in a future version. Use groupby " "instead. ser.count(level=1) should use ser.groupby(level=1).count().", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if not isinstance(self.index, MultiIndex): raise ValueError("Series.count level is only valid with a MultiIndex") @@ -5135,7 +5136,7 @@ def between(self, left, right, inclusive="both") -> Series: "Boolean inputs to the `inclusive` argument are deprecated in " "favour of `both` or `neither`.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) if inclusive: inclusive = "both" diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 1e27febab2af9..f82e1aa5d188c 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -19,6 +19,7 @@ F, ) from pandas.util._decorators import Appender +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( ensure_object, @@ -238,7 +239,7 @@ def __iter__(self): warnings.warn( "Columnar iteration over characters will be deprecated in future releases.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) i = 0 g = self.get(i) @@ -1214,7 +1215,7 @@ def contains(self, pat, case=True, flags=0, na=None, regex=True): "This pattern has match groups. To actually get the " "groups, use str.extract.", UserWarning, - stacklevel=3, + stacklevel=find_stack_level(), ) result = self._data.array._str_contains(pat, case, flags, na, regex) diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index 669a39fcb3a74..67a6975c21fdd 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -39,6 +39,7 @@ ArrayLike, Timezone, ) +from pandas.util._exceptions import find_stack_level from pandas.core.dtypes.common import ( ensure_object, @@ -1109,7 +1110,7 @@ def to_time(arg, format=None, infer_time_format=False, errors="raise"): "`to_time` has been moved, should be imported from pandas.core.tools.times. " "This alias will be removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) from pandas.core.tools.times import to_time diff --git a/pandas/core/window/ewm.py b/pandas/core/window/ewm.py index c17af442fe2cc..f5f681d9de797 100644 --- a/pandas/core/window/ewm.py +++ b/pandas/core/window/ewm.py @@ -640,7 +640,7 @@ def vol(self, bias: bool = False, *args, **kwargs): "Use std instead." ), FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self.std(bias, *args, **kwargs) diff --git a/pandas/core/window/rolling.py b/pandas/core/window/rolling.py index b04aab3755b91..f7799912937b7 100644 --- a/pandas/core/window/rolling.py +++ b/pandas/core/window/rolling.py @@ -167,7 +167,7 @@ def win_type(self): "win_type will no longer return 'freq' in a future version. " "Check the type of self.window instead.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return "freq" return self._win_type @@ -177,7 +177,7 @@ def is_datetimelike(self) -> bool: warnings.warn( "is_datetimelike is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._win_freq_i8 is not None @@ -185,7 +185,7 @@ def validate(self) -> None: warnings.warn( "validate is deprecated and will be removed in a future version.", FutureWarning, - stacklevel=2, + stacklevel=find_stack_level(), ) return self._validate() @@ -1763,6 +1763,7 @@ def count(self): "Specify min_periods=0 instead." ), FutureWarning, + stacklevel=find_stack_level(), ) self.min_periods = 0 result = super().count()
Part of #44347 - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them This handles most of the stacklevels in core. A few more will take a bit more effort, separating out into a separate PR. After all stacklevels are replaced, will be removing `check_stacklevel=False` from the tests.
https://api.github.com/repos/pandas-dev/pandas/pulls/44358
2021-11-08T22:47:15Z
2021-11-12T03:19:05Z
2021-11-12T03:19:05Z
2021-12-04T15:25:42Z
DOC: Clarify DST rounding behavior in Timestamp/DatetimeIndex
diff --git a/pandas/_libs/tslibs/nattype.pyx b/pandas/_libs/tslibs/nattype.pyx index 0ec0fb9e814c1..0cbae74ecadac 100644 --- a/pandas/_libs/tslibs/nattype.pyx +++ b/pandas/_libs/tslibs/nattype.pyx @@ -792,6 +792,13 @@ timedelta}, default 'raise' ------ ValueError if the freq cannot be converted + Notes + ----- + If the Timestamp has a timezone, rounding will take place relative to the + local ("wall") time and re-localized to the same timezone. When rounding + near daylight savings time, use ``nonexistent`` and ``ambiguous`` to + control the re-localization behavior. + Examples -------- Create a timestamp object: @@ -826,6 +833,17 @@ timedelta}, default 'raise' >>> pd.NaT.round() NaT + + When rounding near a daylight savings time transition, use ``ambiguous`` or + ``nonexistent`` to control how the timestamp should be re-localized. + + >>> ts_tz = pd.Timestamp("2021-10-31 01:30:00").tz_localize("Europe/Amsterdam") + + >>> ts_tz.round("H", ambiguous=False) + Timestamp('2021-10-31 02:00:00+0100', tz='Europe/Amsterdam') + + >>> ts_tz.round("H", ambiguous=True) + Timestamp('2021-10-31 02:00:00+0200', tz='Europe/Amsterdam') """, ) floor = _make_nat_func( @@ -863,6 +881,13 @@ timedelta}, default 'raise' ------ ValueError if the freq cannot be converted. + Notes + ----- + If the Timestamp has a timezone, flooring will take place relative to the + local ("wall") time and re-localized to the same timezone. When flooring + near daylight savings time, use ``nonexistent`` and ``ambiguous`` to + control the re-localization behavior. + Examples -------- Create a timestamp object: @@ -897,6 +922,17 @@ timedelta}, default 'raise' >>> pd.NaT.floor() NaT + + When rounding near a daylight savings time transition, use ``ambiguous`` or + ``nonexistent`` to control how the timestamp should be re-localized. + + >>> ts_tz = pd.Timestamp("2021-10-31 03:30:00").tz_localize("Europe/Amsterdam") + + >>> ts_tz.floor("2H", ambiguous=False) + Timestamp('2021-10-31 02:00:00+0100', tz='Europe/Amsterdam') + + >>> ts_tz.floor("2H", ambiguous=True) + Timestamp('2021-10-31 02:00:00+0200', tz='Europe/Amsterdam') """, ) ceil = _make_nat_func( @@ -934,6 +970,13 @@ timedelta}, default 'raise' ------ ValueError if the freq cannot be converted. + Notes + ----- + If the Timestamp has a timezone, ceiling will take place relative to the + local ("wall") time and re-localized to the same timezone. When ceiling + near daylight savings time, use ``nonexistent`` and ``ambiguous`` to + control the re-localization behavior. + Examples -------- Create a timestamp object: @@ -968,6 +1011,17 @@ timedelta}, default 'raise' >>> pd.NaT.ceil() NaT + + When rounding near a daylight savings time transition, use ``ambiguous`` or + ``nonexistent`` to control how the timestamp should be re-localized. + + >>> ts_tz = pd.Timestamp("2021-10-31 01:30:00").tz_localize("Europe/Amsterdam") + + >>> ts_tz.ceil("H", ambiguous=False) + Timestamp('2021-10-31 02:00:00+0100', tz='Europe/Amsterdam') + + >>> ts_tz.ceil("H", ambiguous=True) + Timestamp('2021-10-31 02:00:00+0200', tz='Europe/Amsterdam') """, ) diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index bf3b3ed0264a0..9ea347594229f 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -1462,6 +1462,13 @@ timedelta}, default 'raise' ------ ValueError if the freq cannot be converted + Notes + ----- + If the Timestamp has a timezone, rounding will take place relative to the + local ("wall") time and re-localized to the same timezone. When rounding + near daylight savings time, use ``nonexistent`` and ``ambiguous`` to + control the re-localization behavior. + Examples -------- Create a timestamp object: @@ -1496,6 +1503,17 @@ timedelta}, default 'raise' >>> pd.NaT.round() NaT + + When rounding near a daylight savings time transition, use ``ambiguous`` or + ``nonexistent`` to control how the timestamp should be re-localized. + + >>> ts_tz = pd.Timestamp("2021-10-31 01:30:00").tz_localize("Europe/Amsterdam") + + >>> ts_tz.round("H", ambiguous=False) + Timestamp('2021-10-31 02:00:00+0100', tz='Europe/Amsterdam') + + >>> ts_tz.round("H", ambiguous=True) + Timestamp('2021-10-31 02:00:00+0200', tz='Europe/Amsterdam') """ return self._round( freq, RoundTo.NEAREST_HALF_EVEN, ambiguous, nonexistent @@ -1535,6 +1553,13 @@ timedelta}, default 'raise' ------ ValueError if the freq cannot be converted. + Notes + ----- + If the Timestamp has a timezone, flooring will take place relative to the + local ("wall") time and re-localized to the same timezone. When flooring + near daylight savings time, use ``nonexistent`` and ``ambiguous`` to + control the re-localization behavior. + Examples -------- Create a timestamp object: @@ -1569,6 +1594,17 @@ timedelta}, default 'raise' >>> pd.NaT.floor() NaT + + When rounding near a daylight savings time transition, use ``ambiguous`` or + ``nonexistent`` to control how the timestamp should be re-localized. + + >>> ts_tz = pd.Timestamp("2021-10-31 03:30:00").tz_localize("Europe/Amsterdam") + + >>> ts_tz.floor("2H", ambiguous=False) + Timestamp('2021-10-31 02:00:00+0100', tz='Europe/Amsterdam') + + >>> ts_tz.floor("2H", ambiguous=True) + Timestamp('2021-10-31 02:00:00+0200', tz='Europe/Amsterdam') """ return self._round(freq, RoundTo.MINUS_INFTY, ambiguous, nonexistent) @@ -1606,6 +1642,13 @@ timedelta}, default 'raise' ------ ValueError if the freq cannot be converted. + Notes + ----- + If the Timestamp has a timezone, ceiling will take place relative to the + local ("wall") time and re-localized to the same timezone. When ceiling + near daylight savings time, use ``nonexistent`` and ``ambiguous`` to + control the re-localization behavior. + Examples -------- Create a timestamp object: @@ -1640,6 +1683,17 @@ timedelta}, default 'raise' >>> pd.NaT.ceil() NaT + + When rounding near a daylight savings time transition, use ``ambiguous`` or + ``nonexistent`` to control how the timestamp should be re-localized. + + >>> ts_tz = pd.Timestamp("2021-10-31 01:30:00").tz_localize("Europe/Amsterdam") + + >>> ts_tz.ceil("H", ambiguous=False) + Timestamp('2021-10-31 02:00:00+0100', tz='Europe/Amsterdam') + + >>> ts_tz.ceil("H", ambiguous=True) + Timestamp('2021-10-31 02:00:00+0200', tz='Europe/Amsterdam') """ return self._round(freq, RoundTo.PLUS_INFTY, ambiguous, nonexistent) diff --git a/pandas/core/arrays/datetimelike.py b/pandas/core/arrays/datetimelike.py index a8cc07c8fd964..6f18db6caab7d 100644 --- a/pandas/core/arrays/datetimelike.py +++ b/pandas/core/arrays/datetimelike.py @@ -1636,6 +1636,13 @@ def strftime(self, date_format: str) -> npt.NDArray[np.object_]: ------ ValueError if the `freq` cannot be converted. + Notes + ----- + If the timestamps have a timezone, {op}ing will take place relative to the + local ("wall") time and re-localized to the same timezone. When {op}ing + near daylight savings time, use ``nonexistent`` and ``ambiguous`` to + control the re-localization behavior. + Examples -------- **DatetimeIndex** @@ -1659,6 +1666,19 @@ def strftime(self, date_format: str) -> npt.NDArray[np.object_]: 1 2018-01-01 12:00:00 2 2018-01-01 12:00:00 dtype: datetime64[ns] + + When rounding near a daylight savings time transition, use ``ambiguous`` or + ``nonexistent`` to control how the timestamp should be re-localized. + + >>> rng_tz = pd.DatetimeIndex(["2021-10-31 03:30:00"], tz="Europe/Amsterdam") + + >>> rng_tz.floor("2H", ambiguous=False) + DatetimeIndex(['2021-10-31 02:00:00+01:00'], + dtype='datetime64[ns, Europe/Amsterdam]', freq=None) + + >>> rng_tz.floor("2H", ambiguous=True) + DatetimeIndex(['2021-10-31 02:00:00+02:00'], + dtype='datetime64[ns, Europe/Amsterdam]', freq=None) """ _floor_example = """>>> rng.floor('H') @@ -1673,6 +1693,19 @@ def strftime(self, date_format: str) -> npt.NDArray[np.object_]: 1 2018-01-01 12:00:00 2 2018-01-01 12:00:00 dtype: datetime64[ns] + + When rounding near a daylight savings time transition, use ``ambiguous`` or + ``nonexistent`` to control how the timestamp should be re-localized. + + >>> rng_tz = pd.DatetimeIndex(["2021-10-31 03:30:00"], tz="Europe/Amsterdam") + + >>> rng_tz.floor("2H", ambiguous=False) + DatetimeIndex(['2021-10-31 02:00:00+01:00'], + dtype='datetime64[ns, Europe/Amsterdam]', freq=None) + + >>> rng_tz.floor("2H", ambiguous=True) + DatetimeIndex(['2021-10-31 02:00:00+02:00'], + dtype='datetime64[ns, Europe/Amsterdam]', freq=None) """ _ceil_example = """>>> rng.ceil('H') @@ -1687,6 +1720,19 @@ def strftime(self, date_format: str) -> npt.NDArray[np.object_]: 1 2018-01-01 12:00:00 2 2018-01-01 13:00:00 dtype: datetime64[ns] + + When rounding near a daylight savings time transition, use ``ambiguous`` or + ``nonexistent`` to control how the timestamp should be re-localized. + + >>> rng_tz = pd.DatetimeIndex(["2021-10-31 01:30:00"], tz="Europe/Amsterdam") + + >>> rng_tz.ceil("H", ambiguous=False) + DatetimeIndex(['2021-10-31 02:00:00+01:00'], + dtype='datetime64[ns, Europe/Amsterdam]', freq=None) + + >>> rng_tz.ceil("H", ambiguous=True) + DatetimeIndex(['2021-10-31 02:00:00+02:00'], + dtype='datetime64[ns, Europe/Amsterdam]', freq=None) """
xref https://github.com/pandas-dev/pandas/issues/44287 - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/44357
2021-11-08T22:35:44Z
2021-11-17T13:52:38Z
2021-11-17T13:52:38Z
2021-11-17T17:48:56Z
Fixed regression in Series.duplicated for categorical dtype with bool categories
diff --git a/doc/source/whatsnew/v1.3.5.rst b/doc/source/whatsnew/v1.3.5.rst index 589092c0dd7e3..951b05b65c81b 100644 --- a/doc/source/whatsnew/v1.3.5.rst +++ b/doc/source/whatsnew/v1.3.5.rst @@ -16,6 +16,7 @@ Fixed regressions ~~~~~~~~~~~~~~~~~ - Fixed regression in :meth:`Series.equals` when comparing floats with dtype object to None (:issue:`44190`) - Fixed performance regression in :func:`read_csv` (:issue:`44106`) +- Fixed regression in :meth:`Series.duplicated` and :meth:`Series.drop_duplicates` when Series has :class:`Categorical` dtype with boolean categories (:issue:`44351`) - .. --------------------------------------------------------------------------- diff --git a/pandas/core/algorithms.py b/pandas/core/algorithms.py index c1b587ce3a6b2..8c2c01b6aedc8 100644 --- a/pandas/core/algorithms.py +++ b/pandas/core/algorithms.py @@ -148,7 +148,7 @@ def _ensure_data(values: ArrayLike) -> np.ndarray: # i.e. all-bool Categorical, BooleanArray try: return np.asarray(values).astype("uint8", copy=False) - except TypeError: + except (TypeError, ValueError): # GH#42107 we have pd.NAs present return np.asarray(values) diff --git a/pandas/tests/series/methods/test_drop_duplicates.py b/pandas/tests/series/methods/test_drop_duplicates.py index 7eb51f8037792..f72d85337df8e 100644 --- a/pandas/tests/series/methods/test_drop_duplicates.py +++ b/pandas/tests/series/methods/test_drop_duplicates.py @@ -2,6 +2,7 @@ import pytest from pandas import ( + NA, Categorical, Series, ) @@ -224,6 +225,20 @@ def test_drop_duplicates_categorical_bool(self, ordered): assert return_value is None tm.assert_series_equal(sc, tc[~expected]) + def test_drop_duplicates_categorical_bool_na(self): + # GH#44351 + ser = Series( + Categorical( + [True, False, True, False, NA], categories=[True, False], ordered=True + ) + ) + result = ser.drop_duplicates() + expected = Series( + Categorical([True, False, np.nan], categories=[True, False], ordered=True), + index=[0, 1, 4], + ) + tm.assert_series_equal(result, expected) + def test_drop_duplicates_pos_args_deprecation(): # GH#41485 diff --git a/pandas/tests/series/methods/test_duplicated.py b/pandas/tests/series/methods/test_duplicated.py index 5cc297913e851..c61492168da63 100644 --- a/pandas/tests/series/methods/test_duplicated.py +++ b/pandas/tests/series/methods/test_duplicated.py @@ -1,7 +1,11 @@ import numpy as np import pytest -from pandas import Series +from pandas import ( + NA, + Categorical, + Series, +) import pandas._testing as tm @@ -33,3 +37,15 @@ def test_duplicated_nan_none(keep, expected): result = ser.duplicated(keep=keep) tm.assert_series_equal(result, expected) + + +def test_duplicated_categorical_bool_na(): + # GH#44351 + ser = Series( + Categorical( + [True, False, True, False, NA], categories=[True, False], ordered=True + ) + ) + result = ser.duplicated() + expected = Series([False, False, True, True, False]) + tm.assert_series_equal(result, expected)
- [x] closes #44351 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/44356
2021-11-08T22:10:59Z
2021-11-12T03:09:36Z
2021-11-12T03:09:35Z
2021-11-12T11:44:04Z
CLN: split giant dt accessor tests
diff --git a/pandas/tests/series/accessors/test_dt_accessor.py b/pandas/tests/series/accessors/test_dt_accessor.py index eb7e1d4268605..48a3ebd25c239 100644 --- a/pandas/tests/series/accessors/test_dt_accessor.py +++ b/pandas/tests/series/accessors/test_dt_accessor.py @@ -39,121 +39,136 @@ ) import pandas.core.common as com +ok_for_period = PeriodArray._datetimelike_ops +ok_for_period_methods = ["strftime", "to_timestamp", "asfreq"] +ok_for_dt = DatetimeArray._datetimelike_ops +ok_for_dt_methods = [ + "to_period", + "to_pydatetime", + "tz_localize", + "tz_convert", + "normalize", + "strftime", + "round", + "floor", + "ceil", + "day_name", + "month_name", + "isocalendar", +] +ok_for_td = TimedeltaArray._datetimelike_ops +ok_for_td_methods = [ + "components", + "to_pytimedelta", + "total_seconds", + "round", + "floor", + "ceil", +] + + +def get_dir(ser): + # check limited display api + results = [r for r in ser.dt.__dir__() if not r.startswith("_")] + return sorted(set(results)) -class TestSeriesDatetimeValues: - def test_dt_namespace_accessor(self): +class TestSeriesDatetimeValues: + def _compare(self, ser, name): # GH 7207, 11128 # test .dt namespace accessor - ok_for_period = PeriodArray._datetimelike_ops - ok_for_period_methods = ["strftime", "to_timestamp", "asfreq"] - ok_for_dt = DatetimeArray._datetimelike_ops - ok_for_dt_methods = [ - "to_period", - "to_pydatetime", - "tz_localize", - "tz_convert", - "normalize", - "strftime", - "round", - "floor", - "ceil", - "day_name", - "month_name", - "isocalendar", - ] - ok_for_td = TimedeltaArray._datetimelike_ops - ok_for_td_methods = [ - "components", - "to_pytimedelta", - "total_seconds", - "round", - "floor", - "ceil", - ] - - def get_expected(s, name): - result = getattr(Index(s._values), prop) + def get_expected(ser, prop): + result = getattr(Index(ser._values), prop) if isinstance(result, np.ndarray): if is_integer_dtype(result): result = result.astype("int64") elif not is_list_like(result) or isinstance(result, DataFrame): return result - return Series(result, index=s.index, name=s.name) - - def compare(s, name): - a = getattr(s.dt, prop) - b = get_expected(s, prop) - if not (is_list_like(a) and is_list_like(b)): - assert a == b - elif isinstance(a, DataFrame): - tm.assert_frame_equal(a, b) - else: - tm.assert_series_equal(a, b) + return Series(result, index=ser.index, name=ser.name) + + left = getattr(ser.dt, name) + right = get_expected(ser, name) + if not (is_list_like(left) and is_list_like(right)): + assert left == right + elif isinstance(left, DataFrame): + tm.assert_frame_equal(left, right) + else: + tm.assert_series_equal(left, right) + + @pytest.mark.parametrize("freq", ["D", "s", "ms"]) + def test_dt_namespace_accessor_datetime64(self, freq): + # GH#7207, GH#11128 + # test .dt namespace accessor # datetimeindex - cases = [ - Series(date_range("20130101", periods=5), name="xxx"), - Series(date_range("20130101", periods=5, freq="s"), name="xxx"), - Series(date_range("20130101 00:00:00", periods=5, freq="ms"), name="xxx"), - ] - for s in cases: - for prop in ok_for_dt: - # we test freq below - # we ignore week and weekofyear because they are deprecated - if prop not in ["freq", "week", "weekofyear"]: - compare(s, prop) + dti = date_range("20130101", periods=5, freq=freq) + ser = Series(dti, name="xxx") - for prop in ok_for_dt_methods: - getattr(s.dt, prop) + for prop in ok_for_dt: + # we test freq below + # we ignore week and weekofyear because they are deprecated + if prop not in ["freq", "week", "weekofyear"]: + self._compare(ser, prop) - result = s.dt.to_pydatetime() - assert isinstance(result, np.ndarray) - assert result.dtype == object + for prop in ok_for_dt_methods: + getattr(ser.dt, prop) - result = s.dt.tz_localize("US/Eastern") - exp_values = DatetimeIndex(s.values).tz_localize("US/Eastern") - expected = Series(exp_values, index=s.index, name="xxx") - tm.assert_series_equal(result, expected) + result = ser.dt.to_pydatetime() + assert isinstance(result, np.ndarray) + assert result.dtype == object - tz_result = result.dt.tz - assert str(tz_result) == "US/Eastern" - freq_result = s.dt.freq - assert freq_result == DatetimeIndex(s.values, freq="infer").freq - - # let's localize, then convert - result = s.dt.tz_localize("UTC").dt.tz_convert("US/Eastern") - exp_values = ( - DatetimeIndex(s.values).tz_localize("UTC").tz_convert("US/Eastern") - ) - expected = Series(exp_values, index=s.index, name="xxx") - tm.assert_series_equal(result, expected) + result = ser.dt.tz_localize("US/Eastern") + exp_values = DatetimeIndex(ser.values).tz_localize("US/Eastern") + expected = Series(exp_values, index=ser.index, name="xxx") + tm.assert_series_equal(result, expected) + + tz_result = result.dt.tz + assert str(tz_result) == "US/Eastern" + freq_result = ser.dt.freq + assert freq_result == DatetimeIndex(ser.values, freq="infer").freq + + # let's localize, then convert + result = ser.dt.tz_localize("UTC").dt.tz_convert("US/Eastern") + exp_values = ( + DatetimeIndex(ser.values).tz_localize("UTC").tz_convert("US/Eastern") + ) + expected = Series(exp_values, index=ser.index, name="xxx") + tm.assert_series_equal(result, expected) + + def test_dt_namespace_accessor_datetime64tz(self): + # GH#7207, GH#11128 + # test .dt namespace accessor # datetimeindex with tz - s = Series(date_range("20130101", periods=5, tz="US/Eastern"), name="xxx") + dti = date_range("20130101", periods=5, tz="US/Eastern") + ser = Series(dti, name="xxx") for prop in ok_for_dt: # we test freq below # we ignore week and weekofyear because they are deprecated if prop not in ["freq", "week", "weekofyear"]: - compare(s, prop) + self._compare(ser, prop) for prop in ok_for_dt_methods: - getattr(s.dt, prop) + getattr(ser.dt, prop) - result = s.dt.to_pydatetime() + result = ser.dt.to_pydatetime() assert isinstance(result, np.ndarray) assert result.dtype == object - result = s.dt.tz_convert("CET") - expected = Series(s._values.tz_convert("CET"), index=s.index, name="xxx") + result = ser.dt.tz_convert("CET") + expected = Series(ser._values.tz_convert("CET"), index=ser.index, name="xxx") tm.assert_series_equal(result, expected) tz_result = result.dt.tz assert str(tz_result) == "CET" - freq_result = s.dt.freq - assert freq_result == DatetimeIndex(s.values, freq="infer").freq + freq_result = ser.dt.freq + assert freq_result == DatetimeIndex(ser.values, freq="infer").freq + + def test_dt_namespace_accessor_timedelta(self): + # GH#7207, GH#11128 + # test .dt namespace accessor # timedelta index cases = [ @@ -166,102 +181,115 @@ def compare(s, name): name="xxx", ), ] - for s in cases: + for ser in cases: for prop in ok_for_td: # we test freq below if prop != "freq": - compare(s, prop) + self._compare(ser, prop) for prop in ok_for_td_methods: - getattr(s.dt, prop) + getattr(ser.dt, prop) - result = s.dt.components + result = ser.dt.components assert isinstance(result, DataFrame) - tm.assert_index_equal(result.index, s.index) + tm.assert_index_equal(result.index, ser.index) - result = s.dt.to_pytimedelta() + result = ser.dt.to_pytimedelta() assert isinstance(result, np.ndarray) assert result.dtype == object - result = s.dt.total_seconds() + result = ser.dt.total_seconds() assert isinstance(result, Series) assert result.dtype == "float64" - freq_result = s.dt.freq - assert freq_result == TimedeltaIndex(s.values, freq="infer").freq + freq_result = ser.dt.freq + assert freq_result == TimedeltaIndex(ser.values, freq="infer").freq + + def test_dt_namespace_accessor_period(self): + # GH#7207, GH#11128 + # test .dt namespace accessor + + # periodindex + pi = period_range("20130101", periods=5, freq="D") + ser = Series(pi, name="xxx") + + for prop in ok_for_period: + # we test freq below + if prop != "freq": + self._compare(ser, prop) + + for prop in ok_for_period_methods: + getattr(ser.dt, prop) + + freq_result = ser.dt.freq + assert freq_result == PeriodIndex(ser.values).freq + + def test_dt_namespace_accessor_index_and_values(self): # both index = date_range("20130101", periods=3, freq="D") - s = Series(date_range("20140204", periods=3, freq="s"), index=index, name="xxx") + dti = date_range("20140204", periods=3, freq="s") + ser = Series(dti, index=index, name="xxx") exp = Series( np.array([2014, 2014, 2014], dtype="int64"), index=index, name="xxx" ) - tm.assert_series_equal(s.dt.year, exp) + tm.assert_series_equal(ser.dt.year, exp) exp = Series(np.array([2, 2, 2], dtype="int64"), index=index, name="xxx") - tm.assert_series_equal(s.dt.month, exp) + tm.assert_series_equal(ser.dt.month, exp) exp = Series(np.array([0, 1, 2], dtype="int64"), index=index, name="xxx") - tm.assert_series_equal(s.dt.second, exp) - - exp = Series([s[0]] * 3, index=index, name="xxx") - tm.assert_series_equal(s.dt.normalize(), exp) - - # periodindex - cases = [Series(period_range("20130101", periods=5, freq="D"), name="xxx")] - for s in cases: - for prop in ok_for_period: - # we test freq below - if prop != "freq": - compare(s, prop) - - for prop in ok_for_period_methods: - getattr(s.dt, prop) + tm.assert_series_equal(ser.dt.second, exp) - freq_result = s.dt.freq - assert freq_result == PeriodIndex(s.values).freq + exp = Series([ser[0]] * 3, index=index, name="xxx") + tm.assert_series_equal(ser.dt.normalize(), exp) - # test limited display api - def get_dir(s): - results = [r for r in s.dt.__dir__() if not r.startswith("_")] - return sorted(set(results)) + def test_dt_accessor_limited_display_api(self): + # tznaive + ser = Series(date_range("20130101", periods=5, freq="D"), name="xxx") + results = get_dir(ser) + tm.assert_almost_equal(results, sorted(set(ok_for_dt + ok_for_dt_methods))) - s = Series(date_range("20130101", periods=5, freq="D"), name="xxx") - results = get_dir(s) + # tzaware + ser = Series(date_range("2015-01-01", "2016-01-01", freq="T"), name="xxx") + ser = ser.dt.tz_localize("UTC").dt.tz_convert("America/Chicago") + results = get_dir(ser) tm.assert_almost_equal(results, sorted(set(ok_for_dt + ok_for_dt_methods))) - s = Series( + # Period + ser = Series( period_range("20130101", periods=5, freq="D", name="xxx").astype(object) ) - results = get_dir(s) + results = get_dir(ser) tm.assert_almost_equal( results, sorted(set(ok_for_period + ok_for_period_methods)) ) - # 11295 + def test_dt_accessor_ambiguous_freq_conversions(self): + # GH#11295 # ambiguous time error on the conversions - s = Series(date_range("2015-01-01", "2016-01-01", freq="T"), name="xxx") - s = s.dt.tz_localize("UTC").dt.tz_convert("America/Chicago") - results = get_dir(s) - tm.assert_almost_equal(results, sorted(set(ok_for_dt + ok_for_dt_methods))) + ser = Series(date_range("2015-01-01", "2016-01-01", freq="T"), name="xxx") + ser = ser.dt.tz_localize("UTC").dt.tz_convert("America/Chicago") + exp_values = date_range( "2015-01-01", "2016-01-01", freq="T", tz="UTC" ).tz_convert("America/Chicago") # freq not preserved by tz_localize above exp_values = exp_values._with_freq(None) expected = Series(exp_values, name="xxx") - tm.assert_series_equal(s, expected) + tm.assert_series_equal(ser, expected) + def test_dt_accessor_not_writeable(self): # no setting allowed - s = Series(date_range("20130101", periods=5, freq="D"), name="xxx") + ser = Series(date_range("20130101", periods=5, freq="D"), name="xxx") with pytest.raises(ValueError, match="modifications"): - s.dt.hour = 5 + ser.dt.hour = 5 # trying to set a copy msg = "modifications to a property of a datetimelike.+not supported" with pd.option_context("chained_assignment", "raise"): with pytest.raises(com.SettingWithCopyError, match=msg): - s.dt.hour[0] = 5 + ser.dt.hour[0] = 5 @pytest.mark.parametrize( "method, dates", @@ -273,24 +301,24 @@ def get_dir(s): ) def test_dt_round(self, method, dates): # round - s = Series( + ser = Series( pd.to_datetime( ["2012-01-01 13:00:00", "2012-01-01 12:01:00", "2012-01-01 08:00:00"] ), name="xxx", ) - result = getattr(s.dt, method)("D") + result = getattr(ser.dt, method)("D") expected = Series(pd.to_datetime(dates), name="xxx") tm.assert_series_equal(result, expected) def test_dt_round_tz(self): - s = Series( + ser = Series( pd.to_datetime( ["2012-01-01 13:00:00", "2012-01-01 12:01:00", "2012-01-01 08:00:00"] ), name="xxx", ) - result = s.dt.tz_localize("UTC").dt.tz_convert("US/Eastern").dt.round("D") + result = ser.dt.tz_localize("UTC").dt.tz_convert("US/Eastern").dt.round("D") exp_values = pd.to_datetime( ["2012-01-01", "2012-01-01", "2012-01-01"] @@ -339,23 +367,23 @@ def test_dt_round_tz_ambiguous(self, method): ) def test_dt_round_tz_nonexistent(self, method, ts_str, freq): # GH 23324 round near "spring forward" DST - s = Series([pd.Timestamp(ts_str, tz="America/Chicago")]) - result = getattr(s.dt, method)(freq, nonexistent="shift_forward") + ser = Series([pd.Timestamp(ts_str, tz="America/Chicago")]) + result = getattr(ser.dt, method)(freq, nonexistent="shift_forward") expected = Series([pd.Timestamp("2018-03-11 03:00:00", tz="America/Chicago")]) tm.assert_series_equal(result, expected) - result = getattr(s.dt, method)(freq, nonexistent="NaT") + result = getattr(ser.dt, method)(freq, nonexistent="NaT") expected = Series([pd.NaT]).dt.tz_localize(result.dt.tz) tm.assert_series_equal(result, expected) with pytest.raises(pytz.NonExistentTimeError, match="2018-03-11 02:00:00"): - getattr(s.dt, method)(freq, nonexistent="raise") + getattr(ser.dt, method)(freq, nonexistent="raise") def test_dt_namespace_accessor_categorical(self): # GH 19468 dti = DatetimeIndex(["20171111", "20181212"]).repeat(2) - s = Series(pd.Categorical(dti), name="foo") - result = s.dt.year + ser = Series(pd.Categorical(dti), name="foo") + result = ser.dt.year expected = Series([2017, 2017, 2018, 2018], name="foo") tm.assert_series_equal(result, expected) @@ -394,9 +422,9 @@ def test_dt_other_accessors_categorical(self, accessor): def test_dt_accessor_no_new_attributes(self): # https://github.com/pandas-dev/pandas/issues/10673 - s = Series(date_range("20130101", periods=5, freq="D")) + ser = Series(date_range("20130101", periods=5, freq="D")) with pytest.raises(AttributeError, match="You cannot add any new attribute"): - s.dt.xlabel = "a" + ser.dt.xlabel = "a" @pytest.mark.parametrize( "time_locale", [None] if tm.get_locales() is None else [None] + tm.get_locales() @@ -434,7 +462,7 @@ def test_dt_accessor_datetime_name_accessors(self, time_locale): expected_days = calendar.day_name[:] expected_months = calendar.month_name[1:] - s = Series(date_range(freq="D", start=datetime(1998, 1, 1), periods=365)) + ser = Series(date_range(freq="D", start=datetime(1998, 1, 1), periods=365)) english_days = [ "Monday", "Tuesday", @@ -446,13 +474,13 @@ def test_dt_accessor_datetime_name_accessors(self, time_locale): ] for day, name, eng_name in zip(range(4, 11), expected_days, english_days): name = name.capitalize() - assert s.dt.day_name(locale=time_locale)[day] == name - assert s.dt.day_name(locale=None)[day] == eng_name - s = s.append(Series([pd.NaT])) - assert np.isnan(s.dt.day_name(locale=time_locale).iloc[-1]) + assert ser.dt.day_name(locale=time_locale)[day] == name + assert ser.dt.day_name(locale=None)[day] == eng_name + ser = ser.append(Series([pd.NaT])) + assert np.isnan(ser.dt.day_name(locale=time_locale).iloc[-1]) - s = Series(date_range(freq="M", start="2012", end="2013")) - result = s.dt.month_name(locale=time_locale) + ser = Series(date_range(freq="M", start="2012", end="2013")) + result = ser.dt.month_name(locale=time_locale) expected = Series([month.capitalize() for month in expected_months]) # work around https://github.com/pandas-dev/pandas/issues/22342 @@ -461,7 +489,7 @@ def test_dt_accessor_datetime_name_accessors(self, time_locale): tm.assert_series_equal(result, expected) - for s_date, expected in zip(s, expected_months): + for s_date, expected in zip(ser, expected_months): result = s_date.month_name(locale=time_locale) expected = expected.capitalize() @@ -470,20 +498,20 @@ def test_dt_accessor_datetime_name_accessors(self, time_locale): assert result == expected - s = s.append(Series([pd.NaT])) - assert np.isnan(s.dt.month_name(locale=time_locale).iloc[-1]) + ser = ser.append(Series([pd.NaT])) + assert np.isnan(ser.dt.month_name(locale=time_locale).iloc[-1]) def test_strftime(self): # GH 10086 - s = Series(date_range("20130101", periods=5)) - result = s.dt.strftime("%Y/%m/%d") + ser = Series(date_range("20130101", periods=5)) + result = ser.dt.strftime("%Y/%m/%d") expected = Series( ["2013/01/01", "2013/01/02", "2013/01/03", "2013/01/04", "2013/01/05"] ) tm.assert_series_equal(result, expected) - s = Series(date_range("2015-02-03 11:22:33.4567", periods=5)) - result = s.dt.strftime("%Y/%m/%d %H-%M-%S") + ser = Series(date_range("2015-02-03 11:22:33.4567", periods=5)) + result = ser.dt.strftime("%Y/%m/%d %H-%M-%S") expected = Series( [ "2015/02/03 11-22-33", @@ -495,15 +523,15 @@ def test_strftime(self): ) tm.assert_series_equal(result, expected) - s = Series(period_range("20130101", periods=5)) - result = s.dt.strftime("%Y/%m/%d") + ser = Series(period_range("20130101", periods=5)) + result = ser.dt.strftime("%Y/%m/%d") expected = Series( ["2013/01/01", "2013/01/02", "2013/01/03", "2013/01/04", "2013/01/05"] ) tm.assert_series_equal(result, expected) - s = Series(period_range("2015-02-03 11:22:33.4567", periods=5, freq="s")) - result = s.dt.strftime("%Y/%m/%d %H-%M-%S") + ser = Series(period_range("2015-02-03 11:22:33.4567", periods=5, freq="s")) + result = ser.dt.strftime("%Y/%m/%d %H-%M-%S") expected = Series( [ "2015/02/03 11-22-33", @@ -515,9 +543,10 @@ def test_strftime(self): ) tm.assert_series_equal(result, expected) - s = Series(date_range("20130101", periods=5)) - s.iloc[0] = pd.NaT - result = s.dt.strftime("%Y/%m/%d") + def test_strftime_dt64_days(self): + ser = Series(date_range("20130101", periods=5)) + ser.iloc[0] = pd.NaT + result = ser.dt.strftime("%Y/%m/%d") expected = Series( [np.nan, "2013/01/02", "2013/01/03", "2013/01/04", "2013/01/05"] ) @@ -533,6 +562,7 @@ def test_strftime(self): # dtype may be S10 or U10 depending on python version tm.assert_index_equal(result, expected) + def test_strftime_period_days(self): period_index = period_range("20150301", periods=5) result = period_index.strftime("%Y/%m/%d") expected = Index( @@ -541,13 +571,15 @@ def test_strftime(self): ) tm.assert_index_equal(result, expected) - s = Series([datetime(2013, 1, 1, 2, 32, 59), datetime(2013, 1, 2, 14, 32, 1)]) - result = s.dt.strftime("%Y-%m-%d %H:%M:%S") + def test_strftime_dt64_microsecond_resolution(self): + ser = Series([datetime(2013, 1, 1, 2, 32, 59), datetime(2013, 1, 2, 14, 32, 1)]) + result = ser.dt.strftime("%Y-%m-%d %H:%M:%S") expected = Series(["2013-01-01 02:32:59", "2013-01-02 14:32:01"]) tm.assert_series_equal(result, expected) - s = Series(period_range("20130101", periods=4, freq="H")) - result = s.dt.strftime("%Y/%m/%d %H:%M:%S") + def test_strftime_period_hours(self): + ser = Series(period_range("20130101", periods=4, freq="H")) + result = ser.dt.strftime("%Y/%m/%d %H:%M:%S") expected = Series( [ "2013/01/01 00:00:00", @@ -556,9 +588,11 @@ def test_strftime(self): "2013/01/01 03:00:00", ] ) + tm.assert_series_equal(result, expected) - s = Series(period_range("20130101", periods=4, freq="L")) - result = s.dt.strftime("%Y/%m/%d %H:%M:%S.%l") + def test_strftime_period_minutes(self): + ser = Series(period_range("20130101", periods=4, freq="L")) + result = ser.dt.strftime("%Y/%m/%d %H:%M:%S.%l") expected = Series( [ "2013/01/01 00:00:00.000", @@ -578,8 +612,8 @@ def test_strftime(self): ) def test_strftime_nat(self, data): # GH 29578 - s = Series(data) - result = s.dt.strftime("%Y-%m-%d") + ser = Series(data) + result = ser.dt.strftime("%Y-%m-%d") expected = Series(["2019-01-01", np.nan]) tm.assert_series_equal(result, expected) @@ -591,16 +625,16 @@ def test_valid_dt_with_missing_values(self): ) # GH 8689 - s = Series(date_range("20130101", periods=5, freq="D")) - s.iloc[2] = pd.NaT + ser = Series(date_range("20130101", periods=5, freq="D")) + ser.iloc[2] = pd.NaT for attr in ["microsecond", "nanosecond", "second", "minute", "hour", "day"]: - expected = getattr(s.dt, attr).copy() + expected = getattr(ser.dt, attr).copy() expected.iloc[2] = np.nan - result = getattr(s.dt, attr) + result = getattr(ser.dt, attr) tm.assert_series_equal(result, expected) - result = s.dt.date + result = ser.dt.date expected = Series( [ date(2013, 1, 1), @@ -613,7 +647,7 @@ def test_valid_dt_with_missing_values(self): ) tm.assert_series_equal(result, expected) - result = s.dt.time + result = ser.dt.time expected = Series([time(0), time(0), np.nan, time(0), time(0)], dtype="object") tm.assert_series_equal(result, expected) @@ -626,8 +660,8 @@ def test_dt_accessor_api(self): assert Series.dt is CombinedDatetimelikeProperties - s = Series(date_range("2000-01-01", periods=3)) - assert isinstance(s.dt, DatetimeProperties) + ser = Series(date_range("2000-01-01", periods=3)) + assert isinstance(ser.dt, DatetimeProperties) @pytest.mark.parametrize( "ser", [Series(np.arange(5)), Series(list("abcde")), Series(np.random.randn(5))] @@ -639,11 +673,11 @@ def test_dt_accessor_invalid(self, ser): assert not hasattr(ser, "dt") def test_dt_accessor_updates_on_inplace(self): - s = Series(date_range("2018-01-01", periods=10)) - s[2] = None - return_value = s.fillna(pd.Timestamp("2018-01-01"), inplace=True) + ser = Series(date_range("2018-01-01", periods=10)) + ser[2] = None + return_value = ser.fillna(pd.Timestamp("2018-01-01"), inplace=True) assert return_value is None - result = s.dt.date + result = ser.dt.date assert result[0] == result[2] def test_date_tz(self): @@ -652,10 +686,10 @@ def test_date_tz(self): ["2014-04-04 23:56", "2014-07-18 21:24", "2015-11-22 22:14"], tz="US/Eastern", ) - s = Series(rng) + ser = Series(rng) expected = Series([date(2014, 4, 4), date(2014, 7, 18), date(2015, 11, 22)]) - tm.assert_series_equal(s.dt.date, expected) - tm.assert_series_equal(s.apply(lambda x: x.date()), expected) + tm.assert_series_equal(ser.dt.date, expected) + tm.assert_series_equal(ser.apply(lambda x: x.date()), expected) def test_dt_timetz_accessor(self, tz_naive_fixture): # GH21358 @@ -664,11 +698,11 @@ def test_dt_timetz_accessor(self, tz_naive_fixture): dtindex = DatetimeIndex( ["2014-04-04 23:56", "2014-07-18 21:24", "2015-11-22 22:14"], tz=tz ) - s = Series(dtindex) + ser = Series(dtindex) expected = Series( [time(23, 56, tzinfo=tz), time(21, 24, tzinfo=tz), time(22, 14, tzinfo=tz)] ) - result = s.dt.timetz + result = ser.dt.timetz tm.assert_series_equal(result, expected) @pytest.mark.parametrize( @@ -731,9 +765,9 @@ def test_end_time_timevalues(self, input_vals): # 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) + ser = Series(input_vals) + result = ser.dt.end_time + expected = ser.apply(lambda x: x.end_time) tm.assert_series_equal(result, expected) @pytest.mark.parametrize("input_vals", [("2001"), ("NaT")]) @@ -755,7 +789,7 @@ def test_week_and_weekofyear_are_deprecated(): def test_normalize_pre_epoch_dates(): # GH: 36294 - s = pd.to_datetime(Series(["1969-01-01 09:00:00", "2016-01-01 09:00:00"])) - result = s.dt.normalize() + ser = pd.to_datetime(Series(["1969-01-01 09:00:00", "2016-01-01 09:00:00"])) + result = ser.dt.normalize() expected = pd.to_datetime(Series(["1969-01-01", "2016-01-01"])) tm.assert_series_equal(result, expected)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/44355
2021-11-08T21:45:28Z
2021-11-10T01:43:48Z
2021-11-10T01:43:48Z
2021-11-10T02:14:25Z
changed shape argument for ndarray from int to tuple in ./core/strings/object_array.py
diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py index ba2f56c79bdfe..2ce5c0cbea272 100644 --- a/pandas/core/strings/object_array.py +++ b/pandas/core/strings/object_array.py @@ -12,7 +12,7 @@ import pandas._libs.missing as libmissing import pandas._libs.ops as libops from pandas._typing import ( - Dtype, + NpDtype, Scalar, ) @@ -37,7 +37,7 @@ def __len__(self): raise NotImplementedError def _str_map( - self, f, na_value=None, dtype: Dtype | None = None, convert: bool = True + self, f, na_value=None, dtype: NpDtype | None = None, convert: bool = True ): """ Map a callable over valid elements of the array. @@ -62,9 +62,7 @@ def _str_map( na_value = self._str_na_value if not len(self): - # error: Argument 1 to "ndarray" has incompatible type "int"; - # expected "Sequence[int]" - return np.ndarray(0, dtype=dtype) # type: ignore[arg-type] + return np.ndarray(0, dtype=dtype) arr = np.asarray(self, dtype=object) mask = isna(arr)
xref #37715
https://api.github.com/repos/pandas-dev/pandas/pulls/44352
2021-11-08T18:35:46Z
2021-11-16T00:57:31Z
2021-11-16T00:57:31Z
2022-01-05T18:42:34Z
TYP: misc typing in _libs
diff --git a/pandas/_libs/join.pyi b/pandas/_libs/join.pyi index 3a22aa439b7be..a5e91e2ce83eb 100644 --- a/pandas/_libs/join.pyi +++ b/pandas/_libs/join.pyi @@ -55,7 +55,7 @@ def asof_join_backward_on_X_by_Y( left_by_values: np.ndarray, # by_t[:] right_by_values: np.ndarray, # by_t[:] allow_exact_matches: bool = ..., - tolerance=..., + tolerance: np.number | int | float | None = ..., ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ... def asof_join_forward_on_X_by_Y( left_values: np.ndarray, # asof_t[:] @@ -63,7 +63,7 @@ def asof_join_forward_on_X_by_Y( left_by_values: np.ndarray, # by_t[:] right_by_values: np.ndarray, # by_t[:] allow_exact_matches: bool = ..., - tolerance=..., + tolerance: np.number | int | float | None = ..., ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ... def asof_join_nearest_on_X_by_Y( left_values: np.ndarray, # asof_t[:] @@ -71,23 +71,23 @@ def asof_join_nearest_on_X_by_Y( left_by_values: np.ndarray, # by_t[:] right_by_values: np.ndarray, # by_t[:] allow_exact_matches: bool = ..., - tolerance=..., + tolerance: np.number | int | float | None = ..., ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ... def asof_join_backward( left_values: np.ndarray, # asof_t[:] right_values: np.ndarray, # asof_t[:] allow_exact_matches: bool = ..., - tolerance=..., + tolerance: np.number | int | float | None = ..., ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ... def asof_join_forward( left_values: np.ndarray, # asof_t[:] right_values: np.ndarray, # asof_t[:] allow_exact_matches: bool = ..., - tolerance=..., + tolerance: np.number | int | float | None = ..., ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ... def asof_join_nearest( left_values: np.ndarray, # asof_t[:] right_values: np.ndarray, # asof_t[:] allow_exact_matches: bool = ..., - tolerance=..., + tolerance: np.number | int | float | None = ..., ) -> tuple[npt.NDArray[np.intp], npt.NDArray[np.intp]]: ... diff --git a/pandas/_libs/ops.pyi b/pandas/_libs/ops.pyi index 11ae3b852e97a..74a6ad87cd279 100644 --- a/pandas/_libs/ops.pyi +++ b/pandas/_libs/ops.pyi @@ -1,6 +1,7 @@ from typing import ( Any, Callable, + Iterable, Literal, overload, ) @@ -35,15 +36,15 @@ def vec_binop( @overload def maybe_convert_bool( arr: npt.NDArray[np.object_], - true_values=..., - false_values=..., + true_values: Iterable = ..., + false_values: Iterable = ..., convert_to_masked_nullable: Literal[False] = ..., ) -> tuple[np.ndarray, None]: ... @overload def maybe_convert_bool( arr: npt.NDArray[np.object_], - true_values=..., - false_values=..., + true_values: Iterable = ..., + false_values: Iterable = ..., *, convert_to_masked_nullable: Literal[True], ) -> tuple[np.ndarray, np.ndarray]: ... diff --git a/pandas/_libs/tslibs/fields.pyi b/pandas/_libs/tslibs/fields.pyi index cbf91f2bcaf76..415b4329310c0 100644 --- a/pandas/_libs/tslibs/fields.pyi +++ b/pandas/_libs/tslibs/fields.pyi @@ -9,7 +9,7 @@ def month_position_check(fields, weekdays) -> str | None: ... def get_date_name_field( dtindex: npt.NDArray[np.int64], # const int64_t[:] field: str, - locale=..., + locale: str | None = ..., ) -> npt.NDArray[np.object_]: ... def get_start_end_field( dtindex: npt.NDArray[np.int64], # const int64_t[:] @@ -31,7 +31,7 @@ def isleapyear_arr( def build_isocalendar_sarray( dtindex: npt.NDArray[np.int64], # const int64_t[:] ) -> np.ndarray: ... -def get_locale_names(name_type: str, locale: object = ...): ... +def get_locale_names(name_type: str, locale: str | None = ...): ... class RoundTo: @property diff --git a/pandas/_libs/tslibs/nattype.pyi b/pandas/_libs/tslibs/nattype.pyi index 6a5555cfff030..1e29ef8940891 100644 --- a/pandas/_libs/tslibs/nattype.pyi +++ b/pandas/_libs/tslibs/nattype.pyi @@ -1,6 +1,7 @@ from datetime import ( datetime, timedelta, + tzinfo as _tzinfo, ) from typing import Any @@ -17,7 +18,7 @@ class NaTType(datetime): def asm8(self) -> np.datetime64: ... def to_datetime64(self) -> np.datetime64: ... def to_numpy( - self, dtype=..., copy: bool = ... + self, dtype: np.dtype | str | None = ..., copy: bool = ... ) -> np.datetime64 | np.timedelta64: ... @property def is_leap_year(self) -> bool: ... @@ -69,7 +70,20 @@ class NaTType(datetime): def ceil(self) -> NaTType: ... def tz_convert(self) -> NaTType: ... def tz_localize(self) -> NaTType: ... - def replace(self, *args, **kwargs) -> NaTType: ... + # error: Signature of "replace" incompatible with supertype "datetime" + def replace( # type: ignore[override] + self, + year: int | None = ..., + month: int | None = ..., + day: int | None = ..., + hour: int | None = ..., + minute: int | None = ..., + second: int | None = ..., + microsecond: int | None = ..., + nanosecond: int | None = ..., + tzinfo: _tzinfo | None = ..., + fold: int | None = ..., + ) -> NaTType: ... # error: Return type "float" of "year" incompatible with return # type "int" in supertype "date" @property diff --git a/pandas/_libs/tslibs/period.pyi b/pandas/_libs/tslibs/period.pyi index 4f7505fd7e792..2f60df0ad888e 100644 --- a/pandas/_libs/tslibs/period.pyi +++ b/pandas/_libs/tslibs/period.pyi @@ -59,22 +59,22 @@ class Period: def __new__( # type: ignore[misc] cls, value=..., - freq=..., - ordinal=..., - year=..., - month=..., - quarter=..., - day=..., - hour=..., - minute=..., - second=..., + freq: int | str | None = ..., + ordinal: int | None = ..., + year: int | None = ..., + month: int | None = ..., + quarter: int | None = ..., + day: int | None = ..., + hour: int | None = ..., + minute: int | None = ..., + second: int | None = ..., ) -> Period | NaTType: ... @classmethod def _maybe_convert_freq(cls, freq) -> BaseOffset: ... @classmethod def _from_ordinal(cls, ordinal: int, freq) -> Period: ... @classmethod - def now(cls, freq=...) -> Period: ... + def now(cls, freq: BaseOffset = ...) -> Period: ... def strftime(self, fmt: str) -> str: ... def to_timestamp( self, @@ -82,7 +82,7 @@ class Period: how: str = ..., tz: Timezone | None = ..., ) -> Timestamp: ... - def asfreq(self, freq, how=...) -> Period: ... + def asfreq(self, freq: str, how: str = ...) -> Period: ... @property def freqstr(self) -> str: ... @property diff --git a/pandas/_libs/tslibs/timedeltas.pyi b/pandas/_libs/tslibs/timedeltas.pyi index 7c0131cf28c9a..d8369f0cc90f9 100644 --- a/pandas/_libs/tslibs/timedeltas.pyi +++ b/pandas/_libs/tslibs/timedeltas.pyi @@ -14,7 +14,7 @@ from pandas._libs.tslibs import ( ) from pandas._typing import npt -_S = TypeVar("_S") +_S = TypeVar("_S", bound=timedelta) def ints_to_pytimedelta( arr: npt.NDArray[np.int64], # const int64_t[:] @@ -36,7 +36,10 @@ class Timedelta(timedelta): # error: "__new__" must return a class instance (got "Union[Timedelta, NaTType]") def __new__( # type: ignore[misc] - cls: Type[_S], value=..., unit=..., **kwargs + cls: Type[_S], + value=..., + unit: str = ..., + **kwargs: int | float | np.integer | np.floating, ) -> _S | NaTType: ... @property def days(self) -> int: ... @@ -50,9 +53,9 @@ class Timedelta(timedelta): @property def asm8(self) -> np.timedelta64: ... # TODO: round/floor/ceil could return NaT? - def round(self: _S, freq) -> _S: ... - def floor(self: _S, freq) -> _S: ... - def ceil(self: _S, freq) -> _S: ... + def round(self: _S, freq: str) -> _S: ... + def floor(self: _S, freq: str) -> _S: ... + def ceil(self: _S, freq: str) -> _S: ... @property def resolution_string(self) -> str: ... def __add__(self, other: timedelta) -> timedelta: ...
Reduced the list of partially typed functions in _libs a bit.
https://api.github.com/repos/pandas-dev/pandas/pulls/44349
2021-11-08T02:29:57Z
2021-12-14T02:05:20Z
2021-12-14T02:05:20Z
2022-03-09T02:56:34Z
CLN: address TODOs/FIXMEs
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ebf3428020652..1f26b6d9ae6ae 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3732,6 +3732,9 @@ def _setitem_array(self, key, value): self.iloc[indexer] = value else: + # Note: unlike self.iloc[:, indexer] = value, this will + # never try to overwrite values inplace + if isinstance(value, DataFrame): check_key_length(self.columns, key, value) for k1, k2 in zip(key, value.columns): diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 05a9aab4a5554..b4d6e0ace4223 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1045,8 +1045,7 @@ def iset( self._rebuild_blknos_and_blklocs() # Note: we exclude DTA/TDA here - vdtype = getattr(value, "dtype", None) - value_is_extension_type = is_1d_only_ea_dtype(vdtype) + value_is_extension_type = is_1d_only_ea_dtype(value.dtype) # categorical/sparse/datetimetz if value_is_extension_type: diff --git a/pandas/core/series.py b/pandas/core/series.py index 7ee9a0bcdd9e1..996af80139458 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -4538,6 +4538,7 @@ def rename( dtype: int64 """ if axis is not None: + # Make sure we raise if an invalid 'axis' is passed. axis = self._get_axis_number(axis) if callable(index) or is_dict_like(index): diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py index f341014110e18..2e6318955e119 100644 --- a/pandas/tests/frame/methods/test_quantile.py +++ b/pandas/tests/frame/methods/test_quantile.py @@ -617,7 +617,7 @@ def test_quantile_ea_with_na(self, obj, index): expected = type(obj)(expected) tm.assert_equal(result, expected) - # TODO: filtering can be removed after GH#39763 is fixed + # TODO(GH#39763): filtering can be removed after GH#39763 is fixed @pytest.mark.filterwarnings("ignore:Using .astype to convert:FutureWarning") def test_quantile_ea_all_na(self, obj, index, frame_or_series): diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 1bb4b24266de0..f92bbe1c718ab 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -2585,6 +2585,19 @@ def test_error_from_2darray(self, col_a, col_b): DataFrame({"a": col_a, "b": col_b}) +class TestDataFrameConstructorIndexInference: + def test_frame_from_dict_of_series_overlapping_monthly_period_indexes(self): + rng1 = pd.period_range("1/1/1999", "1/1/2012", freq="M") + s1 = Series(np.random.randn(len(rng1)), rng1) + + rng2 = pd.period_range("1/1/1980", "12/1/2001", freq="M") + s2 = Series(np.random.randn(len(rng2)), rng2) + df = DataFrame({"s1": s1, "s2": s2}) + + exp = pd.period_range("1/1/1980", "1/1/2012", freq="M") + tm.assert_index_equal(df.index, exp) + + class TestDataFrameConstructorWithDtypeCoercion: def test_floating_values_integer_dtype(self): # GH#40110 make DataFrame behavior with arraylike floating data and diff --git a/pandas/tests/indexes/base_class/test_setops.py b/pandas/tests/indexes/base_class/test_setops.py index 7a4ba52cdfdd5..87ffe99896199 100644 --- a/pandas/tests/indexes/base_class/test_setops.py +++ b/pandas/tests/indexes/base_class/test_setops.py @@ -90,7 +90,7 @@ def test_union_sort_other_incomparable(self): @pytest.mark.xfail(reason="GH#25151 need to decide on True behavior") def test_union_sort_other_incomparable_true(self): - # TODO decide on True behaviour + # TODO(GH#25151): decide on True behaviour # sort=True idx = Index([1, pd.Timestamp("2000")]) with pytest.raises(TypeError, match=".*"): @@ -98,7 +98,7 @@ def test_union_sort_other_incomparable_true(self): @pytest.mark.xfail(reason="GH#25151 need to decide on True behavior") def test_intersection_equal_sort_true(self): - # TODO decide on True behaviour + # TODO(GH#25151): decide on True behaviour idx = Index(["c", "a", "b"]) sorted_ = Index(["a", "b", "c"]) tm.assert_index_equal(idx.intersection(idx, sort=True), sorted_) diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 80c86e0103436..a99d2f590be97 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -746,7 +746,7 @@ def test_cached_range_bug(self): assert len(rng) == 50 assert rng[0] == datetime(2010, 9, 1, 5) - def test_timezone_comparaison_bug(self): + def test_timezone_comparison_bug(self): # smoke test start = Timestamp("20130220 10:00", tz="US/Eastern") result = date_range(start, periods=2, tz="US/Eastern") diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py index 2a1fa8a015ccc..507449eabfb6e 100644 --- a/pandas/tests/indexes/multi/test_setops.py +++ b/pandas/tests/indexes/multi/test_setops.py @@ -203,7 +203,7 @@ def test_difference_sort_special(): @pytest.mark.xfail(reason="Not implemented.") def test_difference_sort_special_true(): - # TODO decide on True behaviour + # TODO(GH#25151): decide on True behaviour idx = MultiIndex.from_product([[1, 0], ["a", "b"]]) result = idx.difference([], sort=True) expected = MultiIndex.from_product([[0, 1], ["a", "b"]]) @@ -340,7 +340,7 @@ def test_intersect_equal_sort(): @pytest.mark.xfail(reason="Not implemented.") def test_intersect_equal_sort_true(): - # TODO decide on True behaviour + # TODO(GH#25151): decide on True behaviour idx = MultiIndex.from_product([[1, 0], ["a", "b"]]) sorted_ = MultiIndex.from_product([[0, 1], ["a", "b"]]) tm.assert_index_equal(idx.intersection(idx, sort=True), sorted_) @@ -363,7 +363,7 @@ def test_union_sort_other_empty(slice_): @pytest.mark.xfail(reason="Not implemented.") def test_union_sort_other_empty_sort(slice_): - # TODO decide on True behaviour + # TODO(GH#25151): decide on True behaviour # # sort=True idx = MultiIndex.from_product([[1, 0], ["a", "b"]]) other = idx[:0] @@ -388,7 +388,7 @@ def test_union_sort_other_incomparable(): @pytest.mark.xfail(reason="Not implemented.") def test_union_sort_other_incomparable_sort(): - # TODO decide on True behaviour + # TODO(GH#25151): decide on True behaviour # # sort=True idx = MultiIndex.from_product([[1, pd.Timestamp("2000")], ["a", "b"]]) with pytest.raises(TypeError, match="Cannot compare"): diff --git a/pandas/tests/indexes/numeric/test_setops.py b/pandas/tests/indexes/numeric/test_setops.py index 4045cc0b91313..72336d3e33b79 100644 --- a/pandas/tests/indexes/numeric/test_setops.py +++ b/pandas/tests/indexes/numeric/test_setops.py @@ -155,7 +155,7 @@ def test_union_sort_other_special(self, slice_): @pytest.mark.xfail(reason="Not implemented") @pytest.mark.parametrize("slice_", [slice(None), slice(0)]) def test_union_sort_special_true(self, slice_): - # TODO: decide on True behaviour + # TODO(GH#25151): decide on True behaviour # sort=True idx = Index([1, 0, 2]) # default, sort=None diff --git a/pandas/tests/indexes/period/test_setops.py b/pandas/tests/indexes/period/test_setops.py index ce5c46dd55c0d..bac231ef0085d 100644 --- a/pandas/tests/indexes/period/test_setops.py +++ b/pandas/tests/indexes/period/test_setops.py @@ -153,18 +153,6 @@ def test_union_misc(self, sort): expected = index.astype(object).union(index2.astype(object), sort=sort) tm.assert_index_equal(result, expected) - # TODO: belongs elsewhere - def test_union_dataframe_index(self): - rng1 = period_range("1/1/1999", "1/1/2012", freq="M") - s1 = pd.Series(np.random.randn(len(rng1)), rng1) - - rng2 = period_range("1/1/1980", "12/1/2001", freq="M") - s2 = pd.Series(np.random.randn(len(rng2)), rng2) - df = pd.DataFrame({"s1": s1, "s2": s2}) - - exp = period_range("1/1/1980", "1/1/2012", freq="M") - tm.assert_index_equal(df.index, exp) - def test_intersection(self, sort): index = period_range("1/1/2000", "1/20/2000", freq="D") diff --git a/pandas/tests/indexes/ranges/test_range.py b/pandas/tests/indexes/ranges/test_range.py index 277f686a8487a..c45a4c771856c 100644 --- a/pandas/tests/indexes/ranges/test_range.py +++ b/pandas/tests/indexes/ranges/test_range.py @@ -204,10 +204,10 @@ def test_delete_preserves_rangeindex_list_middle(self): loc = [1, 2, 3, 4] result = idx.delete(loc) expected = RangeIndex(0, 6, 5) - tm.assert_index_equal(result, expected, exact="equiv") # TODO: retain! + tm.assert_index_equal(result, expected, exact=True) result = idx.delete(loc[::-1]) - tm.assert_index_equal(result, expected, exact="equiv") # TODO: retain! + tm.assert_index_equal(result, expected, exact=True) def test_delete_all_preserves_rangeindex(self): idx = RangeIndex(0, 6, 1) diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index f1ece3e363bb6..50be69fb93d7c 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -525,20 +525,6 @@ def test_asof_numeric_vs_bool_raises(self): with pytest.raises(TypeError, match=msg): right.asof(left) - # TODO: this tests Series.asof - def test_asof_nanosecond_index_access(self): - s = Timestamp("20130101").value - r = DatetimeIndex([s + 50 + i for i in range(100)]) - ser = Series(np.random.randn(100), index=r) - - first_value = ser.asof(ser.index[0]) - - # this does not yet work, as parsing strings is done via dateutil - # assert first_value == x['2013-01-01 00:00:00.000000050+0000'] - - expected_ts = np_datetime64_compat("2013-01-01 00:00:00.000000050+0000", "ns") - assert first_value == ser[Timestamp(expected_ts)] - @pytest.mark.parametrize("index", ["string"], indirect=True) def test_booleanindex(self, index): bool_index = np.ones(len(index), dtype=bool) diff --git a/pandas/tests/indexes/test_setops.py b/pandas/tests/indexes/test_setops.py index a0e97223435e6..abe1c4fd03fcd 100644 --- a/pandas/tests/indexes/test_setops.py +++ b/pandas/tests/indexes/test_setops.py @@ -773,7 +773,7 @@ def test_difference_incomparable(self, opname): @pytest.mark.xfail(reason="Not implemented") @pytest.mark.parametrize("opname", ["difference", "symmetric_difference"]) def test_difference_incomparable_true(self, opname): - # TODO: decide on True behaviour + # TODO(GH#25151): decide on True behaviour # # sort=True, raises a = Index([3, Timestamp("2000"), 1]) b = Index([2, Timestamp("1999"), 1]) diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index d446d606d726f..7d2f68b00d95f 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -96,10 +96,7 @@ def test_iloc_setitem_fullcol_categorical(self, indexer, key, using_array_manage # check we dont have a view on cat (may be undesired GH#39986) df.iloc[0, 0] = "gamma" - if overwrite: - assert cat[0] != "gamma" - else: - assert cat[0] != "gamma" + assert cat[0] != "gamma" # TODO with mixed dataframe ("split" path), we always overwrite the column frame = DataFrame({0: np.array([0, 1, 2], dtype=object), 1: range(3)}) diff --git a/pandas/tests/indexing/test_indexing.py b/pandas/tests/indexing/test_indexing.py index d6402e027be98..a10288b2091ca 100644 --- a/pandas/tests/indexing/test_indexing.py +++ b/pandas/tests/indexing/test_indexing.py @@ -129,6 +129,21 @@ def test_setitem_ndarray_3d(self, index, frame_or_series, indexer_sli): with pytest.raises(err, match=msg): idxr[nd3] = 0 + def test_getitem_ndarray_0d(self): + # GH#24924 + key = np.array(0) + + # dataframe __getitem__ + df = DataFrame([[1, 2], [3, 4]]) + result = df[key] + expected = Series([1, 3], name=0) + tm.assert_series_equal(result, expected) + + # series __getitem__ + ser = Series([1, 2]) + result = ser[key] + assert result == 1 + def test_inf_upcast(self): # GH 16957 # We should be able to use np.inf as a key diff --git a/pandas/tests/indexing/test_loc.py b/pandas/tests/indexing/test_loc.py index bc08c53784e76..b0aa05371271b 100644 --- a/pandas/tests/indexing/test_loc.py +++ b/pandas/tests/indexing/test_loc.py @@ -6,7 +6,6 @@ time, timedelta, ) -from io import StringIO import re from dateutil.tz import gettz @@ -558,15 +557,27 @@ def test_loc_setitem_consistency_empty(self): def test_loc_setitem_consistency_slice_column_len(self): # .loc[:,column] setting with slice == len of the column # GH10408 - data = """Level_0,,,Respondent,Respondent,Respondent,OtherCat,OtherCat -Level_1,,,Something,StartDate,EndDate,Yes/No,SomethingElse -Region,Site,RespondentID,,,,, -Region_1,Site_1,3987227376,A,5/25/2015 10:59,5/25/2015 11:22,Yes, -Region_1,Site_1,3980680971,A,5/21/2015 9:40,5/21/2015 9:52,Yes,Yes -Region_1,Site_2,3977723249,A,5/20/2015 8:27,5/20/2015 8:41,Yes, -Region_1,Site_2,3977723089,A,5/20/2015 8:33,5/20/2015 9:09,Yes,No""" - - df = pd.read_csv(StringIO(data), header=[0, 1], index_col=[0, 1, 2]) + levels = [ + ["Region_1"] * 4, + ["Site_1", "Site_1", "Site_2", "Site_2"], + [3987227376, 3980680971, 3977723249, 3977723089], + ] + mi = MultiIndex.from_arrays(levels, names=["Region", "Site", "RespondentID"]) + + clevels = [ + ["Respondent", "Respondent", "Respondent", "OtherCat", "OtherCat"], + ["Something", "StartDate", "EndDate", "Yes/No", "SomethingElse"], + ] + cols = MultiIndex.from_arrays(clevels, names=["Level_0", "Level_1"]) + + values = [ + ["A", "5/25/2015 10:59", "5/25/2015 11:22", "Yes", np.nan], + ["A", "5/21/2015 9:40", "5/21/2015 9:52", "Yes", "Yes"], + ["A", "5/20/2015 8:27", "5/20/2015 8:41", "Yes", np.nan], + ["A", "5/20/2015 8:33", "5/20/2015 9:09", "Yes", "No"], + ] + df = DataFrame(values, index=mi, columns=cols) + df.loc[:, ("Respondent", "StartDate")] = to_datetime( df.loc[:, ("Respondent", "StartDate")] ) diff --git a/pandas/tests/indexing/test_scalar.py b/pandas/tests/indexing/test_scalar.py index 39611bce2b4fa..bf262e6755289 100644 --- a/pandas/tests/indexing/test_scalar.py +++ b/pandas/tests/indexing/test_scalar.py @@ -74,8 +74,8 @@ def _check(f, func, values=False): _check(f, "at") -class TestScalar2: - # TODO: Better name, just separating things that dont need Base class +class TestAtAndiAT: + # at and iat tests that don't need Base class def test_at_iat_coercion(self): @@ -214,19 +214,6 @@ def test_iat_setter_incompatible_assignment(self): expected = DataFrame({"a": [None, 1], "b": [4, 5]}) tm.assert_frame_equal(result, expected) - def test_getitem_zerodim_np_array(self): - # GH24924 - # dataframe __getitem__ - df = DataFrame([[1, 2], [3, 4]]) - result = df[np.array(0)] - expected = Series([1, 3], name=0) - tm.assert_series_equal(result, expected) - - # series __getitem__ - s = Series([1, 2]) - result = s[np.array(0)] - assert result == 1 - def test_iat_dont_wrap_object_datetimelike(): # GH#32809 .iat calls go through DataFrame._get_value, should not diff --git a/pandas/tests/io/formats/test_console.py b/pandas/tests/io/formats/test_console.py index 39674db6916c1..5bd73e6045e32 100644 --- a/pandas/tests/io/formats/test_console.py +++ b/pandas/tests/io/formats/test_console.py @@ -5,7 +5,7 @@ from pandas._config import detect_console_encoding -class MockEncoding: # TODO(py27): replace with mock +class MockEncoding: """ Used to add a side effect when accessing the 'encoding' property. If the side effect is a str in nature, the value will be returned. Otherwise, the diff --git a/pandas/tests/plotting/test_backend.py b/pandas/tests/plotting/test_backend.py index 2eef940ee9a40..be053a8f46051 100644 --- a/pandas/tests/plotting/test_backend.py +++ b/pandas/tests/plotting/test_backend.py @@ -71,7 +71,7 @@ def test_register_entrypoint(restore_backend): result = pandas.plotting._core._get_plot_backend("my_backend") assert result is mod - # TODO: https://github.com/pandas-dev/pandas/issues/27517 + # TODO(GH#27517): https://github.com/pandas-dev/pandas/issues/27517 # Remove the td.skip_if_no_mpl with pandas.option_context("plotting.backend", "my_backend"): result = pandas.plotting._core._get_plot_backend() diff --git a/pandas/tests/reshape/test_melt.py b/pandas/tests/reshape/test_melt.py index af9d6dd83bee3..8a83cdcbdefb0 100644 --- a/pandas/tests/reshape/test_melt.py +++ b/pandas/tests/reshape/test_melt.py @@ -671,13 +671,12 @@ def test_simple(self): tm.assert_frame_equal(result, expected) def test_stubs(self): - # GH9204 + # GH9204 wide_to_long call should not modify 'stubs' list df = DataFrame([[0, 1, 2, 3, 8], [4, 5, 6, 7, 9]]) df.columns = ["id", "inc1", "inc2", "edu1", "edu2"] stubs = ["inc", "edu"] - # TODO: unused? - df_long = wide_to_long(df, stubs, i="id", j="age") # noqa + wide_to_long(df, stubs, i="id", j="age") assert stubs == ["inc", "edu"] diff --git a/pandas/tests/scalar/period/test_asfreq.py b/pandas/tests/scalar/period/test_asfreq.py index 9110352d33c26..386ab4150c6ff 100644 --- a/pandas/tests/scalar/period/test_asfreq.py +++ b/pandas/tests/scalar/period/test_asfreq.py @@ -428,9 +428,6 @@ def test_conv_daily(self): ival_D_saturday = Period(freq="D", year=2007, month=1, day=6) ival_D_sunday = Period(freq="D", year=2007, month=1, day=7) - # TODO: unused? - # ival_D_monday = Period(freq='D', year=2007, month=1, day=8) - ival_B_friday = Period(freq="B", year=2007, month=1, day=5) ival_B_monday = Period(freq="B", year=2007, month=1, day=8) diff --git a/pandas/tests/series/methods/test_asof.py b/pandas/tests/series/methods/test_asof.py index 7a3f68fd3d990..8ddcf07934e21 100644 --- a/pandas/tests/series/methods/test_asof.py +++ b/pandas/tests/series/methods/test_asof.py @@ -2,8 +2,10 @@ import pytest from pandas._libs.tslibs import IncompatibleFrequency +from pandas.compat import np_datetime64_compat from pandas import ( + DatetimeIndex, Series, Timestamp, date_range, @@ -15,6 +17,20 @@ class TestSeriesAsof: + def test_asof_nanosecond_index_access(self): + ts = Timestamp("20130101").value + dti = DatetimeIndex([ts + 50 + i for i in range(100)]) + ser = Series(np.random.randn(100), index=dti) + + first_value = ser.asof(ser.index[0]) + + # this used to not work bc parsing was done by dateutil that didn't + # handle nanoseconds + assert first_value == ser["2013-01-01 00:00:00.000000050+0000"] + + expected_ts = np_datetime64_compat("2013-01-01 00:00:00.000000050+0000", "ns") + assert first_value == ser[Timestamp(expected_ts)] + def test_basic(self): # array or list or dates diff --git a/pandas/tests/series/test_logical_ops.py b/pandas/tests/series/test_logical_ops.py index ec060aa91e383..563c8f63df57d 100644 --- a/pandas/tests/series/test_logical_ops.py +++ b/pandas/tests/series/test_logical_ops.py @@ -49,9 +49,6 @@ def test_logical_operators_bool_dtype_with_empty(self): def test_logical_operators_int_dtype_with_int_dtype(self): # GH#9016: support bitwise op for integer types - # TODO: unused - # s_0101 = Series([0, 1, 0, 1]) - s_0123 = Series(range(4), dtype="int64") s_3333 = Series([3] * 4) s_4444 = Series([4] * 4)
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/44348
2021-11-07T23:01:47Z
2021-11-08T13:13:09Z
2021-11-08T13:13:09Z
2021-11-08T14:57:32Z
REF: re-remove _putmask_preserve
diff --git a/pandas/core/array_algos/putmask.py b/pandas/core/array_algos/putmask.py index 54324bf721945..77e38e6c6e3fc 100644 --- a/pandas/core/array_algos/putmask.py +++ b/pandas/core/array_algos/putmask.py @@ -126,7 +126,8 @@ def putmask_smart(values: np.ndarray, mask: npt.NDArray[np.bool_], new) -> np.nd if values.dtype.kind == new.dtype.kind: # preserves dtype if possible - return _putmask_preserve(values, new, mask) + np.putmask(values, mask, new) + return values dtype = find_common_type([values.dtype, new.dtype]) # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has incompatible type @@ -135,15 +136,8 @@ def putmask_smart(values: np.ndarray, mask: npt.NDArray[np.bool_], new) -> np.nd # List[Any], _DTypeDict, Tuple[Any, Any]]]" values = values.astype(dtype) # type: ignore[arg-type] - return _putmask_preserve(values, new, mask) - - -def _putmask_preserve(new_values: np.ndarray, new, mask: npt.NDArray[np.bool_]): - try: - new_values[mask] = new[mask] - except (IndexError, ValueError): - new_values[mask] = new - return new_values + np.putmask(values, mask, new) + return values def putmask_without_repeat(
Un-revert half of #44338
https://api.github.com/repos/pandas-dev/pandas/pulls/44346
2021-11-07T19:36:21Z
2021-11-10T01:45:18Z
2021-11-10T01:45:18Z
2021-11-10T02:14:07Z
BUG: frame.loc[2:, 'z'] not setting inplace when multi-block
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 8732e1c397ce5..85f0f16c44b89 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -543,6 +543,7 @@ Indexing - Bug when setting string-backed :class:`Categorical` values that can be parsed to datetimes into a :class:`DatetimeArray` or :class:`Series` or :class:`DataFrame` column backed by :class:`DatetimeArray` failing to parse these strings (:issue:`44236`) - Bug in :meth:`Series.__setitem__` with an integer dtype other than ``int64`` setting with a ``range`` object unnecessarily upcasting to ``int64`` (:issue:`44261`) - Bug in :meth:`Series.__setitem__` with a boolean mask indexer setting a listlike value of length 1 incorrectly broadcasting that value (:issue:`44265`) +- Bug in :meth:`DataFrame.loc.__setitem__` and :meth:`DataFrame.iloc.__setitem__` with mixed dtypes sometimes failing to operate in-place (:issue:`44345`) - Missing diff --git a/pandas/core/indexing.py b/pandas/core/indexing.py index 669274e034905..4aa9d251b04c7 100644 --- a/pandas/core/indexing.py +++ b/pandas/core/indexing.py @@ -1859,10 +1859,19 @@ def _setitem_single_column(self, loc: int, value, plane_indexer): # in case of slice ser = value[pi] else: - # set the item, possibly having a dtype change - ser = ser.copy() - ser._mgr = ser._mgr.setitem(indexer=(pi,), value=value) - ser._maybe_update_cacher(clear=True, inplace=True) + # set the item, first attempting to operate inplace, then + # falling back to casting if necessary; see + # _whatsnew_130.notable_bug_fixes.setitem_column_try_inplace + + orig_values = ser._values + ser._mgr = ser._mgr.setitem((pi,), value) + + if ser._values is orig_values: + # The setitem happened inplace, so the DataFrame's values + # were modified inplace. + return + self.obj._iset_item(loc, ser, inplace=True) + return # reset the sliced object if unique self.obj._iset_item(loc, ser, inplace=True) diff --git a/pandas/io/stata.py b/pandas/io/stata.py index f6c93e6f751c8..9803a2e4e3309 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -600,6 +600,8 @@ def _cast_to_stata_types(data: DataFrame) -> DataFrame: # Cast from unsupported types to supported types is_nullable_int = isinstance(data[col].dtype, (_IntegerDtype, BooleanDtype)) orig = data[col] + # We need to find orig_missing before altering data below + orig_missing = orig.isna() if is_nullable_int: missing_loc = data[col].isna() if missing_loc.any(): @@ -650,11 +652,10 @@ def _cast_to_stata_types(data: DataFrame) -> DataFrame: f"supported by Stata ({float64_max})" ) if is_nullable_int: - missing = orig.isna() - if missing.any(): + if orig_missing.any(): # Replace missing by Stata sentinel value sentinel = StataMissingValue.BASE_MISSING_VALUES[data[col].dtype.name] - data.loc[missing, col] = sentinel + data.loc[orig_missing, col] = sentinel if ws: warnings.warn(ws, PossiblePrecisionLoss) diff --git a/pandas/tests/frame/indexing/test_setitem.py b/pandas/tests/frame/indexing/test_setitem.py index d735f0dbec8a5..389bf56ab6035 100644 --- a/pandas/tests/frame/indexing/test_setitem.py +++ b/pandas/tests/frame/indexing/test_setitem.py @@ -384,7 +384,7 @@ def test_setitem_frame_length_0_str_key(self, indexer): expected["A"] = expected["A"].astype("object") tm.assert_frame_equal(df, expected) - def test_setitem_frame_duplicate_columns(self, using_array_manager): + def test_setitem_frame_duplicate_columns(self, using_array_manager, request): # GH#15695 cols = ["A", "B", "C"] * 2 df = DataFrame(index=range(3), columns=cols) @@ -407,6 +407,11 @@ def test_setitem_frame_duplicate_columns(self, using_array_manager): expected["C"] = expected["C"].astype("int64") # TODO(ArrayManager) .loc still overwrites expected["B"] = expected["B"].astype("int64") + + mark = pytest.mark.xfail( + reason="Both 'A' columns get set with 3 instead of 0 and 3" + ) + request.node.add_marker(mark) else: # set these with unique columns to be extra-unambiguous expected[2] = expected[2].astype(np.int64) @@ -995,22 +1000,37 @@ def test_setitem_always_copy(self, float_frame): float_frame["E"][5:10] = np.nan assert notna(s[5:10]).all() - def test_setitem_clear_caches(self): - # see GH#304 + @pytest.mark.parametrize("consolidate", [True, False]) + def test_setitem_partial_column_inplace(self, consolidate, using_array_manager): + # This setting should be in-place, regardless of whether frame is + # single-block or multi-block + # GH#304 this used to be incorrectly not-inplace, in which case + # we needed to ensure _item_cache was cleared. + df = DataFrame( {"x": [1.1, 2.1, 3.1, 4.1], "y": [5.1, 6.1, 7.1, 8.1]}, index=[0, 1, 2, 3] ) df.insert(2, "z", np.nan) + if not using_array_manager: + if consolidate: + df._consolidate_inplace() + assert len(df._mgr.blocks) == 1 + else: + assert len(df._mgr.blocks) == 2 - # cache it - foo = df["z"] - df.loc[df.index[2:], "z"] = 42 + zvals = df["z"]._values - expected = Series([np.nan, np.nan, 42, 42], index=df.index, name="z") + df.loc[2:, "z"] = 42 - assert df["z"] is not foo + expected = Series([np.nan, np.nan, 42, 42], index=df.index, name="z") tm.assert_series_equal(df["z"], expected) + # check setting occurred in-place + tm.assert_numpy_array_equal(zvals, expected.values) + assert np.shares_memory(zvals, df["z"]._values) + if not consolidate: + assert df["z"]._values is zvals + def test_setitem_duplicate_columns_not_inplace(self): # GH#39510 cols = ["A", "B"] * 2 diff --git a/pandas/tests/frame/indexing/test_xs.py b/pandas/tests/frame/indexing/test_xs.py index d2704876c31c5..c6938abb57d64 100644 --- a/pandas/tests/frame/indexing/test_xs.py +++ b/pandas/tests/frame/indexing/test_xs.py @@ -366,12 +366,7 @@ def test_xs_droplevel_false_view(self, using_array_manager): assert np.shares_memory(result.iloc[:, 0]._values, df.iloc[:, 0]._values) # modifying original df also modifies result when having a single block df.iloc[0, 0] = 2 - if not using_array_manager: - expected = DataFrame({"a": [2]}) - else: - # TODO(ArrayManager) iloc does not update the array inplace using - # "split" path - expected = DataFrame({"a": [1]}) + expected = DataFrame({"a": [2]}) tm.assert_frame_equal(result, expected) # with mixed dataframe, modifying the parent doesn't modify result @@ -379,7 +374,13 @@ def test_xs_droplevel_false_view(self, using_array_manager): df = DataFrame([[1, 2.5, "a"]], columns=Index(["a", "b", "c"])) result = df.xs("a", axis=1, drop_level=False) df.iloc[0, 0] = 2 - expected = DataFrame({"a": [1]}) + if using_array_manager: + # Here the behavior is consistent + expected = DataFrame({"a": [2]}) + else: + # FIXME: iloc does not update the array inplace using + # "split" path + expected = DataFrame({"a": [1]}) tm.assert_frame_equal(result, expected) def test_xs_list_indexer_droplevel_false(self): diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 919d8ab14778e..fc2c138538ac9 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -789,6 +789,10 @@ def test_std_timedelta64_skipna_false(self): # GH#37392 tdi = pd.timedelta_range("1 Day", periods=10) df = DataFrame({"A": tdi, "B": tdi}) + # Copy is needed for ArrayManager case, otherwise setting df.iloc + # below edits tdi, alterting both df['A'] and df['B'] + # FIXME: passing copy=True to constructor does not fix this + df = df.copy() df.iloc[-2, -1] = pd.NaT result = df.std(skipna=False) @@ -1017,7 +1021,9 @@ def test_idxmax_mixed_dtype(self): # don't cast to object, which would raise in nanops dti = date_range("2016-01-01", periods=3) - df = DataFrame({1: [0, 2, 1], 2: range(3)[::-1], 3: dti}) + # Copying dti is needed for ArrayManager otherwise when we set + # df.loc[0, 3] = pd.NaT below it edits dti + df = DataFrame({1: [0, 2, 1], 2: range(3)[::-1], 3: dti.copy(deep=True)}) result = df.idxmax() expected = Series([1, 0, 2], index=[1, 2, 3]) @@ -1074,6 +1080,10 @@ def test_idxmax_idxmin_convert_dtypes(self, op, expected_value): def test_idxmax_dt64_multicolumn_axis1(self): dti = date_range("2016-01-01", periods=3) df = DataFrame({3: dti, 4: dti[::-1]}) + # FIXME: copy needed for ArrayManager, otherwise setting with iloc + # below also sets df.iloc[-1, 1]; passing copy=True to DataFrame + # does not solve this. + df = df.copy() df.iloc[0, 0] = pd.NaT df._consolidate_inplace()
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/44345
2021-11-07T19:04:39Z
2021-11-13T00:28:44Z
2021-11-13T00:28:44Z
2021-11-13T00:32:18Z
TYP: timestamps.pyi
diff --git a/pandas/_libs/tslibs/timestamps.pyi b/pandas/_libs/tslibs/timestamps.pyi index 17df594a39c44..9693f18e2e05d 100644 --- a/pandas/_libs/tslibs/timestamps.pyi +++ b/pandas/_libs/tslibs/timestamps.pyi @@ -8,7 +8,6 @@ from datetime import ( from time import struct_time from typing import ( ClassVar, - Type, TypeVar, overload, ) @@ -22,9 +21,9 @@ from pandas._libs.tslibs import ( Timedelta, ) -_S = TypeVar("_S") +_S = TypeVar("_S", bound=datetime) -def integer_op_not_supported(obj) -> TypeError: ... +def integer_op_not_supported(obj: object) -> TypeError: ... class Timestamp(datetime): min: ClassVar[Timestamp] @@ -35,7 +34,7 @@ class Timestamp(datetime): # error: "__new__" must return a class instance (got "Union[Timestamp, NaTType]") def __new__( # type: ignore[misc] - cls: Type[_S], + cls: type[_S], ts_input: int | np.integer | float @@ -43,9 +42,9 @@ class Timestamp(datetime): | _date | datetime | np.datetime64 = ..., - freq=..., + freq: int | None | str | BaseOffset = ..., tz: str | _tzinfo | None | int = ..., - unit=..., + unit: str | int | None = ..., year: int | None = ..., month: int | None = ..., day: int | None = ..., @@ -80,24 +79,28 @@ class Timestamp(datetime): @property def fold(self) -> int: ... @classmethod - def fromtimestamp(cls: Type[_S], t: float, tz: _tzinfo | None = ...) -> _S: ... + def fromtimestamp(cls: type[_S], t: float, tz: _tzinfo | None = ...) -> _S: ... @classmethod - def utcfromtimestamp(cls: Type[_S], t: float) -> _S: ... + def utcfromtimestamp(cls: type[_S], t: float) -> _S: ... @classmethod - def today(cls: Type[_S]) -> _S: ... + def today(cls: type[_S], tz: _tzinfo | str | None = ...) -> _S: ... @classmethod - def fromordinal(cls: Type[_S], n: int) -> _S: ... + def fromordinal( + cls: type[_S], + ordinal: int, + freq: str | BaseOffset | None = ..., + tz: _tzinfo | str | None = ..., + ) -> _S: ... @classmethod - def now(cls: Type[_S], tz: _tzinfo | str | None = ...) -> _S: ... + def now(cls: type[_S], tz: _tzinfo | str | None = ...) -> _S: ... @classmethod - def utcnow(cls: Type[_S]) -> _S: ... + def utcnow(cls: type[_S]) -> _S: ... + # error: Signature of "combine" incompatible with supertype "datetime" @classmethod - def combine( - cls, date: _date, time: _time, tzinfo: _tzinfo | None = ... - ) -> datetime: ... + def combine(cls, date: _date, time: _time) -> datetime: ... # type: ignore[override] @classmethod - def fromisoformat(cls: Type[_S], date_string: str) -> _S: ... - def strftime(self, fmt: str) -> str: ... + def fromisoformat(cls: type[_S], date_string: str) -> _S: ... + def strftime(self, format: str) -> str: ... def __format__(self, fmt: str) -> str: ... def toordinal(self) -> int: ... def timetuple(self) -> struct_time: ... @@ -116,12 +119,12 @@ class Timestamp(datetime): second: int = ..., microsecond: int = ..., tzinfo: _tzinfo | None = ..., - *, fold: int = ..., ) -> datetime: ... def astimezone(self: _S, tz: _tzinfo | None = ...) -> _S: ... def ctime(self) -> str: ... - def isoformat(self, sep: str = ..., timespec: str = ...) -> str: ... + # error: Signature of "isoformat" incompatible with supertype "datetime" + def isoformat(self, sep: str = ...) -> str: ... # type: ignore[override] @classmethod def strptime(cls, date_string: str, format: str) -> datetime: ... def utcoffset(self) -> timedelta | None: ... @@ -131,12 +134,18 @@ class Timestamp(datetime): def __lt__(self, other: datetime) -> bool: ... # type: ignore def __ge__(self, other: datetime) -> bool: ... # type: ignore def __gt__(self, other: datetime) -> bool: ... # type: ignore - def __add__(self: _S, other: timedelta) -> _S: ... + # error: Signature of "__add__" incompatible with supertype "date"/"datetime" + @overload # type: ignore[override] + def __add__(self, other: np.ndarray) -> np.ndarray: ... + @overload + # TODO: other can also be Tick (but it cannot be resolved) + def __add__(self: _S, other: timedelta | np.timedelta64) -> _S: ... def __radd__(self: _S, other: timedelta) -> _S: ... @overload # type: ignore def __sub__(self, other: datetime) -> timedelta: ... @overload - def __sub__(self, other: timedelta) -> datetime: ... + # TODO: other can also be Tick (but it cannot be resolved) + def __sub__(self, other: timedelta | np.timedelta64) -> datetime: ... def __hash__(self) -> int: ... def weekday(self) -> int: ... def isoweekday(self) -> int: ... @@ -157,23 +166,38 @@ class Timestamp(datetime): def is_year_end(self) -> bool: ... def to_pydatetime(self, warn: bool = ...) -> datetime: ... def to_datetime64(self) -> np.datetime64: ... - def to_period(self, freq) -> Period: ... + def to_period(self, freq: BaseOffset | str | None = ...) -> Period: ... def to_julian_date(self) -> np.float64: ... @property def asm8(self) -> np.datetime64: ... - def tz_convert(self: _S, tz) -> _S: ... + def tz_convert(self: _S, tz: _tzinfo | str | None) -> _S: ... # TODO: could return NaT? def tz_localize( - self: _S, tz, ambiguous: str = ..., nonexistent: str = ... + self: _S, tz: _tzinfo | str | None, ambiguous: str = ..., nonexistent: str = ... ) -> _S: ... def normalize(self: _S) -> _S: ... # TODO: round/floor/ceil could return NaT? def round( - self: _S, freq, ambiguous: bool | str = ..., nonexistent: str = ... + self: _S, freq: str, ambiguous: bool | str = ..., nonexistent: str = ... ) -> _S: ... def floor( - self: _S, freq, ambiguous: bool | str = ..., nonexistent: str = ... + self: _S, freq: str, ambiguous: bool | str = ..., nonexistent: str = ... ) -> _S: ... def ceil( - self: _S, freq, ambiguous: bool | str = ..., nonexistent: str = ... + self: _S, freq: str, ambiguous: bool | str = ..., nonexistent: str = ... ) -> _S: ... + def day_name(self, locale: str | None = ...) -> str: ... + def month_name(self, locale: str | None = ...) -> str: ... + @property + def day_of_week(self) -> int: ... + @property + def day_of_month(self) -> int: ... + @property + def day_of_year(self) -> int: ... + @property + def quarter(self) -> int: ... + @property + def week(self) -> int: ... + def to_numpy( + self, dtype: np.dtype | None = ..., copy: bool = ... + ) -> np.datetime64: ...
Should type annotations from a pyi files also be added to the pyx file (if possible)?
https://api.github.com/repos/pandas-dev/pandas/pulls/44339
2021-11-06T23:59:15Z
2021-12-19T22:41:15Z
2021-12-19T22:41:15Z
2021-12-20T16:20:29Z
Revert "REF: remove putmask_preserve, putmask_without_repeat"
diff --git a/pandas/core/array_algos/putmask.py b/pandas/core/array_algos/putmask.py index b17e86e774f60..54324bf721945 100644 --- a/pandas/core/array_algos/putmask.py +++ b/pandas/core/array_algos/putmask.py @@ -126,8 +126,7 @@ def putmask_smart(values: np.ndarray, mask: npt.NDArray[np.bool_], new) -> np.nd if values.dtype.kind == new.dtype.kind: # preserves dtype if possible - np.putmask(values, mask, new) - return values + return _putmask_preserve(values, new, mask) dtype = find_common_type([values.dtype, new.dtype]) # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has incompatible type @@ -136,8 +135,51 @@ def putmask_smart(values: np.ndarray, mask: npt.NDArray[np.bool_], new) -> np.nd # List[Any], _DTypeDict, Tuple[Any, Any]]]" values = values.astype(dtype) # type: ignore[arg-type] - np.putmask(values, mask, new) - return values + return _putmask_preserve(values, new, mask) + + +def _putmask_preserve(new_values: np.ndarray, new, mask: npt.NDArray[np.bool_]): + try: + new_values[mask] = new[mask] + except (IndexError, ValueError): + new_values[mask] = new + return new_values + + +def putmask_without_repeat( + values: np.ndarray, mask: npt.NDArray[np.bool_], new: Any +) -> None: + """ + np.putmask will truncate or repeat if `new` is a listlike with + len(new) != len(values). We require an exact match. + + Parameters + ---------- + values : np.ndarray + mask : np.ndarray[bool] + new : Any + """ + if getattr(new, "ndim", 0) >= 1: + new = new.astype(values.dtype, copy=False) + + # TODO: this prob needs some better checking for 2D cases + nlocs = mask.sum() + if nlocs > 0 and is_list_like(new) and getattr(new, "ndim", 1) == 1: + if nlocs == len(new): + # GH#30567 + # If length of ``new`` is less than the length of ``values``, + # `np.putmask` would first repeat the ``new`` array and then + # assign the masked values hence produces incorrect result. + # `np.place` on the other hand uses the ``new`` values at it is + # to place in the masked locations of ``values`` + np.place(values, mask, new) + # i.e. values[mask] = new + elif mask.shape[-1] == len(new) or len(new) == 1: + np.putmask(values, mask, new) + else: + raise ValueError("cannot assign mismatch length to masked array") + else: + np.putmask(values, mask, new) def validate_putmask( diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index a452eabd4ea6f..2589015e0f0b1 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -51,7 +51,6 @@ is_extension_array_dtype, is_interval_dtype, is_list_like, - is_object_dtype, is_string_dtype, ) from pandas.core.dtypes.dtypes import ( @@ -77,6 +76,7 @@ extract_bool_array, putmask_inplace, putmask_smart, + putmask_without_repeat, setitem_datetimelike_compat, validate_putmask, ) @@ -960,7 +960,10 @@ def putmask(self, mask, new) -> list[Block]: new = self.fill_value if self._can_hold_element(new): - np.putmask(self.values.T, mask, new) + + # error: Argument 1 to "putmask_without_repeat" has incompatible type + # "Union[ndarray, ExtensionArray]"; expected "ndarray" + putmask_without_repeat(self.values.T, mask, new) # type: ignore[arg-type] return [self] elif noop: @@ -1412,16 +1415,15 @@ def putmask(self, mask, new) -> list[Block]: new_values = self.values + if isinstance(new, (np.ndarray, ExtensionArray)) and len(new) == len(mask): + new = new[mask] + if mask.ndim == new_values.ndim + 1: # TODO(EA2D): unnecessary with 2D EAs mask = mask.reshape(new_values.shape) try: - if isinstance(new, (np.ndarray, ExtensionArray)): - # Caller is responsible for ensuring matching lengths - new_values[mask] = new[mask] - else: - new_values[mask] = new + new_values[mask] = new except TypeError: if not is_interval_dtype(self.dtype): # Discussion about what we want to support in the general @@ -1479,14 +1481,7 @@ def setitem(self, indexer, value): # we are always 1-D indexer = indexer[0] - try: - check_setitem_lengths(indexer, value, self.values) - except ValueError: - # If we are object dtype (e.g. PandasDtype[object]) then - # we can hold nested data, so can ignore this mismatch. - if not is_object_dtype(self.dtype): - raise - + check_setitem_lengths(indexer, value, self.values) self.values[indexer] = value return self diff --git a/pandas/core/series.py b/pandas/core/series.py index 579c16613ec2e..7ee9a0bcdd9e1 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1101,6 +1101,7 @@ def __setitem__(self, key, value) -> None: is_list_like(value) and len(value) != len(self) and not isinstance(value, Series) + and not is_object_dtype(self.dtype) ): # Series will be reindexed to have matching length inside # _where call below diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index df424e649fbe9..e60f7769270bd 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -363,11 +363,6 @@ def test_concat(self, data, in_frame): class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): - @skip_nested - def test_setitem_sequence_mismatched_length_raises(self, data, as_array): - # doesn't raise bc object dtype holds nested data - super().test_setitem_sequence_mismatched_length_raises(data, as_array) - @skip_nested def test_setitem_invalid(self, data, invalid_scalar): # object dtype can hold anything, so doesn't raise
Reverts pandas-dev/pandas#44328 cc @jbrockmendel
https://api.github.com/repos/pandas-dev/pandas/pulls/44338
2021-11-06T21:26:42Z
2021-11-06T22:28:05Z
2021-11-06T22:28:05Z
2021-11-06T22:28:11Z
ENH: option to change the number in `_dir_additions_for_owner`
diff --git a/doc/source/user_guide/options.rst b/doc/source/user_guide/options.rst index a65bb774b9df8..93448dae578c9 100644 --- a/doc/source/user_guide/options.rst +++ b/doc/source/user_guide/options.rst @@ -430,6 +430,10 @@ display.html.use_mathjax True When True, Jupyter notebook table contents using MathJax, rendering mathematical expressions enclosed by the dollar symbol. +display.max_dir_items 100 The number of columns from a dataframe that + are added to dir. These columns can then be + suggested by tab completion. 'None' value means + unlimited. io.excel.xls.writer xlwt The default Excel writer engine for 'xls' files. diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index ad6bf64dcdfa8..64bdbca9c1f27 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -213,7 +213,7 @@ Other enhancements - :meth:`.GroupBy.mean` now supports `Numba <http://numba.pydata.org/>`_ execution with the ``engine`` keyword (:issue:`43731`) - :meth:`Timestamp.isoformat`, now handles the ``timespec`` argument from the base :class:``datetime`` class (:issue:`26131`) - :meth:`NaT.to_numpy` ``dtype`` argument is now respected, so ``np.timedelta64`` can be returned (:issue:`44460`) -- +- New option ``display.max_dir_items`` customizes the number of columns added to :meth:`Dataframe.__dir__` and suggested for tab completion (:issue:`37996`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/config_init.py b/pandas/core/config_init.py index 31c2ec8f0cbf9..bf2d770ee1e7f 100644 --- a/pandas/core/config_init.py +++ b/pandas/core/config_init.py @@ -238,6 +238,16 @@ def use_numba_cb(key): (default: True) """ +pc_max_dir_items = """\ +: int + The number of items that will be added to `dir(...)`. 'None' value means + unlimited. Because dir is cached, changing this option will not immediately + affect already existing dataframes until a column is deleted or added. + + This is for instance used to suggest columns from a dataframe to tab + completion. +""" + pc_width_doc = """ : int Width of the display in characters. In case python/IPython is running in @@ -451,6 +461,9 @@ def _deprecate_negative_int_max_colwidth(key): cf.register_option( "html.use_mathjax", True, pc_html_use_mathjax_doc, validator=is_bool ) + cf.register_option( + "max_dir_items", 100, pc_max_dir_items, validator=is_nonnegative_int + ) tc_sim_interactive_doc = """ : boolean diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 220b43f323a5f..5f7bc718215be 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -846,7 +846,7 @@ def _dir_additions_for_owner(self) -> set[str_t]: """ return { c - for c in self.unique(level=0)[:100] + for c in self.unique(level=0)[: get_option("display.max_dir_items")] if isinstance(c, str) and c.isidentifier() } diff --git a/pandas/tests/frame/test_api.py b/pandas/tests/frame/test_api.py index 2e276f4f27a67..3adc4ebceaad5 100644 --- a/pandas/tests/frame/test_api.py +++ b/pandas/tests/frame/test_api.py @@ -5,6 +5,8 @@ import numpy as np import pytest +from pandas._config.config import option_context + import pandas.util._test_decorators as td from pandas.util._test_decorators import ( async_mark, @@ -87,6 +89,25 @@ def test_tab_completion(self): assert key not in dir(df) assert isinstance(df.__getitem__("A"), DataFrame) + def test_display_max_dir_items(self): + # display.max_dir_items increaes the number of columns that are in __dir__. + columns = ["a" + str(i) for i in range(420)] + values = [range(420), range(420)] + df = DataFrame(values, columns=columns) + + # The default value for display.max_dir_items is 100 + assert "a99" in dir(df) + assert "a100" not in dir(df) + + with option_context("display.max_dir_items", 300): + df = DataFrame(values, columns=columns) + assert "a299" in dir(df) + assert "a300" not in dir(df) + + with option_context("display.max_dir_items", None): + df = DataFrame(values, columns=columns) + assert "a419" in dir(df) + def test_not_hashable(self): empty_frame = DataFrame()
- [x] closes #37996 - [x] tests added / passed - [x] Allows to optionally change the number of columns from a dataframe that are added to `dir`, which is frequently also the number of columns suggested by tab completion, by using the option `pandas.set_option('display.max_dir_additions', 100)` to a higher number than 100 or None for an unlimited number of columns. Changing the value of `display.max_dir_additions` will only take effect for existing dataframes after a column is added or deleted, as the result of `dir` is cached.
https://api.github.com/repos/pandas-dev/pandas/pulls/44335
2021-11-06T16:39:28Z
2021-11-26T15:02:54Z
2021-11-26T15:02:53Z
2021-11-26T15:02:57Z
TST: use custom parametrization for consistency in base extension array tests
diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py index c52f20255eb81..1d3d736ca7ee2 100644 --- a/pandas/tests/extension/base/ops.py +++ b/pandas/tests/extension/base/ops.py @@ -162,13 +162,12 @@ def test_compare_array(self, data, comparison_op): other = pd.Series([data[0]] * len(data)) self._compare_other(ser, data, comparison_op, other) - def test_direct_arith_with_ndframe_returns_not_implemented( - self, data, frame_or_series - ): + @pytest.mark.parametrize("box", [pd.Series, pd.DataFrame]) + def test_direct_arith_with_ndframe_returns_not_implemented(self, data, box): # EAs should return NotImplemented for ops with Series/DataFrame # Pandas takes care of unboxing the series and calling the EA's op. other = pd.Series(data) - if frame_or_series is pd.DataFrame: + if box is pd.DataFrame: other = other.to_frame() if hasattr(data, "__eq__"):
Follow-up on https://github.com/pandas-dev/pandas/pull/44242, as that broke geopandas CI. This adds back the custom parametrization, which also makes it consistent with the other occurrence of this test (for a different op) which is still using this: https://github.com/pandas-dev/pandas/blob/057c6f81b464c6bbb667d326e203ad0dbd17cbde/pandas/tests/extension/base/ops.py#L116-L127 Since this is the only occurrence of `frame_or_series` in the base extension tests, I think it's not warranted to make it a fixture. If we would rather want this, we should add it to `tests/extension/conftest.py` instead (can always be done in a follow-up).
https://api.github.com/repos/pandas-dev/pandas/pulls/44332
2021-11-06T10:16:12Z
2021-11-11T20:10:23Z
2021-11-11T20:10:23Z
2021-11-11T20:10:27Z
DOC: df.to_html documentation incorrectly contains min_rows optional param
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 4e7f6329bb73b..b97175cc57fd3 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1065,11 +1065,11 @@ def to_string( index_names: bool = True, justify: str | None = None, max_rows: int | None = None, - min_rows: int | None = None, max_cols: int | None = None, show_dimensions: bool = False, decimal: str = ".", line_width: int | None = None, + min_rows: int | None = None, max_colwidth: int | None = None, encoding: str | None = None, ) -> str | None: @@ -1078,6 +1078,9 @@ def to_string( %(shared_params)s line_width : int, optional Width to wrap a line in characters. + min_rows : int, optional + The number of rows to display in the console in a truncated repr + (when number of rows is above `max_rows`). max_colwidth : int, optional Max width to truncate each column in characters. By default, no limit. @@ -2838,15 +2841,14 @@ def to_html( border : int A ``border=border`` attribute is included in the opening `<table>` tag. Default ``pd.options.display.html.border``. - encoding : str, default "utf-8" - Set character encoding. - - .. versionadded:: 1.0 - table_id : str, optional A css id is included in the opening `<table>` tag if specified. render_links : bool, default False Convert URLs to HTML links. + encoding : str, default "utf-8" + Set character encoding. + + .. versionadded:: 1.0 %(returns)s See Also -------- diff --git a/pandas/io/formats/format.py b/pandas/io/formats/format.py index ba85a1b340d05..ca53bfb7d5e08 100644 --- a/pandas/io/formats/format.py +++ b/pandas/io/formats/format.py @@ -164,9 +164,6 @@ * unset. max_rows : int, optional Maximum number of rows to display in the console. - min_rows : int, optional - The number of rows to display in the console in a truncated repr - (when number of rows is above `max_rows`). max_cols : int, optional Maximum number of columns to display in the console. show_dimensions : bool, default False
- [x] closes #44304 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [NA] whatsnew entry Moved min_rows parameter out of the common docstring that is used by both DataFrame.to_html and DataFrame.to_string and reintroduced the parameter in DataFrame.to_string only
https://api.github.com/repos/pandas-dev/pandas/pulls/44331
2021-11-06T03:41:55Z
2021-11-14T02:40:08Z
2021-11-14T02:40:07Z
2021-11-15T10:50:07Z
CLN: remove _AXIS_REVERSED
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 4e7f6329bb73b..ebf3428020652 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1686,9 +1686,7 @@ def to_numpy( self._consolidate_inplace() if dtype is not None: dtype = np.dtype(dtype) - result = self._mgr.as_array( - transpose=self._AXIS_REVERSED, dtype=dtype, copy=copy, na_value=na_value - ) + result = self._mgr.as_array(dtype=dtype, copy=copy, na_value=na_value) if result.dtype is not dtype: result = np.array(result, dtype=dtype, copy=False) @@ -10715,7 +10713,6 @@ def isin(self, values) -> DataFrame: 1: 1, "columns": 1, } - _AXIS_REVERSED = True _AXIS_LEN = len(_AXIS_ORDERS) _info_axis_number = 1 _info_axis_name = "columns" @@ -10840,7 +10837,7 @@ def values(self) -> np.ndarray: ['monkey', nan, None]], dtype=object) """ self._consolidate_inplace() - return self._mgr.as_array(transpose=True) + return self._mgr.as_array() @deprecate_nonkeyword_arguments(version=None, allowed_args=["self"]) def ffill( diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 732508f9b7fb6..13e1c6e7e20b1 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -479,7 +479,6 @@ def _data(self): _stat_axis_name = "index" _AXIS_ORDERS: list[str] _AXIS_TO_AXIS_NUMBER: dict[Axis, int] = {0: 0, "index": 0, "rows": 0} - _AXIS_REVERSED: bool_t _info_axis_number: int _info_axis_name: str _AXIS_LEN: int @@ -566,9 +565,10 @@ def _get_axis(self, axis: Axis) -> Index: def _get_block_manager_axis(cls, axis: Axis) -> int: """Map the axis to the block_manager axis.""" axis = cls._get_axis_number(axis) - if cls._AXIS_REVERSED: - m = cls._AXIS_LEN - 1 - return m - axis + ndim = cls._AXIS_LEN + if ndim == 2: + # i.e. DataFrame + return 1 - axis return axis @final diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index fc7d2168c1c79..543b2ea26f750 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -1082,7 +1082,6 @@ def unstack(self, unstacker, fill_value) -> ArrayManager: def as_array( self, - transpose: bool = False, dtype=None, copy: bool = False, na_value=lib.no_default, @@ -1092,8 +1091,6 @@ def as_array( Parameters ---------- - transpose : bool, default False - If True, transpose the return array. dtype : object, default None Data type of the return array. copy : bool, default False @@ -1109,7 +1106,7 @@ def as_array( """ if len(self.arrays) == 0: empty_arr = np.empty(self.shape, dtype=float) - return empty_arr.transpose() if transpose else empty_arr + return empty_arr.transpose() # We want to copy when na_value is provided to avoid # mutating the original object @@ -1137,8 +1134,6 @@ def as_array( result[isna(result)] = na_value return result - # FIXME: don't leave commented-out - # return arr.transpose() if transpose else arr class SingleArrayManager(BaseArrayManager, SingleDataManager): diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 7db19eda0f2fb..05a9aab4a5554 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -1465,7 +1465,6 @@ def to_dict(self, copy: bool = True): def as_array( self, - transpose: bool = False, dtype: np.dtype | None = None, copy: bool = False, na_value=lib.no_default, @@ -1475,8 +1474,6 @@ def as_array( Parameters ---------- - transpose : bool, default False - If True, transpose the return array. dtype : np.dtype or None, default None Data type of the return array. copy : bool, default False @@ -1492,7 +1489,7 @@ def as_array( """ if len(self.blocks) == 0: arr = np.empty(self.shape, dtype=float) - return arr.transpose() if transpose else arr + return arr.transpose() # We want to copy when na_value is provided to avoid # mutating the original object @@ -1524,7 +1521,7 @@ def as_array( if na_value is not lib.no_default: arr[isna(arr)] = na_value - return arr.transpose() if transpose else arr + return arr.transpose() def _interleave( self, diff --git a/pandas/core/series.py b/pandas/core/series.py index cfa3e90f8bc73..7ee9a0bcdd9e1 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -5498,7 +5498,6 @@ def mask( # ---------------------------------------------------------------------- # Add index _AXIS_ORDERS = ["index"] - _AXIS_REVERSED = False _AXIS_LEN = len(_AXIS_ORDERS) _info_axis_number = 0 _info_axis_name = "index" diff --git a/pandas/tests/internals/test_internals.py b/pandas/tests/internals/test_internals.py index 54706dc24fc42..b577bc7e436df 100644 --- a/pandas/tests/internals/test_internals.py +++ b/pandas/tests/internals/test_internals.py @@ -851,7 +851,7 @@ def test_validate_bool_args(self, value): def _as_array(mgr): if mgr.ndim == 1: return mgr.external_values() - return mgr.as_array() + return mgr.as_array().T class TestIndexing:
Motivated by the FIXME in ArrayManager.as_array
https://api.github.com/repos/pandas-dev/pandas/pulls/44330
2021-11-06T02:03:17Z
2021-11-06T19:41:13Z
2021-11-06T19:41:13Z
2021-11-06T19:41:52Z
REF: remove putmask_preserve, putmask_without_repeat
diff --git a/pandas/core/array_algos/putmask.py b/pandas/core/array_algos/putmask.py index 54324bf721945..b17e86e774f60 100644 --- a/pandas/core/array_algos/putmask.py +++ b/pandas/core/array_algos/putmask.py @@ -126,7 +126,8 @@ def putmask_smart(values: np.ndarray, mask: npt.NDArray[np.bool_], new) -> np.nd if values.dtype.kind == new.dtype.kind: # preserves dtype if possible - return _putmask_preserve(values, new, mask) + np.putmask(values, mask, new) + return values dtype = find_common_type([values.dtype, new.dtype]) # error: Argument 1 to "astype" of "_ArrayOrScalarCommon" has incompatible type @@ -135,51 +136,8 @@ def putmask_smart(values: np.ndarray, mask: npt.NDArray[np.bool_], new) -> np.nd # List[Any], _DTypeDict, Tuple[Any, Any]]]" values = values.astype(dtype) # type: ignore[arg-type] - return _putmask_preserve(values, new, mask) - - -def _putmask_preserve(new_values: np.ndarray, new, mask: npt.NDArray[np.bool_]): - try: - new_values[mask] = new[mask] - except (IndexError, ValueError): - new_values[mask] = new - return new_values - - -def putmask_without_repeat( - values: np.ndarray, mask: npt.NDArray[np.bool_], new: Any -) -> None: - """ - np.putmask will truncate or repeat if `new` is a listlike with - len(new) != len(values). We require an exact match. - - Parameters - ---------- - values : np.ndarray - mask : np.ndarray[bool] - new : Any - """ - if getattr(new, "ndim", 0) >= 1: - new = new.astype(values.dtype, copy=False) - - # TODO: this prob needs some better checking for 2D cases - nlocs = mask.sum() - if nlocs > 0 and is_list_like(new) and getattr(new, "ndim", 1) == 1: - if nlocs == len(new): - # GH#30567 - # If length of ``new`` is less than the length of ``values``, - # `np.putmask` would first repeat the ``new`` array and then - # assign the masked values hence produces incorrect result. - # `np.place` on the other hand uses the ``new`` values at it is - # to place in the masked locations of ``values`` - np.place(values, mask, new) - # i.e. values[mask] = new - elif mask.shape[-1] == len(new) or len(new) == 1: - np.putmask(values, mask, new) - else: - raise ValueError("cannot assign mismatch length to masked array") - else: - np.putmask(values, mask, new) + np.putmask(values, mask, new) + return values def validate_putmask( diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 33c78f396b80b..758633a7ab956 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -51,6 +51,7 @@ is_extension_array_dtype, is_interval_dtype, is_list_like, + is_object_dtype, is_string_dtype, ) from pandas.core.dtypes.dtypes import ( @@ -76,7 +77,6 @@ extract_bool_array, putmask_inplace, putmask_smart, - putmask_without_repeat, setitem_datetimelike_compat, validate_putmask, ) @@ -960,10 +960,7 @@ def putmask(self, mask, new) -> list[Block]: new = self.fill_value if self._can_hold_element(new): - - # error: Argument 1 to "putmask_without_repeat" has incompatible type - # "Union[ndarray, ExtensionArray]"; expected "ndarray" - putmask_without_repeat(self.values.T, mask, new) # type: ignore[arg-type] + np.putmask(self.values.T, mask, new) return [self] elif noop: @@ -1407,15 +1404,16 @@ def putmask(self, mask, new) -> list[Block]: new_values = self.values - if isinstance(new, (np.ndarray, ExtensionArray)) and len(new) == len(mask): - new = new[mask] - if mask.ndim == new_values.ndim + 1: # TODO(EA2D): unnecessary with 2D EAs mask = mask.reshape(new_values.shape) try: - new_values[mask] = new + if isinstance(new, (np.ndarray, ExtensionArray)): + # Caller is responsible for ensuring matching lengths + new_values[mask] = new[mask] + else: + new_values[mask] = new except TypeError: if not is_interval_dtype(self.dtype): # Discussion about what we want to support in the general @@ -1473,7 +1471,14 @@ def setitem(self, indexer, value): # we are always 1-D indexer = indexer[0] - check_setitem_lengths(indexer, value, self.values) + try: + check_setitem_lengths(indexer, value, self.values) + except ValueError: + # If we are object dtype (e.g. PandasDtype[object]) then + # we can hold nested data, so can ignore this mismatch. + if not is_object_dtype(self.dtype): + raise + self.values[indexer] = value return self diff --git a/pandas/core/series.py b/pandas/core/series.py index 02f4810bb1e6b..77789fd6f7d68 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1101,7 +1101,6 @@ def __setitem__(self, key, value) -> None: is_list_like(value) and len(value) != len(self) and not isinstance(value, Series) - and not is_object_dtype(self.dtype) ): # Series will be reindexed to have matching length inside # _where call below diff --git a/pandas/tests/extension/test_numpy.py b/pandas/tests/extension/test_numpy.py index e60f7769270bd..df424e649fbe9 100644 --- a/pandas/tests/extension/test_numpy.py +++ b/pandas/tests/extension/test_numpy.py @@ -363,6 +363,11 @@ def test_concat(self, data, in_frame): class TestSetitem(BaseNumPyTests, base.BaseSetitemTests): + @skip_nested + def test_setitem_sequence_mismatched_length_raises(self, data, as_array): + # doesn't raise bc object dtype holds nested data + super().test_setitem_sequence_mismatched_length_raises(data, as_array) + @skip_nested def test_setitem_invalid(self, data, invalid_scalar): # object dtype can hold anything, so doesn't raise
No longer needed following #44275
https://api.github.com/repos/pandas-dev/pandas/pulls/44328
2021-11-05T18:51:14Z
2021-11-06T19:42:42Z
2021-11-06T19:42:42Z
2021-11-06T21:10:02Z
BUG: is_dtype_equal(dtype, "string[pyarrow]") raises if pyarrow not installed
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 4f7eb7c87b260..1765b22dda05f 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -655,7 +655,7 @@ Conversion Strings ^^^^^^^ -- +- Fixed bug in checking for ``string[pyarrow]`` dtype incorrectly raising an ImportError when pyarrow is not installed (:issue:`44327`) - Interval diff --git a/pandas/core/dtypes/common.py b/pandas/core/dtypes/common.py index 72cc28c1dd66d..75689b8dba8f5 100644 --- a/pandas/core/dtypes/common.py +++ b/pandas/core/dtypes/common.py @@ -613,7 +613,7 @@ def is_dtype_equal(source, target) -> bool: src = get_dtype(source) if isinstance(src, ExtensionDtype): return src == target - except (TypeError, AttributeError): + except (TypeError, AttributeError, ImportError): return False elif isinstance(source, str): return is_dtype_equal(target, source) @@ -622,7 +622,7 @@ def is_dtype_equal(source, target) -> bool: source = get_dtype(source) target = get_dtype(target) return source == target - except (TypeError, AttributeError): + except (TypeError, AttributeError, ImportError): # invalid comparison # object == category will hit this diff --git a/pandas/tests/dtypes/test_common.py b/pandas/tests/dtypes/test_common.py index be5cb81506efd..7f1bcecc31d26 100644 --- a/pandas/tests/dtypes/test_common.py +++ b/pandas/tests/dtypes/test_common.py @@ -115,6 +115,7 @@ def test_period_dtype(self, dtype): "float": np.dtype(np.float64), "object": np.dtype(object), "category": com.pandas_dtype("category"), + "string": pd.StringDtype(), } @@ -128,6 +129,12 @@ def test_dtype_equal(name1, dtype1, name2, dtype2): assert not com.is_dtype_equal(dtype1, dtype2) +@pytest.mark.parametrize("name,dtype", list(dtypes.items()), ids=lambda x: str(x)) +def test_pyarrow_string_import_error(name, dtype): + # GH-44276 + assert not com.is_dtype_equal(dtype, "string[pyarrow]") + + @pytest.mark.parametrize( "dtype1,dtype2", [
- [x] closes #44276 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry Added instance to check string preventing import error
https://api.github.com/repos/pandas-dev/pandas/pulls/44327
2021-11-05T16:56:31Z
2021-12-15T07:52:51Z
2021-12-15T07:52:50Z
2021-12-15T08:27:03Z
BUG: closes #44312: fixes unwanted TypeError with nullable nested metadata in json_normalize
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 4d0dee01f05c1..17993b8712019 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -569,6 +569,7 @@ I/O - Bug in :func:`read_csv`, changed exception class when expecting a file path name or file-like object from ``OSError`` to ``TypeError`` (:issue:`43366`) - Bug in :func:`read_json` not handling non-numpy dtypes correctly (especially ``category``) (:issue:`21892`, :issue:`33205`) - Bug in :func:`json_normalize` where multi-character ``sep`` parameter is incorrectly prefixed to every key (:issue:`43831`) +- Bug in :func:`json_normalize` where reading data with missing multi-level metadata would not respect errors="ignore" (:issue:`44312`) - Bug in :func:`read_csv` with :code:`float_precision="round_trip"` which did not skip initial/trailing whitespace (:issue:`43713`) - Bug in dumping/loading a :class:`DataFrame` with ``yaml.dump(frame)`` (:issue:`42748`) - diff --git a/pandas/io/json/_normalize.py b/pandas/io/json/_normalize.py index 90fd5d077d031..2c2c127394fb6 100644 --- a/pandas/io/json/_normalize.py +++ b/pandas/io/json/_normalize.py @@ -389,6 +389,8 @@ def _pull_field( try: if isinstance(spec, list): for field in spec: + if result is None: + raise KeyError(field) result = result[field] else: result = result[spec] diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index a2b90f607e918..272a4aa6723dd 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -634,6 +634,33 @@ def test_missing_meta(self, missing_metadata): expected = DataFrame(ex_data, columns=columns) tm.assert_frame_equal(result, expected) + def test_missing_nested_meta(self): + # GH44312 + # If errors="ignore" and nested metadata is null, we should return nan + data = {"meta": "foo", "nested_meta": None, "value": [{"rec": 1}, {"rec": 2}]} + result = json_normalize( + data, + record_path="value", + meta=["meta", ["nested_meta", "leaf"]], + errors="ignore", + ) + ex_data = [[1, "foo", np.nan], [2, "foo", np.nan]] + columns = ["rec", "meta", "nested_meta.leaf"] + expected = DataFrame(ex_data, columns=columns).astype( + {"nested_meta.leaf": object} + ) + tm.assert_frame_equal(result, expected) + + # If errors="raise" and nested metadata is null, we should raise with the + # key of the first missing level + with pytest.raises(KeyError, match="'leaf' not found"): + json_normalize( + data, + record_path="value", + meta=["meta", ["nested_meta", "leaf"]], + errors="raise", + ) + def test_missing_meta_multilevel_record_path_errors_raise(self, missing_metadata): # GH41876 # Ensure errors='raise' works as intended even when a record_path of length
- [x] closes #44312 Fixes TypeError crash in json_normalize when using errors="ignore" and extracting nullable nested metadata.
https://api.github.com/repos/pandas-dev/pandas/pulls/44325
2021-11-05T14:40:05Z
2021-11-14T02:34:45Z
2021-11-14T02:34:45Z
2021-11-14T02:34:49Z
DOC: remove note about groupby.apply side-effect
diff --git a/pandas/core/groupby/groupby.py b/pandas/core/groupby/groupby.py index ac3808d9ee590..00c4d2778e545 100644 --- a/pandas/core/groupby/groupby.py +++ b/pandas/core/groupby/groupby.py @@ -163,11 +163,6 @@ class providing the base-class of operations. Notes ----- - In the current implementation ``apply`` calls ``func`` twice on the - first group to decide whether it can take a fast or slow code - path. This can lead to unexpected behavior if ``func`` has - side-effects, as they will take effect twice for the first - group. .. versionchanged:: 1.3.0
The described behavior has been fixed in 0.25 - [x] closes #44318 - [ ] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry, _comment:_ wouldn't say this is applicable here
https://api.github.com/repos/pandas-dev/pandas/pulls/44321
2021-11-05T11:04:47Z
2021-11-05T13:04:15Z
2021-11-05T13:04:15Z
2021-11-05T13:20:28Z
Backport PR #44315 on branch 1.3.x (Pin aiobotocore to lower than 2.0 )
diff --git a/ci/deps/actions-37-db.yaml b/ci/deps/actions-37-db.yaml index 73d3bf2dcc70a..ed6086832cf71 100644 --- a/ci/deps/actions-37-db.yaml +++ b/ci/deps/actions-37-db.yaml @@ -12,6 +12,7 @@ dependencies: - pytest-cov>=2.10.1 # this is only needed in the coverage build, ref: GH 35737 # pandas dependencies + - aiobotocore<2.0.0 - beautifulsoup4 - botocore>=1.11 - dask diff --git a/ci/deps/actions-39.yaml b/ci/deps/actions-39.yaml index 5ca449d537df3..c9249b272829f 100644 --- a/ci/deps/actions-39.yaml +++ b/ci/deps/actions-39.yaml @@ -12,6 +12,7 @@ dependencies: - hypothesis>=3.58.0 # pandas dependencies + - aiobotocore<2.0.0 - beautifulsoup4 - bottleneck - fsspec>=0.8.0, <2021.6.0 diff --git a/ci/deps/azure-windows-38.yaml b/ci/deps/azure-windows-38.yaml index 52a5de70f85dc..e455563ef9e9c 100644 --- a/ci/deps/azure-windows-38.yaml +++ b/ci/deps/azure-windows-38.yaml @@ -13,6 +13,7 @@ dependencies: - pytest-azurepipelines # pandas dependencies + - aiobotocore<2.0.0 - blosc - bottleneck - fastparquet>=0.4.0 diff --git a/environment.yml b/environment.yml index 13d022c3f0e72..2843d5302b404 100644 --- a/environment.yml +++ b/environment.yml @@ -106,7 +106,7 @@ dependencies: - pyqt>=5.9.2 # pandas.read_clipboard - pytables>=3.5.1 # pandas.read_hdf, DataFrame.to_hdf - s3fs>=0.4.0 # file IO when using 's3://...' path - - aiobotocore + - aiobotocore<2.0.0 - fsspec>=0.7.4, <2021.6.0 # for generic remote file operations - gcsfs>=0.6.0 # file IO when using 'gcs://...' path - sqlalchemy # pandas.read_sql, DataFrame.to_sql diff --git a/requirements-dev.txt b/requirements-dev.txt index 0341f645e595b..c801aba57b201 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -70,7 +70,7 @@ python-snappy pyqt5>=5.9.2 tables>=3.5.1 s3fs>=0.4.0 -aiobotocore +aiobotocore<2.0.0 fsspec>=0.7.4, <2021.6.0 gcsfs>=0.6.0 sqlalchemy
(cherry picked from commit 28c7f7628dd6b862e1eed29ff71e2e8363ca1eee) - [x] xref #44315
https://api.github.com/repos/pandas-dev/pandas/pulls/44319
2021-11-05T08:31:32Z
2021-11-09T09:21:59Z
2021-11-09T09:21:59Z
2021-11-13T19:32:27Z
ENH: Add decimal parameter to read_excel
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 1b3be65ee66f2..a1bb3261d0445 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -182,6 +182,7 @@ Other enhancements - Added :meth:`.ExponentialMovingWindow.sum` (:issue:`13297`) - :meth:`Series.str.split` now supports a ``regex`` argument that explicitly specifies whether the pattern is a regular expression. Default is ``None`` (:issue:`43563`, :issue:`32835`, :issue:`25549`) - :meth:`DataFrame.dropna` now accepts a single label as ``subset`` along with array-like (:issue:`41021`) +- :meth:`read_excel` now accepts a ``decimal`` argument that allow the user to specify the decimal point when parsing string columns to numeric (:issue:`14403`) - :meth:`.GroupBy.mean` now supports `Numba <http://numba.pydata.org/>`_ execution with the ``engine`` keyword (:issue:`43731`) .. --------------------------------------------------------------------------- diff --git a/pandas/io/excel/_base.py b/pandas/io/excel/_base.py index 5dd85707220ba..e543c9161a26e 100644 --- a/pandas/io/excel/_base.py +++ b/pandas/io/excel/_base.py @@ -234,6 +234,14 @@ this parameter is only necessary for columns stored as TEXT in Excel, any numeric columns will automatically be parsed, regardless of display format. +decimal : str, default '.' + Character to recognize as decimal point for parsing string columns to numeric. + Note that this parameter is only necessary for columns stored as TEXT in Excel, + any numeric columns will automatically be parsed, regardless of display + format.(e.g. use ',' for European data). + + .. versionadded:: 1.4.0 + comment : str, default None Comments out remainder of line. Pass a character or characters to this argument to indicate comments in the input file. Any data between the @@ -356,6 +364,7 @@ def read_excel( parse_dates=False, date_parser=None, thousands=None, + decimal=".", comment=None, skipfooter=0, convert_float=None, @@ -394,6 +403,7 @@ def read_excel( parse_dates=parse_dates, date_parser=date_parser, thousands=thousands, + decimal=decimal, comment=comment, skipfooter=skipfooter, convert_float=convert_float, @@ -498,6 +508,7 @@ def parse( parse_dates=False, date_parser=None, thousands=None, + decimal=".", comment=None, skipfooter=0, convert_float=None, @@ -624,6 +635,7 @@ def parse( parse_dates=parse_dates, date_parser=date_parser, thousands=thousands, + decimal=decimal, comment=comment, skipfooter=skipfooter, usecols=usecols, diff --git a/pandas/tests/io/data/excel/test_decimal.ods b/pandas/tests/io/data/excel/test_decimal.ods new file mode 100644 index 0000000000000..308a851809dde Binary files /dev/null and b/pandas/tests/io/data/excel/test_decimal.ods differ diff --git a/pandas/tests/io/data/excel/test_decimal.xls b/pandas/tests/io/data/excel/test_decimal.xls new file mode 100644 index 0000000000000..ce34667873cb5 Binary files /dev/null and b/pandas/tests/io/data/excel/test_decimal.xls differ diff --git a/pandas/tests/io/data/excel/test_decimal.xlsb b/pandas/tests/io/data/excel/test_decimal.xlsb new file mode 100644 index 0000000000000..addfd1480a190 Binary files /dev/null and b/pandas/tests/io/data/excel/test_decimal.xlsb differ diff --git a/pandas/tests/io/data/excel/test_decimal.xlsm b/pandas/tests/io/data/excel/test_decimal.xlsm new file mode 100644 index 0000000000000..7dd6b1e7da036 Binary files /dev/null and b/pandas/tests/io/data/excel/test_decimal.xlsm differ diff --git a/pandas/tests/io/data/excel/test_decimal.xlsx b/pandas/tests/io/data/excel/test_decimal.xlsx new file mode 100644 index 0000000000000..0cedf3899a566 Binary files /dev/null and b/pandas/tests/io/data/excel/test_decimal.xlsx differ diff --git a/pandas/tests/io/excel/test_readers.py b/pandas/tests/io/excel/test_readers.py index 657e64bd01809..60302928420d0 100644 --- a/pandas/tests/io/excel/test_readers.py +++ b/pandas/tests/io/excel/test_readers.py @@ -1289,6 +1289,19 @@ def test_ignore_chartsheets_by_int(self, request, read_ext): ): pd.read_excel("chartsheet" + read_ext, sheet_name=1) + def test_euro_decimal_format(self, request, read_ext): + # copied from read_csv + result = pd.read_excel("test_decimal" + read_ext, decimal=",", skiprows=1) + expected = DataFrame( + [ + [1, 1521.1541, 187101.9543, "ABC", "poi", 4.738797819], + [2, 121.12, 14897.76, "DEF", "uyt", 0.377320872], + [3, 878.158, 108013.434, "GHI", "rez", 2.735694704], + ], + columns=["Id", "Number1", "Number2", "Text1", "Text2", "Number3"], + ) + tm.assert_frame_equal(result, expected) + class TestExcelFileRead: @pytest.fixture(autouse=True)
- [ ] closes #14403 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/44317
2021-11-05T02:03:51Z
2021-11-05T13:05:22Z
2021-11-05T13:05:22Z
2022-12-28T06:34:43Z
BUG: failure to cast all-int floating dtypes when setting into int dtypes
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 3f0744abd1d59..9ad53cd189348 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -535,6 +535,7 @@ Indexing - Bug in :meth:`DataFrame.nlargest` and :meth:`Series.nlargest` where sorted result did not count indexes containing ``np.nan`` (:issue:`28984`) - Bug in indexing on a non-unique object-dtype :class:`Index` with an NA scalar (e.g. ``np.nan``) (:issue:`43711`) - Bug in :meth:`DataFrame.__setitem__` incorrectly writing into an existing column's array rather than setting a new array when the new dtype and the old dtype match (:issue:`43406`) +- Bug in setting floating-dtype values into a :class:`Series` with integer dtype failing to set inplace when those values can be losslessly converted to integers (:issue:`44316`) - Bug in :meth:`Series.__setitem__` with object dtype when setting an array with matching size and dtype='datetime64[ns]' or dtype='timedelta64[ns]' incorrectly converting the datetime/timedeltas to integers (:issue:`43868`) - Bug in :meth:`DataFrame.sort_index` where ``ignore_index=True`` was not being respected when the index was already sorted (:issue:`43591`) - Bug in :meth:`Index.get_indexer_non_unique` when index contains multiple ``np.datetime64("NaT")`` and ``np.timedelta64("NaT")`` (:issue:`43869`) diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 261359767cf60..432074a8dd699 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -2205,6 +2205,14 @@ def can_hold_element(arr: ArrayLike, element: Any) -> bool: if tipo.kind not in ["i", "u"]: if is_float(element) and element.is_integer(): return True + + if isinstance(element, np.ndarray) and element.dtype.kind == "f": + # If all can be losslessly cast to integers, then we can hold them + # We do something similar in putmask_smart + casted = element.astype(dtype) + comp = casted == element + return comp.all() + # Anything other than integer we cannot hold return False elif dtype.itemsize < tipo.itemsize: diff --git a/pandas/core/indexes/numeric.py b/pandas/core/indexes/numeric.py index 40aa70a2ada2f..4d8c411478993 100644 --- a/pandas/core/indexes/numeric.py +++ b/pandas/core/indexes/numeric.py @@ -425,6 +425,18 @@ def asi8(self) -> npt.NDArray[np.int64]: ) return self._values.view(self._default_dtype) + def _validate_fill_value(self, value): + # e.g. np.array([1.0]) we want np.array([1], dtype=self.dtype) + # see TestSetitemFloatNDarrayIntoIntegerSeries + super()._validate_fill_value(value) + if hasattr(value, "dtype") and is_float_dtype(value.dtype): + converted = value.astype(self.dtype) + if (converted == value).all(): + # See also: can_hold_element + return converted + raise TypeError + return value + class Int64Index(IntegerIndex): _index_descr_args = { diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 33c78f396b80b..2589015e0f0b1 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1193,6 +1193,14 @@ def where(self, other, cond) -> list[Block]: values, icond.sum(), other # type: ignore[arg-type] ) if alt is not other: + if is_list_like(other) and len(other) < len(values): + # call np.where with other to get the appropriate ValueError + np.where(~icond, values, other) + raise NotImplementedError( + "This should not be reached; call to np.where above is " + "expected to raise ValueError. Please report a bug at " + "github.com/pandas-dev/pandas" + ) result = values.copy() np.putmask(result, icond, alt) else: diff --git a/pandas/tests/dtypes/cast/test_can_hold_element.py b/pandas/tests/dtypes/cast/test_can_hold_element.py index c4776f2a1e143..3a486f795f23e 100644 --- a/pandas/tests/dtypes/cast/test_can_hold_element.py +++ b/pandas/tests/dtypes/cast/test_can_hold_element.py @@ -40,3 +40,16 @@ def test_can_hold_element_range(any_int_numpy_dtype): rng = range(10 ** 10, 10 ** 10) assert len(rng) == 0 assert can_hold_element(arr, rng) + + +def test_can_hold_element_int_values_float_ndarray(): + arr = np.array([], dtype=np.int64) + + element = np.array([1.0, 2.0]) + assert can_hold_element(arr, element) + + assert not can_hold_element(arr, element + 0.5) + + # integer but not losslessly castable to int64 + element = np.array([3, 2 ** 65], dtype=np.float64) + assert not can_hold_element(arr, element) diff --git a/pandas/tests/indexing/multiindex/test_setitem.py b/pandas/tests/indexing/multiindex/test_setitem.py index 5d0aeba4aebbc..b97aaf6c551d8 100644 --- a/pandas/tests/indexing/multiindex/test_setitem.py +++ b/pandas/tests/indexing/multiindex/test_setitem.py @@ -196,16 +196,35 @@ def test_multiindex_assignment(self): df.loc[4, "d"] = arr tm.assert_series_equal(df.loc[4, "d"], Series(arr, index=[8, 10], name="d")) + def test_multiindex_assignment_single_dtype(self, using_array_manager): + # GH3777 part 2b # single dtype + arr = np.array([0.0, 1.0]) + df = DataFrame( np.random.randint(5, 10, size=9).reshape(3, 3), columns=list("abc"), index=[[4, 4, 8], [8, 10, 12]], + dtype=np.int64, ) + view = df["c"].iloc[:2].values + # arr can be losslessly cast to int, so this setitem is inplace df.loc[4, "c"] = arr - exp = Series(arr, index=[8, 10], name="c", dtype="float64") - tm.assert_series_equal(df.loc[4, "c"], exp) + exp = Series(arr, index=[8, 10], name="c", dtype="int64") + result = df.loc[4, "c"] + tm.assert_series_equal(result, exp) + if not using_array_manager: + # FIXME(ArrayManager): this correctly preserves dtype, + # but incorrectly is not inplace. + # extra check for inplace-ness + tm.assert_numpy_array_equal(view, exp.values) + + # arr + 0.5 cannot be cast losslessly to int, so we upcast + df.loc[4, "c"] = arr + 0.5 + result = df.loc[4, "c"] + exp = exp + 0.5 + tm.assert_series_equal(result, exp) # scalar ok df.loc[4, "c"] = 10 diff --git a/pandas/tests/indexing/test_iloc.py b/pandas/tests/indexing/test_iloc.py index 046d349b92f3f..d446d606d726f 100644 --- a/pandas/tests/indexing/test_iloc.py +++ b/pandas/tests/indexing/test_iloc.py @@ -515,9 +515,18 @@ def test_iloc_setitem_frame_duplicate_columns_multiple_blocks( # but on a DataFrame with multiple blocks df = DataFrame([[0, 1], [2, 3]], columns=["B", "B"]) + # setting float values that can be held by existing integer arrays + # is inplace df.iloc[:, 0] = df.iloc[:, 0].astype("f8") + if not using_array_manager: + assert len(df._mgr.blocks) == 1 + + # if the assigned values cannot be held by existing integer arrays, + # we cast + df.iloc[:, 0] = df.iloc[:, 0] + 0.5 if not using_array_manager: assert len(df._mgr.blocks) == 2 + expected = df.copy() # assign back to self @@ -892,7 +901,7 @@ def test_iloc_with_boolean_operation(self): tm.assert_frame_equal(result, expected) result.iloc[[False, False, True, True]] /= 2 - expected = DataFrame([[0.0, 4.0], [8.0, 12.0], [4.0, 5.0], [6.0, np.nan]]) + expected = DataFrame([[0, 4.0], [8, 12.0], [4, 5.0], [6, np.nan]]) tm.assert_frame_equal(result, expected) def test_iloc_getitem_singlerow_slice_categoricaldtype_gives_series(self): diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 4706025b70db6..ea754127b98e9 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -620,23 +620,27 @@ def test_mask_key(self, obj, key, expected, val, indexer_sli): mask[key] = True obj = obj.copy() + + if is_list_like(val) and len(val) < mask.sum(): + msg = "boolean index did not match indexed array along dimension" + with pytest.raises(IndexError, match=msg): + indexer_sli(obj)[mask] = val + return + indexer_sli(obj)[mask] = val tm.assert_series_equal(obj, expected) def test_series_where(self, obj, key, expected, val, is_inplace): - if is_list_like(val) and len(val) < len(obj): - # Series.where is not valid here - if isinstance(val, range): - return - - # FIXME: The remaining TestSetitemDT64IntoInt that go through here - # are relying on technically-incorrect behavior because Block.where - # uses np.putmask instead of expressions.where in those cases, - # which has different length-checking semantics. - mask = np.zeros(obj.shape, dtype=bool) mask[key] = True + if is_list_like(val) and len(val) < len(obj): + # Series.where is not valid here + msg = "operands could not be broadcast together with shapes" + with pytest.raises(ValueError, match=msg): + obj.where(~mask, val) + return + orig = obj obj = obj.copy() arr = obj._values @@ -1014,6 +1018,39 @@ def inplace(self): return True +@pytest.mark.parametrize( + "val", + [ + np.array([2.0, 3.0]), + np.array([2.5, 3.5]), + np.array([2 ** 65, 2 ** 65 + 1], dtype=np.float64), # all ints, but can't cast + ], +) +class TestSetitemFloatNDarrayIntoIntegerSeries(SetitemCastingEquivalents): + @pytest.fixture + def obj(self): + return Series(range(5), dtype=np.int64) + + @pytest.fixture + def key(self): + return slice(0, 2) + + @pytest.fixture + def inplace(self, val): + # NB: this condition is based on currently-harcoded "val" cases + return val[0] == 2 + + @pytest.fixture + def expected(self, val, inplace): + if inplace: + dtype = np.int64 + else: + dtype = np.float64 + res_values = np.array(range(5), dtype=dtype) + res_values[:2] = val + return Series(res_values) + + def test_setitem_int_as_positional_fallback_deprecation(): # GH#42215 deprecated falling back to positional on __setitem__ with an # int not contained in the index
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry Overlap with (but not rebased on top of) #44275
https://api.github.com/repos/pandas-dev/pandas/pulls/44316
2021-11-04T22:38:05Z
2021-11-05T20:56:22Z
2021-11-05T20:56:22Z
2021-11-05T21:07:29Z
Pin aiobotocore to lower than 2.0
diff --git a/ci/deps/actions-38-db.yaml b/ci/deps/actions-38-db.yaml index 3e959f9b7e992..7b73f43b7ba03 100644 --- a/ci/deps/actions-38-db.yaml +++ b/ci/deps/actions-38-db.yaml @@ -12,6 +12,7 @@ dependencies: - pytest-cov>=2.10.1 # this is only needed in the coverage build, ref: GH 35737 # pandas dependencies + - aiobotocore<2.0.0 - beautifulsoup4 - botocore>=1.11 - dask diff --git a/environment.yml b/environment.yml index f5f495bed4d78..7aa7bb0842eca 100644 --- a/environment.yml +++ b/environment.yml @@ -105,7 +105,7 @@ dependencies: - pytables>=3.6.1 # pandas.read_hdf, DataFrame.to_hdf - s3fs>=0.4.0 # file IO when using 's3://...' path - - aiobotocore + - aiobotocore<2.0.0 - fsspec>=0.7.4 # for generic remote file operations - gcsfs>=0.6.0 # file IO when using 'gcs://...' path - sqlalchemy # pandas.read_sql, DataFrame.to_sql diff --git a/requirements-dev.txt b/requirements-dev.txt index b384d3b6af5b8..6247b4e5a12b1 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -69,7 +69,7 @@ pyarrow>=1.0.1 python-snappy tables>=3.6.1 s3fs>=0.4.0 -aiobotocore +aiobotocore<2.0.0 fsspec>=0.7.4 gcsfs>=0.6.0 sqlalchemy
- [x] xref #44311
https://api.github.com/repos/pandas-dev/pandas/pulls/44315
2021-11-04T22:27:32Z
2021-11-05T00:02:19Z
2021-11-05T00:02:19Z
2021-11-05T08:32:43Z
BUG: PeriodIndex in pytables
diff --git a/pandas/io/pytables.py b/pandas/io/pytables.py index f85128ea0ca4a..8c8e9b9feeb80 100644 --- a/pandas/io/pytables.py +++ b/pandas/io/pytables.py @@ -2074,6 +2074,14 @@ def convert(self, values: np.ndarray, nan_rep, encoding: str, errors: str): factory: type[Index] | type[DatetimeIndex] = Index if is_datetime64_dtype(values.dtype) or is_datetime64tz_dtype(values.dtype): factory = DatetimeIndex + elif values.dtype == "i8" and "freq" in kwargs: + # PeriodIndex data is stored as i8 + # error: Incompatible types in assignment (expression has type + # "Callable[[Any, KwArg(Any)], PeriodIndex]", variable has type + # "Union[Type[Index], Type[DatetimeIndex]]") + factory = lambda x, **kwds: PeriodIndex( # type: ignore[assignment] + ordinal=x, **kwds + ) # making an Index instance could throw a number of different errors try: diff --git a/pandas/tests/io/pytables/test_put.py b/pandas/tests/io/pytables/test_put.py index 3707079d03d64..f4b70bc6f238a 100644 --- a/pandas/tests/io/pytables/test_put.py +++ b/pandas/tests/io/pytables/test_put.py @@ -243,10 +243,8 @@ def check(format, index): check("table", index) check("fixed", index) - # period index currently broken for table - # seee GH7796 FIXME check("fixed", tm.makePeriodIndex) - # check('table',tm.makePeriodIndex) + check("table", tm.makePeriodIndex) # GH#7796 # unicode index = tm.makeUnicodeIndex
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry I've ONLY checked that the edit here fixes the commented-out test, not sure if thats sufficient to close #7796
https://api.github.com/repos/pandas-dev/pandas/pulls/44314
2021-11-04T21:29:29Z
2021-11-06T19:43:42Z
2021-11-06T19:43:41Z
2021-11-06T19:45:02Z
CLN/TYP: address TODOs, ignores
diff --git a/pandas/_libs/tslibs/dtypes.pyi b/pandas/_libs/tslibs/dtypes.pyi index 9dbf9d082d8cc..8c510b05de4ce 100644 --- a/pandas/_libs/tslibs/dtypes.pyi +++ b/pandas/_libs/tslibs/dtypes.pyi @@ -14,6 +14,8 @@ class PeriodDtypeBase: def date_offset(self) -> BaseOffset: ... @classmethod def from_date_offset(cls, offset: BaseOffset) -> PeriodDtypeBase: ... + @property + def resolution(self) -> Resolution: ... class FreqGroup(Enum): FR_ANN: int = ... diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 46b505e7384b4..2e2880cced85a 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -1012,10 +1012,8 @@ def factorize(self, na_sentinel: int = -1) -> tuple[np.ndarray, ExtensionArray]: arr, na_sentinel=na_sentinel, na_value=na_value ) - uniques = self._from_factorized(uniques, self) - # error: Incompatible return value type (got "Tuple[ndarray, ndarray]", - # expected "Tuple[ndarray, ExtensionArray]") - return codes, uniques # type: ignore[return-value] + uniques_ea = self._from_factorized(uniques, self) + return codes, uniques_ea _extension_array_shared_docs[ "repeat" diff --git a/pandas/core/arrays/masked.py b/pandas/core/arrays/masked.py index 0247cd717edec..b11b11ded2f22 100644 --- a/pandas/core/arrays/masked.py +++ b/pandas/core/arrays/masked.py @@ -574,14 +574,8 @@ def factorize(self, na_sentinel: int = -1) -> tuple[np.ndarray, ExtensionArray]: # the hashtables don't handle all different types of bits uniques = uniques.astype(self.dtype.numpy_dtype, copy=False) - # error: Incompatible types in assignment (expression has type - # "BaseMaskedArray", variable has type "ndarray") - uniques = type(self)( # type: ignore[assignment] - uniques, np.zeros(len(uniques), dtype=bool) - ) - # error: Incompatible return value type (got "Tuple[ndarray, ndarray]", - # expected "Tuple[ndarray, ExtensionArray]") - return codes, uniques # type: ignore[return-value] + uniques_ea = type(self)(uniques, np.zeros(len(uniques), dtype=bool)) + return codes, uniques_ea def value_counts(self, dropna: bool = True) -> Series: """ diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index 16512305e07ec..261359767cf60 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1792,6 +1792,7 @@ def ensure_nanosecond_dtype(dtype: DtypeObj) -> DtypeObj: return dtype +# TODO: overload to clarify that if all types are np.dtype then result is np.dtype def find_common_type(types: list[DtypeObj]) -> DtypeObj: """ Find a common data type among the given dtypes. diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index e80a88826e4ed..fd5b5bb7396af 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -151,6 +151,7 @@ class PeriodIndex(DatetimeIndexOpsMixin): _data: PeriodArray freq: BaseOffset + dtype: PeriodDtype _data_cls = PeriodArray _engine_type = libindex.PeriodEngine @@ -434,9 +435,7 @@ def get_loc(self, key, method=None, tolerance=None): # TODO: pass if method is not None, like DTI does? raise KeyError(key) from err - # error: Item "ExtensionDtype"/"dtype[Any]" of "Union[dtype[Any], - # ExtensionDtype]" has no attribute "resolution" - if reso == self.dtype.resolution: # type: ignore[union-attr] + if reso == self.dtype.resolution: # the reso < self.dtype.resolution case goes through _get_string_slice key = Period(parsed, freq=self.freq) loc = self.get_loc(key, method=method, tolerance=tolerance) @@ -489,9 +488,7 @@ def _parsed_string_to_bounds(self, reso: Resolution, parsed: datetime): def _can_partial_date_slice(self, reso: Resolution) -> bool: assert isinstance(reso, Resolution), (type(reso), reso) # e.g. test_getitem_setitem_periodindex - # error: Item "ExtensionDtype"/"dtype[Any]" of "Union[dtype[Any], - # ExtensionDtype]" has no attribute "resolution" - return reso > self.dtype.resolution # type: ignore[union-attr] + return reso > self.dtype.resolution def period_range( diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 29edb80f473fa..fc7d2168c1c79 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -1108,8 +1108,8 @@ def as_array( arr : ndarray """ if len(self.arrays) == 0: - arr = np.empty(self.shape, dtype=float) - return arr.transpose() if transpose else arr + empty_arr = np.empty(self.shape, dtype=float) + return empty_arr.transpose() if transpose else empty_arr # We want to copy when na_value is provided to avoid # mutating the original object @@ -1129,9 +1129,7 @@ def as_array( result = np.empty(self.shape_proper, dtype=dtype) - # error: Incompatible types in assignment (expression has type "Union[ndarray, - # ExtensionArray]", variable has type "ndarray") - for i, arr in enumerate(self.arrays): # type: ignore[assignment] + for i, arr in enumerate(self.arrays): arr = arr.astype(dtype, copy=copy) result[:, i] = arr @@ -1139,6 +1137,7 @@ def as_array( result[isna(result)] = na_value return result + # FIXME: don't leave commented-out # return arr.transpose() if transpose else arr diff --git a/pandas/core/internals/base.py b/pandas/core/internals/base.py index 080796e7957a3..74d8b20332fff 100644 --- a/pandas/core/internals/base.py +++ b/pandas/core/internals/base.py @@ -157,10 +157,11 @@ class SingleDataManager(DataManager): @final @property - def array(self): + def array(self) -> ArrayLike: """ Quick access to the backing array of the Block or SingleArrayManager. """ + # error: "SingleDataManager" has no attribute "arrays"; maybe "array" return self.arrays[0] # type: ignore[attr-defined] def setitem_inplace(self, indexer, value) -> None: diff --git a/pandas/core/internals/construction.py b/pandas/core/internals/construction.py index 74388e0b2b91e..159c20382dcfb 100644 --- a/pandas/core/internals/construction.py +++ b/pandas/core/internals/construction.py @@ -617,7 +617,7 @@ def _extract_index(data) -> Index: index = None if len(data) == 0: index = Index([]) - elif len(data) > 0: + else: raw_lengths = [] indexes: list[list[Hashable] | Index] = [] @@ -641,7 +641,7 @@ def _extract_index(data) -> Index: if not indexes and not raw_lengths: raise ValueError("If using all scalar values, you must pass an index") - if have_series: + elif have_series: index = union_indexes(indexes) elif have_dicts: index = union_indexes(indexes, sort=False) diff --git a/pandas/core/ops/array_ops.py b/pandas/core/ops/array_ops.py index 39c6fa13f79a4..2f695200e486b 100644 --- a/pandas/core/ops/array_ops.py +++ b/pandas/core/ops/array_ops.py @@ -5,7 +5,10 @@ import datetime from functools import partial import operator -from typing import Any +from typing import ( + Any, + cast, +) import numpy as np @@ -91,11 +94,9 @@ def _masked_arith_op(x: np.ndarray, y, op): assert isinstance(x, np.ndarray), type(x) if isinstance(y, np.ndarray): dtype = find_common_type([x.dtype, y.dtype]) - # error: Argument "dtype" to "empty" has incompatible type - # "Union[dtype, ExtensionDtype]"; expected "Union[dtype, None, type, - # _SupportsDtype, str, Tuple[Any, int], Tuple[Any, Union[int, - # Sequence[int]]], List[Any], _DtypeDict, Tuple[Any, Any]]" - result = np.empty(x.size, dtype=dtype) # type: ignore[arg-type] + # x and y are both ndarrays -> common_dtype is np.dtype + dtype = cast(np.dtype, dtype) + result = np.empty(x.size, dtype=dtype) if len(x) != len(y): raise ValueError(x.shape, y.shape) diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 813c4282e543a..9c7107ab40644 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -1000,7 +1000,7 @@ def _get_dummies_1d( codes, levels = factorize_from_iterable(Series(data)) if dtype is None: - dtype = np.uint8 + dtype = np.dtype(np.uint8) # error: Argument 1 to "dtype" has incompatible type "Union[ExtensionDtype, str, # dtype[Any], Type[object]]"; expected "Type[Any]" dtype = np.dtype(dtype) # type: ignore[arg-type] @@ -1046,9 +1046,7 @@ def get_empty_frame(data) -> DataFrame: fill_value: bool | float | int if is_integer_dtype(dtype): fill_value = 0 - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[bool]") - elif dtype == bool: # type: ignore[comparison-overlap] + elif dtype == np.dtype(bool): fill_value = False else: fill_value = 0.0 diff --git a/pandas/core/strings/accessor.py b/pandas/core/strings/accessor.py index 9f163f77a2ae8..1e27febab2af9 100644 --- a/pandas/core/strings/accessor.py +++ b/pandas/core/strings/accessor.py @@ -419,7 +419,9 @@ def _get_series_list(self, others): ) @forbid_nonstring_types(["bytes", "mixed", "mixed-integer"]) - def cat(self, others=None, sep=None, na_rep=None, join="left"): + def cat( + self, others=None, sep=None, na_rep=None, join="left" + ) -> str | Series | Index: """ Concatenate strings in the Series/Index with given separator. @@ -628,30 +630,22 @@ def cat(self, others=None, sep=None, na_rep=None, join="left"): # no NaNs - can just concatenate result = cat_safe(all_cols, sep) + out: Index | Series if isinstance(self._orig, ABCIndex): # add dtype for case that result is all-NA - # error: Incompatible types in assignment (expression has type - # "Index", variable has type "ndarray") - result = Index( # type: ignore[assignment] - result, dtype=object, name=self._orig.name - ) + out = Index(result, dtype=object, name=self._orig.name) else: # Series if is_categorical_dtype(self._orig.dtype): # We need to infer the new categories. dtype = None else: dtype = self._orig.dtype - # error: Incompatible types in assignment (expression has type - # "Series", variable has type "ndarray") - result = Series( # type: ignore[assignment] + res_ser = Series( result, dtype=dtype, index=data.index, name=self._orig.name ) - # error: "ndarray" has no attribute "__finalize__" - result = result.__finalize__( # type: ignore[attr-defined] - self._orig, method="str_cat" - ) - return result + out = res_ser.__finalize__(self._orig, method="str_cat") + return out _shared_docs[ "str_split" diff --git a/pandas/core/strings/object_array.py b/pandas/core/strings/object_array.py index 3081575f50700..ba2f56c79bdfe 100644 --- a/pandas/core/strings/object_array.py +++ b/pandas/core/strings/object_array.py @@ -71,7 +71,7 @@ def _str_map( map_convert = convert and not np.all(mask) try: result = lib.map_infer_mask(arr, f, mask.view(np.uint8), map_convert) - except (TypeError, AttributeError) as e: + except (TypeError, AttributeError) as err: # Reraise the exception if callable `f` got wrong number of args. # The user may want to be warned by this, instead of getting NaN p_err = ( @@ -79,9 +79,9 @@ def _str_map( r"(?(3)required )positional arguments?" ) - if len(e.args) >= 1 and re.search(p_err, e.args[0]): + if len(err.args) >= 1 and re.search(p_err, err.args[0]): # FIXME: this should be totally avoidable - raise e + raise err def g(x): # This type of fallback behavior can be removed once diff --git a/pandas/core/tools/datetimes.py b/pandas/core/tools/datetimes.py index aca751362c915..669a39fcb3a74 100644 --- a/pandas/core/tools/datetimes.py +++ b/pandas/core/tools/datetimes.py @@ -888,11 +888,9 @@ def to_datetime( result = arg if tz is not None: if arg.tz is not None: - # error: Too many arguments for "tz_convert" of "NaTType" - result = result.tz_convert(tz) # type: ignore[call-arg] + result = arg.tz_convert(tz) else: - # error: Too many arguments for "tz_localize" of "NaTType" - result = result.tz_localize(tz) # type: ignore[call-arg] + result = arg.tz_localize(tz) elif isinstance(arg, ABCSeries): cache_array = _maybe_cache(arg, format, cache, convert_listlike) if not cache_array.empty: diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 34bcc6687e902..f6c93e6f751c8 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -934,25 +934,15 @@ def __eq__(self, other: Any) -> bool: @classmethod def get_base_missing_value(cls, dtype: np.dtype) -> int | float: - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[signedinteger[Any]]") - if dtype == np.int8: # type: ignore[comparison-overlap] + if dtype.type is np.int8: value = cls.BASE_MISSING_VALUES["int8"] - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[signedinteger[Any]]") - elif dtype == np.int16: # type: ignore[comparison-overlap] + elif dtype.type is np.int16: value = cls.BASE_MISSING_VALUES["int16"] - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[signedinteger[Any]]") - elif dtype == np.int32: # type: ignore[comparison-overlap] + elif dtype.type is np.int32: value = cls.BASE_MISSING_VALUES["int32"] - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[floating[Any]]") - elif dtype == np.float32: # type: ignore[comparison-overlap] + elif dtype.type is np.float32: value = cls.BASE_MISSING_VALUES["float32"] - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[floating[Any]]") - elif dtype == np.float64: # type: ignore[comparison-overlap] + elif dtype.type is np.float64: value = cls.BASE_MISSING_VALUES["float64"] else: raise ValueError("Unsupported dtype") @@ -2120,30 +2110,20 @@ def _dtype_to_stata_type(dtype: np.dtype, column: Series) -> int: type inserted. """ # TODO: expand to handle datetime to integer conversion - if dtype.type == np.object_: # try to coerce it to the biggest string + if dtype.type is np.object_: # try to coerce it to the biggest string # not memory efficient, what else could we # do? itemsize = max_len_string_array(ensure_object(column._values)) return max(itemsize, 1) - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[floating[Any]]") - elif dtype == np.float64: # type: ignore[comparison-overlap] + elif dtype.type is np.float64: return 255 - # Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[floating[Any]]") - elif dtype == np.float32: # type: ignore[comparison-overlap] + elif dtype.type is np.float32: return 254 - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[signedinteger[Any]]") - elif dtype == np.int32: # type: ignore[comparison-overlap] + elif dtype.type is np.int32: return 253 - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[signedinteger[Any]]") - elif dtype == np.int16: # type: ignore[comparison-overlap] + elif dtype.type is np.int16: return 252 - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[signedinteger[Any]]") - elif dtype == np.int8: # type: ignore[comparison-overlap] + elif dtype.type is np.int8: return 251 else: # pragma : no cover raise NotImplementedError(f"Data type {dtype} not supported.") @@ -2174,7 +2154,7 @@ def _dtype_to_default_stata_fmt( max_str_len = 2045 if force_strl: return "%9s" - if dtype.type == np.object_: + if dtype.type is np.object_: itemsize = max_len_string_array(ensure_object(column._values)) if itemsize > max_str_len: if dta_version >= 117: @@ -2400,11 +2380,11 @@ def _prepare_categoricals(self, data: DataFrame) -> DataFrame: # Upcast if needed so that correct missing values can be set if values.max() >= get_base_missing_value(dtype): if dtype == np.int8: - dtype = np.int16 + dtype = np.dtype(np.int16) elif dtype == np.int16: - dtype = np.int32 + dtype = np.dtype(np.int32) else: - dtype = np.float64 + dtype = np.dtype(np.float64) values = np.array(values, dtype=dtype) # Replace missing values with Stata missing value for type @@ -2624,7 +2604,7 @@ def _encode_strings(self) -> None: continue column = self.data[col] dtype = column.dtype - if dtype.type == np.object_: + if dtype.type is np.object_: inferred_dtype = infer_dtype(column, skipna=True) if not ((inferred_dtype == "string") or len(column) == 0): col = column.name @@ -2912,7 +2892,7 @@ def _dtype_to_stata_type_117(dtype: np.dtype, column: Series, force_strl: bool) # TODO: expand to handle datetime to integer conversion if force_strl: return 32768 - if dtype.type == np.object_: # try to coerce it to the biggest string + if dtype.type is np.object_: # try to coerce it to the biggest string # not memory efficient, what else could we # do? itemsize = max_len_string_array(ensure_object(column._values)) @@ -2920,25 +2900,15 @@ def _dtype_to_stata_type_117(dtype: np.dtype, column: Series, force_strl: bool) if itemsize <= 2045: return itemsize return 32768 - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[floating[Any]]") - elif dtype == np.float64: # type: ignore[comparison-overlap] + elif dtype.type is np.float64: return 65526 - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[floating[Any]]") - elif dtype == np.float32: # type: ignore[comparison-overlap] + elif dtype.type is np.float32: return 65527 - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[signedinteger[Any]]") [comparison-overlap] - elif dtype == np.int32: # type: ignore[comparison-overlap] + elif dtype.type is np.int32: return 65528 - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[signedinteger[Any]]") - elif dtype == np.int16: # type: ignore[comparison-overlap] + elif dtype.type is np.int16: return 65529 - # error: Non-overlapping equality check (left operand type: "dtype[Any]", right - # operand type: "Type[signedinteger[Any]]") - elif dtype == np.int8: # type: ignore[comparison-overlap] + elif dtype.type is np.int8: return 65530 else: # pragma : no cover raise NotImplementedError(f"Data type {dtype} not supported.") diff --git a/pandas/tests/frame/test_reductions.py b/pandas/tests/frame/test_reductions.py index 258e4e6eb0cc9..919d8ab14778e 100644 --- a/pandas/tests/frame/test_reductions.py +++ b/pandas/tests/frame/test_reductions.py @@ -1718,7 +1718,7 @@ def test_mad_nullable_integer_all_na(any_signed_int_ea_dtype): df2 = df.astype(any_signed_int_ea_dtype) # case with all-NA row/column - df2.iloc[:, 1] = pd.NA # FIXME: this doesn't operate in-place + df2.iloc[:, 1] = pd.NA # FIXME(GH#44199): this doesn't operate in-place df2.iloc[:, 1] = pd.array([pd.NA] * len(df2), dtype=any_signed_int_ea_dtype) result = df2.mad() expected = df.mad() diff --git a/pandas/tests/indexes/multi/test_setops.py b/pandas/tests/indexes/multi/test_setops.py index f43e3104c64d7..2a1fa8a015ccc 100644 --- a/pandas/tests/indexes/multi/test_setops.py +++ b/pandas/tests/indexes/multi/test_setops.py @@ -253,12 +253,14 @@ def test_union(idx, sort): the_union = idx.union(idx[:0], sort=sort) tm.assert_index_equal(the_union, idx) - # FIXME: dont leave commented-out - # won't work in python 3 - # tuples = _index.values - # result = _index[:4] | tuples[4:] - # assert result.equals(tuples) + tuples = idx.values + result = idx[:4].union(tuples[4:], sort=sort) + if sort is None: + tm.equalContents(result, idx) + else: + assert result.equals(idx) + # FIXME: don't leave commented-out # not valid for python 3 # def test_union_with_regular_index(self): # other = Index(['A', 'B', 'C']) @@ -290,11 +292,9 @@ def test_intersection(idx, sort): expected = idx[:0] assert empty.equals(expected) - # FIXME: dont leave commented-out - # can't do in python 3 - # tuples = _index.values - # result = _index & tuples - # assert result.equals(tuples) + tuples = idx.values + result = idx.intersection(tuples) + assert result.equals(idx) @pytest.mark.parametrize(
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/44308
2021-11-04T05:32:51Z
2021-11-05T09:09:57Z
2021-11-05T09:09:57Z
2021-11-05T15:54:04Z
CLN: libparsers
diff --git a/pandas/_libs/parsers.pyi b/pandas/_libs/parsers.pyi index 9e3c163fb54d9..01f5d5802ccd5 100644 --- a/pandas/_libs/parsers.pyi +++ b/pandas/_libs/parsers.pyi @@ -16,7 +16,6 @@ STR_NA_VALUES: set[str] def sanitize_objects( values: npt.NDArray[np.object_], na_values: set, - convert_empty: bool = ..., ) -> int: ... class TextReader: diff --git a/pandas/_libs/parsers.pyx b/pandas/_libs/parsers.pyx index c9f3e1f01a55c..d2975f83b97d7 100644 --- a/pandas/_libs/parsers.pyx +++ b/pandas/_libs/parsers.pyx @@ -454,7 +454,7 @@ cdef class TextReader: # usecols into TextReader. self.usecols = usecols - # XXX + # TODO: XXX? if skipfooter > 0: self.parser.on_bad_lines = SKIP @@ -842,7 +842,7 @@ cdef class TextReader: cdef _read_rows(self, rows, bint trim): cdef: int64_t buffered_lines - int64_t irows, footer = 0 + int64_t irows self._start_clock() @@ -866,16 +866,13 @@ cdef class TextReader: if status < 0: raise_parser_error('Error tokenizing data', self.parser) - footer = self.skipfooter if self.parser_start >= self.parser.lines: raise StopIteration self._end_clock('Tokenization') self._start_clock() - columns = self._convert_column_data(rows=rows, - footer=footer, - upcast_na=True) + columns = self._convert_column_data(rows) self._end_clock('Type conversion') self._start_clock() if len(columns) > 0: @@ -904,10 +901,7 @@ cdef class TextReader: def remove_noconvert(self, i: int) -> None: self.noconvert.remove(i) - # TODO: upcast_na only ever False, footer never passed - def _convert_column_data( - self, rows: int | None = None, upcast_na: bool = False, footer: int = 0 - ) -> dict[int, "ArrayLike"]: + def _convert_column_data(self, rows: int | None) -> dict[int, "ArrayLike"]: cdef: int64_t i int nused @@ -925,11 +919,6 @@ cdef class TextReader: else: end = min(start + rows, self.parser.lines) - # FIXME: dont leave commented-out - # # skip footer - # if footer > 0: - # end -= footer - num_cols = -1 # Py_ssize_t cast prevents build warning for i in range(<Py_ssize_t>self.parser.lines): @@ -1031,8 +1020,7 @@ cdef class TextReader: self._free_na_set(na_hashset) # don't try to upcast EAs - try_upcast = upcast_na and na_count > 0 - if try_upcast and not is_extension_array_dtype(col_dtype): + if na_count > 0 and not is_extension_array_dtype(col_dtype): col_res = _maybe_upcast(col_res) if col_res is None: @@ -1985,18 +1973,14 @@ cdef list _maybe_encode(list values): return [x.encode('utf-8') if isinstance(x, str) else x for x in values] -# TODO: only ever called with convert_empty=False -def sanitize_objects(ndarray[object] values, set na_values, - bint convert_empty=True) -> int: +def sanitize_objects(ndarray[object] values, set na_values) -> int: """ - Convert specified values, including the given set na_values and empty - strings if convert_empty is True, to np.nan. + Convert specified values, including the given set na_values to np.nan. Parameters ---------- values : ndarray[object] na_values : set - convert_empty : bool, default True Returns ------- @@ -2013,7 +1997,7 @@ def sanitize_objects(ndarray[object] values, set na_values, for i in range(n): val = values[i] - if (convert_empty and val == '') or (val in na_values): + if val in na_values: values[i] = onan na_count += 1 elif val in memo: diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index e8248eeb07395..0ac515f8b0a79 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -1858,7 +1858,8 @@ cdef class YearOffset(SingleConstructorOffset): """ _attributes = tuple(["n", "normalize", "month"]) - # _default_month: int # FIXME: python annotation here breaks things + # FIXME(cython#4446): python annotation here gives compile-time errors + # _default_month: int cdef readonly: int month @@ -2009,7 +2010,7 @@ cdef class QuarterOffset(SingleConstructorOffset): # point. Also apply_index, is_on_offset, rule_code if # startingMonth vs month attr names are resolved - # FIXME: python annotations here breaks things + # FIXME(cython#4446): python annotation here gives compile-time errors # _default_starting_month: int # _from_name_starting_month: int diff --git a/pandas/io/parsers/base_parser.py b/pandas/io/parsers/base_parser.py index 983f7b6a20a48..8cdcc05f60266 100644 --- a/pandas/io/parsers/base_parser.py +++ b/pandas/io/parsers/base_parser.py @@ -713,13 +713,13 @@ def _infer_types(self, values, na_values, try_num_bool=True): # e.g. encountering datetime string gets ValueError # TypeError can be raised in floatify result = values - na_count = parsers.sanitize_objects(result, na_values, False) + na_count = parsers.sanitize_objects(result, na_values) else: na_count = isna(result).sum() else: result = values if values.dtype == np.object_: - na_count = parsers.sanitize_objects(values, na_values, False) + na_count = parsers.sanitize_objects(values, na_values) if result.dtype == np.object_ and try_num_bool: result, _ = libops.maybe_convert_bool(
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/44307
2021-11-04T05:30:26Z
2021-11-05T13:03:31Z
2021-11-05T13:03:30Z
2021-11-05T15:55:17Z
CLN: address TODOs
diff --git a/pandas/_libs/hashtable.pyi b/pandas/_libs/hashtable.pyi index 9c1de67a7ba2a..f4b90648a8dc8 100644 --- a/pandas/_libs/hashtable.pyi +++ b/pandas/_libs/hashtable.pyi @@ -194,21 +194,6 @@ class StringHashTable(HashTable): ... class PyObjectHashTable(HashTable): ... class IntpHashTable(HashTable): ... -def duplicated_int64( - values: np.ndarray, # const int64_t[:] values - keep: Literal["last", "first", False] = ..., -) -> npt.NDArray[np.bool_]: ... - -# TODO: Is it actually bool or is it uint8? - -def mode_int64( - values: np.ndarray, # const int64_t[:] values - dropna: bool, -) -> npt.NDArray[np.int64]: ... -def value_count_int64( - values: np.ndarray, # const int64_t[:] - dropna: bool, -) -> tuple[npt.NDArray[np.int64], npt.NDArray[np.int64]]: ... def duplicated( values: np.ndarray, keep: Literal["last", "first", False] = ..., diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index e8248eeb07395..6588b0435d6f0 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -777,7 +777,7 @@ cdef class Tick(SingleConstructorOffset): "Tick offset with `normalize=True` are not allowed." ) - # FIXME: Without making this cpdef, we get AttributeError when calling + # Note: Without making this cpdef, we get AttributeError when calling # from __mul__ cpdef Tick _next_higher_resolution(Tick self): if type(self) is Day: diff --git a/pandas/_libs/writers.pyi b/pandas/_libs/writers.pyi index c188dc2bd9048..930322fcbeb77 100644 --- a/pandas/_libs/writers.pyi +++ b/pandas/_libs/writers.pyi @@ -1,8 +1,11 @@ +from __future__ import annotations + import numpy as np -# TODO: can make this more specific +from pandas._typing import ArrayLike + def write_csv_rows( - data: list, + data: list[ArrayLike], data_index: np.ndarray, nlevels: int, cols: np.ndarray, diff --git a/pandas/_libs/writers.pyx b/pandas/_libs/writers.pyx index 46f04cf8e15b3..eac6ee4366e33 100644 --- a/pandas/_libs/writers.pyx +++ b/pandas/_libs/writers.pyx @@ -30,7 +30,7 @@ def write_csv_rows( Parameters ---------- - data : list + data : list[ArrayLike] data_index : ndarray nlevels : int cols : ndarray diff --git a/pandas/core/array_algos/putmask.py b/pandas/core/array_algos/putmask.py index ac27aaa42d151..54324bf721945 100644 --- a/pandas/core/array_algos/putmask.py +++ b/pandas/core/array_algos/putmask.py @@ -65,7 +65,7 @@ def putmask_inplace(values: ArrayLike, mask: npt.NDArray[np.bool_], value: Any) np.putmask(values, mask, value) -def putmask_smart(values: np.ndarray, mask: np.ndarray, new) -> np.ndarray: +def putmask_smart(values: np.ndarray, mask: npt.NDArray[np.bool_], new) -> np.ndarray: """ Return a new ndarray, try to preserve dtype if possible. @@ -84,12 +84,11 @@ def putmask_smart(values: np.ndarray, mask: np.ndarray, new) -> np.ndarray: See Also -------- - ndarray.putmask + np.putmask """ # we cannot use np.asarray() here as we cannot have conversions # that numpy does when numeric are mixed with strings - # n should be the length of the mask or a scalar here if not is_list_like(new): new = np.broadcast_to(new, mask.shape) @@ -139,7 +138,7 @@ def putmask_smart(values: np.ndarray, mask: np.ndarray, new) -> np.ndarray: return _putmask_preserve(values, new, mask) -def _putmask_preserve(new_values: np.ndarray, new, mask: np.ndarray): +def _putmask_preserve(new_values: np.ndarray, new, mask: npt.NDArray[np.bool_]): try: new_values[mask] = new[mask] except (IndexError, ValueError): @@ -147,7 +146,9 @@ def _putmask_preserve(new_values: np.ndarray, new, mask: np.ndarray): return new_values -def putmask_without_repeat(values: np.ndarray, mask: np.ndarray, new: Any) -> None: +def putmask_without_repeat( + values: np.ndarray, mask: npt.NDArray[np.bool_], new: Any +) -> None: """ np.putmask will truncate or repeat if `new` is a listlike with len(new) != len(values). We require an exact match. @@ -181,7 +182,9 @@ def putmask_without_repeat(values: np.ndarray, mask: np.ndarray, new: Any) -> No np.putmask(values, mask, new) -def validate_putmask(values: ArrayLike, mask: np.ndarray) -> tuple[np.ndarray, bool]: +def validate_putmask( + values: ArrayLike, mask: np.ndarray +) -> tuple[npt.NDArray[np.bool_], bool]: """ Validate mask and check if this putmask operation is a no-op. """ @@ -193,7 +196,7 @@ def validate_putmask(values: ArrayLike, mask: np.ndarray) -> tuple[np.ndarray, b return mask, noop -def extract_bool_array(mask: ArrayLike) -> np.ndarray: +def extract_bool_array(mask: ArrayLike) -> npt.NDArray[np.bool_]: """ If we have a SparseArray or BooleanArray, convert it to ndarray[bool]. """ diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 005c5f75e6cfa..e2dd5ecfde5a8 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -390,6 +390,7 @@ def fillna(self, value, downcast=None): return type(self)._simple_new(cat, name=self.name) + # TODO(2.0): remove reindex once non-unique deprecation is enforced def reindex( self, target, method=None, level=None, limit=None, tolerance=None ) -> tuple[Index, npt.NDArray[np.intp] | None]: diff --git a/pandas/tests/arithmetic/test_timedelta64.py b/pandas/tests/arithmetic/test_timedelta64.py index f0d01f8727d5a..9b757e9cacdf3 100644 --- a/pandas/tests/arithmetic/test_timedelta64.py +++ b/pandas/tests/arithmetic/test_timedelta64.py @@ -2132,7 +2132,6 @@ def test_float_series_rdiv_td64arr(self, box_with_array, names): result = ser.__rtruediv__(tdi) if box is DataFrame: - # TODO: Should we skip this case sooner or test something else? assert result is NotImplemented else: tm.assert_equal(result, expected) diff --git a/pandas/tests/arrays/categorical/test_replace.py b/pandas/tests/arrays/categorical/test_replace.py index 007c4bdea17f8..b5e1fe030ce1c 100644 --- a/pandas/tests/arrays/categorical/test_replace.py +++ b/pandas/tests/arrays/categorical/test_replace.py @@ -29,14 +29,14 @@ ([1, 2, "3"], "5", ["5", "5", 3], True), ], ) -def test_replace(to_replace, value, expected, flip_categories): +def test_replace_categorical_series(to_replace, value, expected, flip_categories): # GH 31720 stays_categorical = not isinstance(value, list) or len(pd.unique(value)) == 1 - s = pd.Series([1, 2, 3], dtype="category") - result = s.replace(to_replace, value) + ser = pd.Series([1, 2, 3], dtype="category") + result = ser.replace(to_replace, value) expected = pd.Series(expected, dtype="category") - s.replace(to_replace, value, inplace=True) + ser.replace(to_replace, value, inplace=True) if flip_categories: expected = expected.cat.set_categories(expected.cat.categories[::-1]) @@ -46,7 +46,7 @@ def test_replace(to_replace, value, expected, flip_categories): expected = pd.Series(np.asarray(expected)) tm.assert_series_equal(expected, result, check_category_order=False) - tm.assert_series_equal(expected, s, check_category_order=False) + tm.assert_series_equal(expected, ser, check_category_order=False) @pytest.mark.parametrize( @@ -59,8 +59,7 @@ def test_replace(to_replace, value, expected, flip_categories): ("b", None, ["a", None], "Categorical.categories length are different"), ], ) -def test_replace2(to_replace, value, result, expected_error_msg): - # TODO: better name +def test_replace_categorical(to_replace, value, result, expected_error_msg): # GH#26988 cat = Categorical(["a", "b"]) expected = Categorical(result) diff --git a/pandas/tests/arrays/timedeltas/test_reductions.py b/pandas/tests/arrays/timedeltas/test_reductions.py index 5f278b09dc818..9e854577f7e3c 100644 --- a/pandas/tests/arrays/timedeltas/test_reductions.py +++ b/pandas/tests/arrays/timedeltas/test_reductions.py @@ -84,19 +84,8 @@ def test_sum(self): assert isinstance(result, Timedelta) assert result == expected - # TODO: de-duplicate with test_npsum below - def test_np_sum(self): - # GH#25282 - vals = np.arange(5, dtype=np.int64).view("m8[h]").astype("m8[ns]") - arr = TimedeltaArray(vals) - result = np.sum(arr) - assert result == vals.sum() - - result = np.sum(pd.TimedeltaIndex(arr)) - assert result == vals.sum() - def test_npsum(self): - # GH#25335 np.sum should return a Timedelta, not timedelta64 + # GH#25282, GH#25335 np.sum should return a Timedelta, not timedelta64 tdi = pd.TimedeltaIndex(["3H", "3H", "2H", "5H", "4H"]) arr = tdi.array diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index bca87bb8ec2aa..53416b6a3e9db 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -174,11 +174,12 @@ def test_series_repr(self, data): assert "Decimal: " in repr(ser) -# TODO(extension) @pytest.mark.xfail( reason=( - "raising AssertionError as this is not implemented, though easy enough to do" - ) + "DecimalArray constructor raises bc _from_sequence wants Decimals, not ints." + "Easy to fix, just need to do it." + ), + raises=TypeError, ) def test_series_constructor_coerce_data_to_extension_dtype_raises(): xpr = ( diff --git a/pandas/tests/indexes/categorical/test_indexing.py b/pandas/tests/indexes/categorical/test_indexing.py index 6f8b18f449779..2297f8cf87209 100644 --- a/pandas/tests/indexes/categorical/test_indexing.py +++ b/pandas/tests/indexes/categorical/test_indexing.py @@ -300,8 +300,8 @@ def test_get_indexer_same_categories_different_order(self): class TestWhere: - def test_where(self, listlike_box_with_tuple): - klass = listlike_box_with_tuple + def test_where(self, listlike_box): + klass = listlike_box i = CategoricalIndex(list("aabbca"), categories=list("cab"), ordered=False) cond = [True] * len(i) diff --git a/pandas/tests/indexes/common.py b/pandas/tests/indexes/common.py index e34620d4caf17..33d2558613baf 100644 --- a/pandas/tests/indexes/common.py +++ b/pandas/tests/indexes/common.py @@ -375,8 +375,8 @@ def test_numpy_repeat(self, simple_index): with pytest.raises(ValueError, match=msg): np.repeat(idx, rep, axis=0) - def test_where(self, listlike_box_with_tuple, simple_index): - klass = listlike_box_with_tuple + def test_where(self, listlike_box, simple_index): + klass = listlike_box idx = simple_index if isinstance(idx, (DatetimeIndex, TimedeltaIndex)): diff --git a/pandas/tests/indexes/conftest.py b/pandas/tests/indexes/conftest.py index 2eae51c62aa0d..1e701945c79a0 100644 --- a/pandas/tests/indexes/conftest.py +++ b/pandas/tests/indexes/conftest.py @@ -33,19 +33,9 @@ def freq_sample(request): return request.param -@pytest.fixture(params=[list, np.array, array, Series]) +@pytest.fixture(params=[list, tuple, np.array, array, Series]) def listlike_box(request): """ Types that may be passed as the indexer to searchsorted. """ return request.param - - -# TODO: not clear if this _needs_ to be different from listlike_box or -# if that is just a historical artifact -@pytest.fixture(params=[list, tuple, np.array, Series]) -def listlike_box_with_tuple(request): - """ - Types that may be passed as the indexer to searchsorted. - """ - return request.param diff --git a/pandas/tests/indexes/interval/test_base.py b/pandas/tests/indexes/interval/test_base.py index 411e76ca5d8b7..5418f3a5964d9 100644 --- a/pandas/tests/indexes/interval/test_base.py +++ b/pandas/tests/indexes/interval/test_base.py @@ -43,8 +43,8 @@ def test_take(self, closed): expected = IntervalIndex.from_arrays([0, 0, 1], [1, 1, 2], closed=closed) tm.assert_index_equal(result, expected) - def test_where(self, simple_index, listlike_box_with_tuple): - klass = listlike_box_with_tuple + def test_where(self, simple_index, listlike_box): + klass = listlike_box idx = simple_index cond = [True] * len(idx) diff --git a/pandas/tests/indexes/multi/test_indexing.py b/pandas/tests/indexes/multi/test_indexing.py index 99322f474dd9e..34722ad388ae0 100644 --- a/pandas/tests/indexes/multi/test_indexing.py +++ b/pandas/tests/indexes/multi/test_indexing.py @@ -720,12 +720,12 @@ def test_where(self): with pytest.raises(NotImplementedError, match=msg): i.where(True) - def test_where_array_like(self, listlike_box_with_tuple): + def test_where_array_like(self, listlike_box): mi = MultiIndex.from_tuples([("A", 1), ("A", 2)]) cond = [False, True] msg = r"\.where is not supported for MultiIndex operations" with pytest.raises(NotImplementedError, match=msg): - mi.where(listlike_box_with_tuple(cond)) + mi.where(listlike_box(cond)) class TestContains: diff --git a/pandas/tests/indexes/numeric/test_indexing.py b/pandas/tests/indexes/numeric/test_indexing.py index cc309beef92d6..7f7239828f9cf 100644 --- a/pandas/tests/indexes/numeric/test_indexing.py +++ b/pandas/tests/indexes/numeric/test_indexing.py @@ -397,14 +397,14 @@ class TestWhere: UInt64Index(np.arange(5, dtype="uint64")), ], ) - def test_where(self, listlike_box_with_tuple, index): + def test_where(self, listlike_box, index): cond = [True] * len(index) expected = index - result = index.where(listlike_box_with_tuple(cond)) + result = index.where(listlike_box(cond)) cond = [False] + [True] * (len(index) - 1) expected = Float64Index([index._na_value] + index[1:].tolist()) - result = index.where(listlike_box_with_tuple(cond)) + result = index.where(listlike_box(cond)) tm.assert_index_equal(result, expected) def test_where_uint64(self): diff --git a/pandas/tests/indexes/period/test_indexing.py b/pandas/tests/indexes/period/test_indexing.py index 78afcf2fdc78a..dfa750bf933a0 100644 --- a/pandas/tests/indexes/period/test_indexing.py +++ b/pandas/tests/indexes/period/test_indexing.py @@ -602,16 +602,16 @@ def test_get_indexer2(self): class TestWhere: - def test_where(self, listlike_box_with_tuple): + def test_where(self, listlike_box): i = period_range("20130101", periods=5, freq="D") cond = [True] * len(i) expected = i - result = i.where(listlike_box_with_tuple(cond)) + result = i.where(listlike_box(cond)) tm.assert_index_equal(result, expected) cond = [False] + [True] * (len(i) - 1) expected = PeriodIndex([NaT] + i[1:].tolist(), freq="D") - result = i.where(listlike_box_with_tuple(cond)) + result = i.where(listlike_box(cond)) tm.assert_index_equal(result, expected) def test_where_other(self): diff --git a/pandas/tests/io/formats/style/test_html.py b/pandas/tests/io/formats/style/test_html.py index e15283e558479..fc5db59db8336 100644 --- a/pandas/tests/io/formats/style/test_html.py +++ b/pandas/tests/io/formats/style/test_html.py @@ -488,8 +488,8 @@ def test_replaced_css_class_names(styler_mi): uuid_len=0, ).set_table_styles(css_class_names=css) styler_mi.index.names = ["n1", "n2"] - styler_mi.hide_index(styler_mi.index[1:]) - styler_mi.hide_columns(styler_mi.columns[1:]) + styler_mi.hide(styler_mi.index[1:], axis=0) + styler_mi.hide(styler_mi.columns[1:], axis=1) styler_mi.applymap_index(lambda v: "color: red;", axis=0) styler_mi.applymap_index(lambda v: "color: green;", axis=1) styler_mi.applymap(lambda v: "color: blue;") @@ -611,9 +611,9 @@ def test_hiding_index_columns_multiindex_alignment(): ) df = DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=cidx) styler = Styler(df, uuid_len=0) - styler.hide_index(level=1).hide_columns(level=0) - styler.hide_index([("j0", "i1", "j2")]) - styler.hide_columns([("c0", "d1", "d2")]) + styler.hide(level=1, axis=0).hide(level=0, axis=1) + styler.hide([("j0", "i1", "j2")], axis=0) + styler.hide([("c0", "d1", "d2")], axis=1) result = styler.to_html() expected = dedent( """\ diff --git a/pandas/tests/io/formats/style/test_style.py b/pandas/tests/io/formats/style/test_style.py index 8ac0dd03c9fd6..c5e0985205c76 100644 --- a/pandas/tests/io/formats/style/test_style.py +++ b/pandas/tests/io/formats/style/test_style.py @@ -1530,7 +1530,7 @@ def test_hiding_headers_over_index_no_sparsify(): df = DataFrame(9, index=midx, columns=[0]) ctx = df.style._translate(False, False) assert len(ctx["body"]) == 6 - ctx = df.style.hide_index((1, "a"))._translate(False, False) + ctx = df.style.hide((1, "a"), axis=0)._translate(False, False) assert len(ctx["body"]) == 4 assert "row2" in ctx["body"][0][0]["class"] diff --git a/pandas/tests/io/formats/style/test_to_latex.py b/pandas/tests/io/formats/style/test_to_latex.py index 63658e9bf60d7..9c2a364b396b8 100644 --- a/pandas/tests/io/formats/style/test_to_latex.py +++ b/pandas/tests/io/formats/style/test_to_latex.py @@ -803,7 +803,7 @@ def test_css_convert_apply_index(styler, axis): def test_hide_index_latex(styler): # GH 43637 - styler.hide_index([0]) + styler.hide([0], axis=0) result = styler.to_latex() expected = dedent( """\ @@ -826,9 +826,9 @@ def test_latex_hiding_index_columns_multiindex_alignment(): ) df = DataFrame(np.arange(16).reshape(4, 4), index=midx, columns=cidx) styler = Styler(df, uuid_len=0) - styler.hide_index(level=1).hide_columns(level=0) - styler.hide_index([("i0", "i1", "i2")]) - styler.hide_columns([("c0", "c1", "c2")]) + styler.hide(level=1, axis=0).hide(level=0, axis=1) + styler.hide([("i0", "i1", "i2")], axis=0) + styler.hide([("c0", "c1", "c2")], axis=1) styler.applymap(lambda x: "color:{red};" if x == 5 else "") styler.applymap_index(lambda x: "color:{blue};" if "j" in x else "") result = styler.to_latex()
- [ ] closes #xxxx - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/44305
2021-11-03T17:06:55Z
2021-11-05T13:07:28Z
2021-11-05T13:07:28Z
2021-11-05T15:55:58Z
ENH: Implement multi-column `DataFrame.quantiles`
diff --git a/doc/source/whatsnew/v1.5.0.rst b/doc/source/whatsnew/v1.5.0.rst index a1a2149da7cf6..ce7fa940d018a 100644 --- a/doc/source/whatsnew/v1.5.0.rst +++ b/doc/source/whatsnew/v1.5.0.rst @@ -293,6 +293,7 @@ Other enhancements - :class:`Series` reducers (e.g. ``min``, ``max``, ``sum``, ``mean``) will now successfully operate when the dtype is numeric and ``numeric_only=True`` is provided; previously this would raise a ``NotImplementedError`` (:issue:`47500`) - :meth:`RangeIndex.union` now can return a :class:`RangeIndex` instead of a :class:`Int64Index` if the resulting values are equally spaced (:issue:`47557`, :issue:`43885`) - :meth:`DataFrame.compare` now accepts an argument ``result_names`` to allow the user to specify the result's names of both left and right DataFrame which are being compared. This is by default ``'self'`` and ``'other'`` (:issue:`44354`) +- :meth:`DataFrame.quantile` gained a ``method`` argument that can accept ``table`` to evaluate multi-column quantiles (:issue:`43881`) - :class:`Interval` now supports checking whether one interval is contained by another interval (:issue:`46613`) - :meth:`Series.add_suffix`, :meth:`DataFrame.add_suffix`, :meth:`Series.add_prefix` and :meth:`DataFrame.add_prefix` support a ``copy`` argument. If ``False``, the underlying data is not copied in the returned object (:issue:`47934`) - :meth:`DataFrame.set_index` now supports a ``copy`` keyword. If ``False``, the underlying data is not copied when a new :class:`DataFrame` is returned (:issue:`48043`) diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 6cfca4ebdc612..74d4184fe985d 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -83,7 +83,10 @@ npt, ) from pandas.compat._optional import import_optional_dependency -from pandas.compat.numpy import function as nv +from pandas.compat.numpy import ( + function as nv, + np_percentile_argname, +) from pandas.util._decorators import ( Appender, Substitution, @@ -11129,6 +11132,7 @@ def quantile( axis: Axis = 0, numeric_only: bool | lib.NoDefault = no_default, interpolation: QuantileInterpolation = "linear", + method: Literal["single", "table"] = "single", ) -> Series | DataFrame: """ Return values at the given quantile over requested axis. @@ -11157,6 +11161,10 @@ def quantile( * higher: `j`. * nearest: `i` or `j` whichever is nearest. * midpoint: (`i` + `j`) / 2. + method : {'single', 'table'}, default 'single' + Whether to compute quantiles per-column ('single') or over all columns + ('table'). When 'table', the only allowed interpolation methods are + 'nearest', 'lower', and 'higher'. Returns ------- @@ -11186,6 +11194,17 @@ def quantile( 0.1 1.3 3.7 0.5 2.5 55.0 + Specifying `method='table'` will compute the quantile over all columns. + + >>> df.quantile(.1, method="table", interpolation="nearest") + a 1 + b 1 + Name: 0.1, dtype: int64 + >>> df.quantile([.1, .5], method="table", interpolation="nearest") + a b + 0.1 1 1 + 0.5 3 100 + Specifying `numeric_only=False` will also compute the quantile of datetime and timedelta data. @@ -11212,13 +11231,18 @@ def quantile( # error: List item 0 has incompatible type "Union[float, Union[Union[ # ExtensionArray, ndarray[Any, Any]], Index, Series], Sequence[float]]"; # expected "float" - res_df = self.quantile( - [q], # type: ignore[list-item] + res_df = self.quantile( # type: ignore[call-overload] + [q], axis=axis, numeric_only=numeric_only, interpolation=interpolation, + method=method, ) - res = res_df.iloc[0] + if method == "single": + res = res_df.iloc[0] + else: + # cannot directly iloc over sparse arrays + res = res_df.T.iloc[:, 0] if axis == 1 and len(self) == 0: # GH#41544 try to get an appropriate dtype dtype = find_common_type(list(self.dtypes)) @@ -11246,11 +11270,47 @@ def quantile( res = self._constructor([], index=q, columns=cols, dtype=dtype) return res.__finalize__(self, method="quantile") - # error: Argument "qs" to "quantile" of "BlockManager" has incompatible type - # "Index"; expected "Float64Index" - res = data._mgr.quantile( - qs=q, axis=1, interpolation=interpolation # type: ignore[arg-type] - ) + valid_method = {"single", "table"} + if method not in valid_method: + raise ValueError( + f"Invalid method: {method}. Method must be in {valid_method}." + ) + if method == "single": + # error: Argument "qs" to "quantile" of "BlockManager" has incompatible type + # "Index"; expected "Float64Index" + res = data._mgr.quantile( + qs=q, axis=1, interpolation=interpolation # type: ignore[arg-type] + ) + elif method == "table": + valid_interpolation = {"nearest", "lower", "higher"} + if interpolation not in valid_interpolation: + raise ValueError( + f"Invalid interpolation: {interpolation}. " + f"Interpolation must be in {valid_interpolation}" + ) + # handle degenerate case + if len(data) == 0: + if data.ndim == 2: + dtype = find_common_type(list(self.dtypes)) + else: + dtype = self.dtype + return self._constructor([], index=q, columns=data.columns, dtype=dtype) + + q_idx = np.quantile( # type: ignore[call-overload] + np.arange(len(data)), q, **{np_percentile_argname: interpolation} + ) + + by = data.columns + if len(by) > 1: + keys = [data._get_label_or_level_values(x) for x in by] + indexer = lexsort_indexer(keys) + else: + by = by[0] + k = data._get_label_or_level_values(by) # type: ignore[arg-type] + indexer = nargsort(k) + + res = data._mgr.take(indexer[q_idx], verify=False) + res.axes[1] = q result = self._constructor(res) return result.__finalize__(self, method="quantile") diff --git a/pandas/tests/frame/methods/test_quantile.py b/pandas/tests/frame/methods/test_quantile.py index 16b82727fd069..14b416011b956 100644 --- a/pandas/tests/frame/methods/test_quantile.py +++ b/pandas/tests/frame/methods/test_quantile.py @@ -16,6 +16,14 @@ import pandas._testing as tm +@pytest.fixture( + params=[["linear", "single"], ["nearest", "table"]], ids=lambda x: "-".join(x) +) +def interp_method(request): + """(interpolation, method) arguments for quantile""" + return request.param + + class TestDataFrameQuantile: @pytest.mark.parametrize( "non_num_col", @@ -25,8 +33,11 @@ class TestDataFrameQuantile: [DataFrame, Series, Timestamp], ], ) - def test_numeric_only_default_false_warning(self, non_num_col): + def test_numeric_only_default_false_warning( + self, non_num_col, interp_method, request, using_array_manager + ): # GH #7308 + interpolation, method = interp_method df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}) df["C"] = non_num_col @@ -35,8 +46,14 @@ def test_numeric_only_default_false_warning(self, non_num_col): index=["A", "B"], name=0.5, ) + if interpolation == "nearest": + expected = expected.astype(np.int64) + if method == "table" and using_array_manager: + request.node.add_marker( + pytest.mark.xfail(reason="Axis name incorrectly set.") + ) with tm.assert_produces_warning(FutureWarning, match="numeric_only"): - result = df.quantile(0.5) + result = df.quantile(0.5, interpolation=interpolation, method=method) tm.assert_series_equal(result, expected) @pytest.mark.parametrize( @@ -64,66 +81,142 @@ def test_quantile_sparse(self, df, expected): tm.assert_series_equal(result, expected) - def test_quantile(self, datetime_frame): - from numpy import percentile - + def test_quantile( + self, datetime_frame, interp_method, using_array_manager, request + ): + interpolation, method = interp_method df = datetime_frame - q = df.quantile(0.1, axis=0, numeric_only=True) - assert q["A"] == percentile(df["A"], 10) - tm.assert_index_equal(q.index, df.columns) - - q = df.quantile(0.9, axis=1, numeric_only=True) - assert q["2000-01-17"] == percentile(df.loc["2000-01-17"], 90) - tm.assert_index_equal(q.index, df.index) - - # test degenerate case - q = DataFrame({"x": [], "y": []}).quantile(0.1, axis=0, numeric_only=True) + result = df.quantile( + 0.1, axis=0, numeric_only=True, interpolation=interpolation, method=method + ) + expected = Series( + [np.percentile(df[col], 10) for col in df.columns], + index=df.columns, + name=0.1, + ) + if interpolation == "linear": + # np.percentile values only comparable to linear interpolation + tm.assert_series_equal(result, expected) + else: + tm.assert_index_equal(result.index, expected.index) + request.node.add_marker( + pytest.mark.xfail( + using_array_manager, reason="Name set incorrectly for arraymanager" + ) + ) + assert result.name == expected.name + + result = df.quantile( + 0.9, axis=1, numeric_only=True, interpolation=interpolation, method=method + ) + expected = Series( + [np.percentile(df.loc[date], 90) for date in df.index], + index=df.index, + name=0.9, + ) + if interpolation == "linear": + # np.percentile values only comparable to linear interpolation + tm.assert_series_equal(result, expected) + else: + tm.assert_index_equal(result.index, expected.index) + request.node.add_marker( + pytest.mark.xfail( + using_array_manager, reason="Name set incorrectly for arraymanager" + ) + ) + assert result.name == expected.name + + def test_empty(self, interp_method): + interpolation, method = interp_method + q = DataFrame({"x": [], "y": []}).quantile( + 0.1, axis=0, numeric_only=True, interpolation=interpolation, method=method + ) assert np.isnan(q["x"]) and np.isnan(q["y"]) - # non-numeric exclusion + def test_non_numeric_exclusion(self, interp_method, request, using_array_manager): + interpolation, method = interp_method df = DataFrame({"col1": ["A", "A", "B", "B"], "col2": [1, 2, 3, 4]}) - rs = df.quantile(0.5, numeric_only=True) + rs = df.quantile( + 0.5, numeric_only=True, interpolation=interpolation, method=method + ) with tm.assert_produces_warning(FutureWarning, match="Select only valid"): xp = df.median().rename(0.5) + if interpolation == "nearest": + xp = (xp + 0.5).astype(np.int64) + if method == "table" and using_array_manager: + request.node.add_marker( + pytest.mark.xfail(reason="Axis name incorrectly set.") + ) tm.assert_series_equal(rs, xp) + def test_axis(self, interp_method, request, using_array_manager): # axis + interpolation, method = interp_method df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3]) - result = df.quantile(0.5, axis=1) + result = df.quantile(0.5, axis=1, interpolation=interpolation, method=method) expected = Series([1.5, 2.5, 3.5], index=[1, 2, 3], name=0.5) + if interpolation == "nearest": + expected = expected.astype(np.int64) + if method == "table" and using_array_manager: + request.node.add_marker( + pytest.mark.xfail(reason="Axis name incorrectly set.") + ) tm.assert_series_equal(result, expected) - result = df.quantile([0.5, 0.75], axis=1) + result = df.quantile( + [0.5, 0.75], axis=1, interpolation=interpolation, method=method + ) expected = DataFrame( {1: [1.5, 1.75], 2: [2.5, 2.75], 3: [3.5, 3.75]}, index=[0.5, 0.75] ) + if interpolation == "nearest": + expected.iloc[0, :] -= 0.5 + expected.iloc[1, :] += 0.25 + expected = expected.astype(np.int64) tm.assert_frame_equal(result, expected, check_index_type=True) + def test_axis_numeric_only_true(self, interp_method, request, using_array_manager): # We may want to break API in the future to change this # so that we exclude non-numeric along the same axis # See GH #7312 + interpolation, method = interp_method df = DataFrame([[1, 2, 3], ["a", "b", 4]]) - result = df.quantile(0.5, axis=1, numeric_only=True) + result = df.quantile( + 0.5, axis=1, numeric_only=True, interpolation=interpolation, method=method + ) expected = Series([3.0, 4.0], index=[0, 1], name=0.5) + if interpolation == "nearest": + expected = expected.astype(np.int64) + if method == "table" and using_array_manager: + request.node.add_marker( + pytest.mark.xfail(reason="Axis name incorrectly set.") + ) tm.assert_series_equal(result, expected) - def test_quantile_date_range(self): + def test_quantile_date_range(self, interp_method, request, using_array_manager): # GH 2460 - + interpolation, method = interp_method dti = pd.date_range("2016-01-01", periods=3, tz="US/Pacific") ser = Series(dti) df = DataFrame(ser) - result = df.quantile(numeric_only=False) + result = df.quantile( + numeric_only=False, interpolation=interpolation, method=method + ) expected = Series( ["2016-01-02 00:00:00"], name=0.5, dtype="datetime64[ns, US/Pacific]" ) + if method == "table" and using_array_manager: + request.node.add_marker( + pytest.mark.xfail(reason="Axis name incorrectly set.") + ) tm.assert_series_equal(result, expected) - def test_quantile_axis_mixed(self): + def test_quantile_axis_mixed(self, interp_method, request, using_array_manager): # mixed on axis=1 + interpolation, method = interp_method df = DataFrame( { "A": [1, 2, 3], @@ -132,8 +225,16 @@ def test_quantile_axis_mixed(self): "D": ["foo", "bar", "baz"], } ) - result = df.quantile(0.5, axis=1, numeric_only=True) + result = df.quantile( + 0.5, axis=1, numeric_only=True, interpolation=interpolation, method=method + ) expected = Series([1.5, 2.5, 3.5], name=0.5) + if interpolation == "nearest": + expected -= 0.5 + if method == "table" and using_array_manager: + request.node.add_marker( + pytest.mark.xfail(reason="Axis name incorrectly set.") + ) tm.assert_series_equal(result, expected) # must raise @@ -141,30 +242,44 @@ def test_quantile_axis_mixed(self): with pytest.raises(TypeError, match=msg): df.quantile(0.5, axis=1, numeric_only=False) - def test_quantile_axis_parameter(self): + def test_quantile_axis_parameter(self, interp_method, request, using_array_manager): # GH 9543/9544 - + interpolation, method = interp_method + if method == "table" and using_array_manager: + request.node.add_marker( + pytest.mark.xfail(reason="Axis name incorrectly set.") + ) df = DataFrame({"A": [1, 2, 3], "B": [2, 3, 4]}, index=[1, 2, 3]) - result = df.quantile(0.5, axis=0) + result = df.quantile(0.5, axis=0, interpolation=interpolation, method=method) expected = Series([2.0, 3.0], index=["A", "B"], name=0.5) + if interpolation == "nearest": + expected = expected.astype(np.int64) tm.assert_series_equal(result, expected) - expected = df.quantile(0.5, axis="index") + expected = df.quantile( + 0.5, axis="index", interpolation=interpolation, method=method + ) + if interpolation == "nearest": + expected = expected.astype(np.int64) tm.assert_series_equal(result, expected) - result = df.quantile(0.5, axis=1) + result = df.quantile(0.5, axis=1, interpolation=interpolation, method=method) expected = Series([1.5, 2.5, 3.5], index=[1, 2, 3], name=0.5) + if interpolation == "nearest": + expected = expected.astype(np.int64) tm.assert_series_equal(result, expected) - result = df.quantile(0.5, axis="columns") + result = df.quantile( + 0.5, axis="columns", interpolation=interpolation, method=method + ) tm.assert_series_equal(result, expected) msg = "No axis named -1 for object type DataFrame" with pytest.raises(ValueError, match=msg): - df.quantile(0.1, axis=-1) + df.quantile(0.1, axis=-1, interpolation=interpolation, method=method) msg = "No axis named column for object type DataFrame" with pytest.raises(ValueError, match=msg): df.quantile(0.1, axis="column") @@ -247,24 +362,45 @@ def test_quantile_interpolation_int(self, int_frame): assert q1["A"] == np.percentile(df["A"], 10) tm.assert_series_equal(q, q1) - def test_quantile_multi(self): + def test_quantile_multi(self, interp_method, request, using_array_manager): + interpolation, method = interp_method df = DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["a", "b", "c"]) - result = df.quantile([0.25, 0.5]) + result = df.quantile([0.25, 0.5], interpolation=interpolation, method=method) expected = DataFrame( [[1.5, 1.5, 1.5], [2.0, 2.0, 2.0]], index=[0.25, 0.5], columns=["a", "b", "c"], ) + if interpolation == "nearest": + expected = expected.astype(np.int64) + if method == "table" and using_array_manager: + request.node.add_marker( + pytest.mark.xfail(reason="Axis name incorrectly set.") + ) tm.assert_frame_equal(result, expected) - # axis = 1 - result = df.quantile([0.25, 0.5], axis=1) + def test_quantile_multi_axis_1(self, interp_method, request, using_array_manager): + interpolation, method = interp_method + df = DataFrame([[1, 1, 1], [2, 2, 2], [3, 3, 3]], columns=["a", "b", "c"]) + result = df.quantile( + [0.25, 0.5], axis=1, interpolation=interpolation, method=method + ) expected = DataFrame( - [[1.5, 1.5, 1.5], [2.0, 2.0, 2.0]], index=[0.25, 0.5], columns=[0, 1, 2] + [[1.0, 2.0, 3.0]] * 2, index=[0.25, 0.5], columns=[0, 1, 2] ) + if interpolation == "nearest": + expected = expected.astype(np.int64) + if method == "table" and using_array_manager: + request.node.add_marker( + pytest.mark.xfail(reason="Axis name incorrectly set.") + ) + tm.assert_frame_equal(result, expected) - # empty - result = DataFrame({"x": [], "y": []}).quantile([0.1, 0.9], axis=0) + def test_quantile_multi_empty(self, interp_method): + interpolation, method = interp_method + result = DataFrame({"x": [], "y": []}).quantile( + [0.1, 0.9], axis=0, interpolation=interpolation, method=method + ) expected = DataFrame( {"x": [np.nan, np.nan], "y": [np.nan, np.nan]}, index=[0.1, 0.9] ) @@ -275,7 +411,8 @@ def test_quantile_datetime(self): # exclude datetime result = df.quantile(0.5, numeric_only=True) - expected = Series([2.5], index=["b"]) + expected = Series([2.5], index=["b"], name=0.5) + tm.assert_series_equal(result, expected) # datetime result = df.quantile(0.5, numeric_only=False) @@ -327,26 +464,41 @@ def test_quantile_datetime(self): "Period[D]", ], ) - def test_quantile_dt64_empty(self, dtype): + def test_quantile_dt64_empty(self, dtype, interp_method): # GH#41544 + interpolation, method = interp_method df = DataFrame(columns=["a", "b"], dtype=dtype) - res = df.quantile(0.5, axis=1, numeric_only=False) + res = df.quantile( + 0.5, axis=1, numeric_only=False, interpolation=interpolation, method=method + ) expected = Series([], index=[], name=0.5, dtype=dtype) tm.assert_series_equal(res, expected) # no columns in result, so no dtype preservation - res = df.quantile([0.5], axis=1, numeric_only=False) + res = df.quantile( + [0.5], + axis=1, + numeric_only=False, + interpolation=interpolation, + method=method, + ) expected = DataFrame(index=[0.5]) tm.assert_frame_equal(res, expected) - def test_quantile_invalid(self, datetime_frame): + @pytest.mark.parametrize("invalid", [-1, 2, [0.5, -1], [0.5, 2]]) + def test_quantile_invalid(self, invalid, datetime_frame, interp_method): msg = "percentiles should all be in the interval \\[0, 1\\]" - for invalid in [-1, 2, [0.5, -1], [0.5, 2]]: - with pytest.raises(ValueError, match=msg): - datetime_frame.quantile(invalid) - - def test_quantile_box(self): + interpolation, method = interp_method + with pytest.raises(ValueError, match=msg): + datetime_frame.quantile(invalid, interpolation=interpolation, method=method) + + def test_quantile_box(self, interp_method, request, using_array_manager): + interpolation, method = interp_method + if method == "table" and using_array_manager: + request.node.add_marker( + pytest.mark.xfail(reason="Axis name incorrectly set.") + ) df = DataFrame( { "A": [ @@ -367,7 +519,9 @@ def test_quantile_box(self): } ) - res = df.quantile(0.5, numeric_only=False) + res = df.quantile( + 0.5, numeric_only=False, interpolation=interpolation, method=method + ) exp = Series( [ @@ -380,7 +534,9 @@ def test_quantile_box(self): ) tm.assert_series_equal(res, exp) - res = df.quantile([0.5], numeric_only=False) + res = df.quantile( + [0.5], numeric_only=False, interpolation=interpolation, method=method + ) exp = DataFrame( [ [ @@ -394,6 +550,7 @@ def test_quantile_box(self): ) tm.assert_frame_equal(res, exp) + def test_quantile_box_nat(self): # DatetimeLikeBlock may be consolidated and contain NaT in different loc df = DataFrame( { @@ -469,49 +626,73 @@ def test_quantile_box(self): ) tm.assert_frame_equal(res, exp) - def test_quantile_nan(self): - + def test_quantile_nan(self, interp_method, request, using_array_manager): + interpolation, method = interp_method + if method == "table" and using_array_manager: + request.node.add_marker( + pytest.mark.xfail(reason="Axis name incorrectly set.") + ) # GH 14357 - float block where some cols have missing values df = DataFrame({"a": np.arange(1, 6.0), "b": np.arange(1, 6.0)}) df.iloc[-1, 1] = np.nan - res = df.quantile(0.5) - exp = Series([3.0, 2.5], index=["a", "b"], name=0.5) + res = df.quantile(0.5, interpolation=interpolation, method=method) + exp = Series( + [3.0, 2.5 if interpolation == "linear" else 3.0], index=["a", "b"], name=0.5 + ) tm.assert_series_equal(res, exp) - res = df.quantile([0.5, 0.75]) - exp = DataFrame({"a": [3.0, 4.0], "b": [2.5, 3.25]}, index=[0.5, 0.75]) + res = df.quantile([0.5, 0.75], interpolation=interpolation, method=method) + exp = DataFrame( + { + "a": [3.0, 4.0], + "b": [2.5, 3.25] if interpolation == "linear" else [3.0, 4.0], + }, + index=[0.5, 0.75], + ) tm.assert_frame_equal(res, exp) - res = df.quantile(0.5, axis=1) + res = df.quantile(0.5, axis=1, interpolation=interpolation, method=method) exp = Series(np.arange(1.0, 6.0), name=0.5) tm.assert_series_equal(res, exp) - res = df.quantile([0.5, 0.75], axis=1) + res = df.quantile( + [0.5, 0.75], axis=1, interpolation=interpolation, method=method + ) exp = DataFrame([np.arange(1.0, 6.0)] * 2, index=[0.5, 0.75]) + if interpolation == "nearest": + exp.iloc[1, -1] = np.nan tm.assert_frame_equal(res, exp) # full-nan column df["b"] = np.nan - res = df.quantile(0.5) + res = df.quantile(0.5, interpolation=interpolation, method=method) exp = Series([3.0, np.nan], index=["a", "b"], name=0.5) tm.assert_series_equal(res, exp) - res = df.quantile([0.5, 0.75]) + res = df.quantile([0.5, 0.75], interpolation=interpolation, method=method) exp = DataFrame({"a": [3.0, 4.0], "b": [np.nan, np.nan]}, index=[0.5, 0.75]) tm.assert_frame_equal(res, exp) - def test_quantile_nat(self): - + def test_quantile_nat(self, interp_method, request, using_array_manager): + interpolation, method = interp_method + if method == "table" and using_array_manager: + request.node.add_marker( + pytest.mark.xfail(reason="Axis name incorrectly set.") + ) # full NaT column df = DataFrame({"a": [pd.NaT, pd.NaT, pd.NaT]}) - res = df.quantile(0.5, numeric_only=False) + res = df.quantile( + 0.5, numeric_only=False, interpolation=interpolation, method=method + ) exp = Series([pd.NaT], index=["a"], name=0.5) tm.assert_series_equal(res, exp) - res = df.quantile([0.5], numeric_only=False) + res = df.quantile( + [0.5], numeric_only=False, interpolation=interpolation, method=method + ) exp = DataFrame({"a": [pd.NaT]}, index=[0.5]) tm.assert_frame_equal(res, exp) @@ -527,50 +708,57 @@ def test_quantile_nat(self): } ) - res = df.quantile(0.5, numeric_only=False) + res = df.quantile( + 0.5, numeric_only=False, interpolation=interpolation, method=method + ) 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) + res = df.quantile( + [0.5], numeric_only=False, interpolation=interpolation, method=method + ) exp = DataFrame( [[Timestamp("2012-01-02"), pd.NaT]], index=[0.5], columns=["a", "b"] ) tm.assert_frame_equal(res, exp) - def test_quantile_empty_no_rows_floats(self): + def test_quantile_empty_no_rows_floats(self, interp_method): + interpolation, method = interp_method - # floats df = DataFrame(columns=["a", "b"], dtype="float64") - res = df.quantile(0.5) + res = df.quantile(0.5, interpolation=interpolation, method=method) exp = Series([np.nan, np.nan], index=["a", "b"], name=0.5) tm.assert_series_equal(res, exp) - res = df.quantile([0.5]) + res = df.quantile([0.5], interpolation=interpolation, method=method) exp = DataFrame([[np.nan, np.nan]], columns=["a", "b"], index=[0.5]) tm.assert_frame_equal(res, exp) - res = df.quantile(0.5, axis=1) + res = df.quantile(0.5, axis=1, interpolation=interpolation, method=method) exp = Series([], index=[], dtype="float64", name=0.5) tm.assert_series_equal(res, exp) - res = df.quantile([0.5], axis=1) + res = df.quantile([0.5], axis=1, interpolation=interpolation, method=method) exp = DataFrame(columns=[], index=[0.5]) tm.assert_frame_equal(res, exp) - def test_quantile_empty_no_rows_ints(self): - # ints + def test_quantile_empty_no_rows_ints(self, interp_method): + interpolation, method = interp_method df = DataFrame(columns=["a", "b"], dtype="int64") - res = df.quantile(0.5) + res = df.quantile(0.5, interpolation=interpolation, method=method) exp = Series([np.nan, np.nan], index=["a", "b"], name=0.5) tm.assert_series_equal(res, exp) - def test_quantile_empty_no_rows_dt64(self): + def test_quantile_empty_no_rows_dt64(self, interp_method): + interpolation, method = interp_method # datetimes df = DataFrame(columns=["a", "b"], dtype="datetime64[ns]") - res = df.quantile(0.5, numeric_only=False) + res = df.quantile( + 0.5, numeric_only=False, interpolation=interpolation, method=method + ) exp = Series( [pd.NaT, pd.NaT], index=["a", "b"], dtype="datetime64[ns]", name=0.5 ) @@ -578,43 +766,61 @@ def test_quantile_empty_no_rows_dt64(self): # Mixed dt64/dt64tz df["a"] = df["a"].dt.tz_localize("US/Central") - res = df.quantile(0.5, numeric_only=False) + res = df.quantile( + 0.5, numeric_only=False, interpolation=interpolation, method=method + ) exp = exp.astype(object) tm.assert_series_equal(res, exp) # both dt64tz df["b"] = df["b"].dt.tz_localize("US/Central") - res = df.quantile(0.5, numeric_only=False) + res = df.quantile( + 0.5, numeric_only=False, interpolation=interpolation, method=method + ) exp = exp.astype(df["b"].dtype) tm.assert_series_equal(res, exp) - def test_quantile_empty_no_columns(self): + def test_quantile_empty_no_columns(self, interp_method): # GH#23925 _get_numeric_data may drop all columns + interpolation, method = interp_method df = DataFrame(pd.date_range("1/1/18", periods=5)) df.columns.name = "captain tightpants" - result = df.quantile(0.5, numeric_only=True) + result = df.quantile( + 0.5, numeric_only=True, interpolation=interpolation, method=method + ) expected = Series([], index=[], name=0.5, dtype=np.float64) expected.index.name = "captain tightpants" tm.assert_series_equal(result, expected) - result = df.quantile([0.5], numeric_only=True) + result = df.quantile( + [0.5], numeric_only=True, interpolation=interpolation, method=method + ) expected = DataFrame([], index=[0.5], columns=[]) expected.columns.name = "captain tightpants" tm.assert_frame_equal(result, expected) - def test_quantile_item_cache(self, using_array_manager): + def test_quantile_item_cache(self, using_array_manager, interp_method): # previous behavior incorrect retained an invalid _item_cache entry + interpolation, method = interp_method df = DataFrame(np.random.randn(4, 3), columns=["A", "B", "C"]) df["D"] = df["A"] * 2 ser = df["A"] if not using_array_manager: assert len(df._mgr.blocks) == 2 - df.quantile(numeric_only=False) + df.quantile(numeric_only=False, interpolation=interpolation, method=method) ser.values[0] = 99 assert df.iloc[0, 0] == df["A"][0] + def test_invalid_method(self): + with pytest.raises(ValueError, match="Invalid method: foo"): + DataFrame(range(1)).quantile(0.5, method="foo") + + def test_table_invalid_interpolation(self): + with pytest.raises(ValueError, match="Invalid interpolation: foo"): + DataFrame(range(1)).quantile(0.5, method="table", interpolation="foo") + class TestQuantileExtensionDtype: # TODO: tests for axis=1?
Rough attempt at implementing cuDF's `DataFrame.quantiles`; shares a lot of common logic with `sort_values`, as the indexer that sorts the dataframe by all columns is ultimately what is used to grab the desired quantiles. cc @quasiben @rjzamora - [ ] closes #43881 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/44301
2021-11-03T15:08:09Z
2022-08-17T02:01:44Z
2022-08-17T02:01:44Z
2022-08-17T02:01:59Z
Detect CPORT header in SAS files
diff --git a/pandas/io/sas/sas_xport.py b/pandas/io/sas/sas_xport.py index bdb7d86a9b37e..3f9bf6662e99f 100644 --- a/pandas/io/sas/sas_xport.py +++ b/pandas/io/sas/sas_xport.py @@ -279,6 +279,12 @@ def _read_header(self): # read file header line1 = self._get_row() if line1 != _correct_line1: + if "**COMPRESSED**" in line1: + # this was created with the PROC CPORT method and can't be read + # https://documentation.sas.com/doc/en/pgmsascdc/9.4_3.5/movefile/p1bm6aqp3fw4uin1hucwh718f6kp.htm + raise ValueError( + "Header record indicates a CPORT file, which is not readable." + ) raise ValueError("Header record is not an XPORT file.") line2 = self._get_row() diff --git a/pandas/tests/io/sas/data/DEMO_PUF.cpt b/pandas/tests/io/sas/data/DEMO_PUF.cpt new file mode 100644 index 0000000000000..d74b6a70d2812 Binary files /dev/null and b/pandas/tests/io/sas/data/DEMO_PUF.cpt differ diff --git a/pandas/tests/io/sas/test_xport.py b/pandas/tests/io/sas/test_xport.py index 5d3e3b8e23cdb..9232ea8a25e4d 100644 --- a/pandas/tests/io/sas/test_xport.py +++ b/pandas/tests/io/sas/test_xport.py @@ -30,6 +30,7 @@ def setup_method(self, datapath): self.file02 = os.path.join(self.dirpath, "SSHSV1_A.xpt") self.file03 = os.path.join(self.dirpath, "DRXFCD_G.xpt") self.file04 = os.path.join(self.dirpath, "paxraw_d_short.xpt") + self.file05 = os.path.join(self.dirpath, "DEMO_PUF.cpt") with td.file_leak_context(): yield @@ -157,3 +158,11 @@ def test_truncated_float_support(self): data = read_sas(self.file04, format="xport") tm.assert_frame_equal(data.astype("int64"), data_csv) + + def test_cport_header_found_raises(self): + # Test with DEMO_PUF.cpt, the beginning of puf2019_1_fall.xpt + # from https://www.cms.gov/files/zip/puf2019.zip + # (despite the extension, it's a cpt file) + msg = "Header record indicates a CPORT file, which is not readable." + with pytest.raises(ValueError, match=msg): + read_sas(self.file05, format="xport")
Refers https://github.com/pandas-dev/pandas/issues/15825 . Doesn't fix the issue (might be unfixable), but gives a more helpful warning.
https://api.github.com/repos/pandas-dev/pandas/pulls/44300
2021-11-03T13:56:42Z
2021-11-06T19:41:49Z
2021-11-06T19:41:49Z
2021-11-07T09:50:03Z
BUG: partially-inferring pydatetime objects
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 2a718fdcf16e7..46d0ef1bb8ad5 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -475,6 +475,7 @@ Datetimelike - Bug in :meth:`date_range` and :meth:`bdate_range` do not return right bound when ``start`` = ``end`` and set is closed on one side (:issue:`43394`) - Bug in inplace addition and subtraction of :class:`DatetimeIndex` or :class:`TimedeltaIndex` with :class:`DatetimeArray` or :class:`TimedeltaArray` (:issue:`43904`) - Bug in in calling ``np.isnan``, ``np.isfinite``, or ``np.isinf`` on a timezone-aware :class:`DatetimeIndex` incorrectly raising ``TypeError`` (:issue:`43917`) +- Bug in constructing a :class:`Series` from datetime-like strings with mixed timezones incorrectly partially-inferring datetime values (:issue:`40111`) - Timedelta diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index c0ac9098ec7fc..7693f4cd13e9b 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1526,7 +1526,7 @@ def try_datetime(v: np.ndarray) -> ArrayLike: try: # GH#19671 we pass require_iso8601 to be relatively strict # when parsing strings. - dta = sequence_to_datetimes(v, require_iso8601=True, allow_object=True) + dta = sequence_to_datetimes(v, require_iso8601=True, allow_object=False) except (ValueError, TypeError): # e.g. <class 'numpy.timedelta64'> is not convertible to datetime return v.reshape(shape) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index dbf6d5627c00b..2c33284df18c5 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -1045,6 +1045,18 @@ def test_constructor_with_datetime_tz2(self): expected = Series(DatetimeIndex(["NaT", "NaT"], tz="US/Eastern")) tm.assert_series_equal(s, expected) + def test_constructor_no_partial_datetime_casting(self): + # GH#40111 + vals = [ + "nan", + Timestamp("1990-01-01"), + "2015-03-14T16:15:14.123-08:00", + "2019-03-04T21:56:32.620-07:00", + None, + ] + ser = Series(vals) + assert all(ser[i] is vals[i] for i in range(len(vals))) + @pytest.mark.parametrize("arr_dtype", [np.int64, np.float64]) @pytest.mark.parametrize("dtype", ["M8", "m8"]) @pytest.mark.parametrize("unit", ["ns", "us", "ms", "s", "h", "m", "D"]) diff --git a/pandas/tests/tools/test_to_datetime.py b/pandas/tests/tools/test_to_datetime.py index 3fa6441e47242..1f75bc11005bc 100644 --- a/pandas/tests/tools/test_to_datetime.py +++ b/pandas/tests/tools/test_to_datetime.py @@ -1123,17 +1123,32 @@ def test_iso8601_strings_mixed_offsets_with_naive(self): def test_mixed_offsets_with_native_datetime_raises(self): # GH 25978 - ser = Series( + + vals = [ + "nan", + Timestamp("1990-01-01"), + "2015-03-14T16:15:14.123-08:00", + "2019-03-04T21:56:32.620-07:00", + None, + ] + ser = Series(vals) + assert all(ser[i] is vals[i] for i in range(len(vals))) # GH#40111 + + mixed = to_datetime(ser) + expected = Series( [ - "nan", + "NaT", Timestamp("1990-01-01"), - "2015-03-14T16:15:14.123-08:00", - "2019-03-04T21:56:32.620-07:00", + Timestamp("2015-03-14T16:15:14.123-08:00").to_pydatetime(), + Timestamp("2019-03-04T21:56:32.620-07:00").to_pydatetime(), None, - ] + ], + dtype=object, ) + tm.assert_series_equal(mixed, expected) + with pytest.raises(ValueError, match="Tz-aware datetime.datetime"): - to_datetime(ser) + to_datetime(mixed) def test_non_iso_strings_with_tz_offset(self): result = to_datetime(["March 1, 2018 12:00:00+0400"] * 2)
- [x] xref #40111 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/44296
2021-11-02T23:29:00Z
2021-11-04T00:38:40Z
2021-11-04T00:38:40Z
2021-11-04T01:11:32Z
DEPR: unused 'errors' keyword in where, mask
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 2a718fdcf16e7..b58a917f5d8b4 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -397,7 +397,7 @@ Other Deprecations - Deprecated silent dropping of columns that raised a ``TypeError``, ``DataError``, and some cases of ``ValueError`` in :meth:`Series.aggregate`, :meth:`DataFrame.aggregate`, :meth:`Series.groupby.aggregate`, and :meth:`DataFrame.groupby.aggregate` when used with a list (:issue:`43740`) - Deprecated casting behavior when setting timezone-aware value(s) into a timezone-aware :class:`Series` or :class:`DataFrame` column when the timezones do not match. Previously this cast to object dtype. In a future version, the values being inserted will be converted to the series or column's existing timezone (:issue:`37605`) - Deprecated casting behavior when passing an item with mismatched-timezone to :meth:`DatetimeIndex.insert`, :meth:`DatetimeIndex.putmask`, :meth:`DatetimeIndex.where` :meth:`DatetimeIndex.fillna`, :meth:`Series.mask`, :meth:`Series.where`, :meth:`Series.fillna`, :meth:`Series.shift`, :meth:`Series.replace`, :meth:`Series.reindex` (and :class:`DataFrame` column analogues). In the past this has cast to object dtype. In a future version, these will cast the passed item to the index or series's timezone (:issue:`37605`) -- +- Deprecated the 'errors' keyword argument in :meth:`Series.where`, :meth:`DataFrame.where`, :meth:`Series.mask`, and meth:`DataFrame.mask`; in a future version the argument will be removed (:issue:`44294`) .. --------------------------------------------------------------------------- diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 5c24c57925393..9186365fc390e 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -10907,7 +10907,7 @@ def where( inplace=False, axis=None, level=None, - errors="raise", + errors=lib.no_default, try_cast=lib.no_default, ): return super().where(cond, other, inplace, axis, level, errors, try_cast) @@ -10922,7 +10922,7 @@ def mask( inplace=False, axis=None, level=None, - errors="raise", + errors=lib.no_default, try_cast=lib.no_default, ): return super().mask(cond, other, inplace, axis, level, errors, try_cast) diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f3d7d6cee5446..b53679e2b584a 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -8900,7 +8900,7 @@ def _where( inplace=False, axis=None, level=None, - errors="raise", + errors=lib.no_default, ): """ Equivalent to public method `where`, except that `other` is not @@ -8908,6 +8908,14 @@ def _where( """ inplace = validate_bool_kwarg(inplace, "inplace") + if errors is not lib.no_default: + warnings.warn( + f"The 'errors' keyword in {type(self).__name__}.where and mask is " + "deprecated and will be removed in a future version.", + FutureWarning, + stacklevel=find_stack_level(), + ) + if axis is not None: axis = self._get_axis_number(axis) @@ -9025,7 +9033,6 @@ def _where( other=other, cond=cond, align=align, - errors=errors, ) result = self._constructor(new_data) return result.__finalize__(self) @@ -9044,7 +9051,7 @@ def where( inplace=False, axis=None, level=None, - errors="raise", + errors=lib.no_default, try_cast=lib.no_default, ): """ @@ -9077,6 +9084,9 @@ def where( - 'raise' : allow exceptions to be raised. - 'ignore' : suppress exceptions. On error return original object. + .. deprecated:: 1.4.0 + Previously was silently ignored. + try_cast : bool, default None Try to cast the result back to the input type (if possible). @@ -9197,7 +9207,7 @@ def mask( inplace=False, axis=None, level=None, - errors="raise", + errors=lib.no_default, try_cast=lib.no_default, ): diff --git a/pandas/core/internals/array_manager.py b/pandas/core/internals/array_manager.py index 7f728ac9ddae5..29edb80f473fa 100644 --- a/pandas/core/internals/array_manager.py +++ b/pandas/core/internals/array_manager.py @@ -327,7 +327,7 @@ def apply_with_block(self: T, f, align_keys=None, swap_axis=True, **kwargs) -> T return type(self)(result_arrays, self._axes) - def where(self: T, other, cond, align: bool, errors: str) -> T: + def where(self: T, other, cond, align: bool) -> T: if align: align_keys = ["other", "cond"] else: @@ -339,7 +339,6 @@ def where(self: T, other, cond, align: bool, errors: str) -> T: align_keys=align_keys, other=other, cond=cond, - errors=errors, ) # TODO what is this used for? diff --git a/pandas/core/internals/blocks.py b/pandas/core/internals/blocks.py index 751cf41a09f14..33c78f396b80b 100644 --- a/pandas/core/internals/blocks.py +++ b/pandas/core/internals/blocks.py @@ -1144,7 +1144,7 @@ def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> list[Blo return [self.make_block(new_values)] - def where(self, other, cond, errors="raise") -> list[Block]: + def where(self, other, cond) -> list[Block]: """ evaluate the block; return result block(s) from the result @@ -1152,9 +1152,6 @@ def where(self, other, cond, errors="raise") -> list[Block]: ---------- other : a ndarray/object cond : np.ndarray[bool], SparseArray[bool], or BooleanArray - errors : str, {'raise', 'ignore'}, default 'raise' - - ``raise`` : allow exceptions to be raised - - ``ignore`` : suppress exceptions. On error return original object Returns ------- @@ -1163,7 +1160,6 @@ def where(self, other, cond, errors="raise") -> list[Block]: assert cond.ndim == self.ndim assert not isinstance(other, (ABCIndex, ABCSeries, ABCDataFrame)) - assert errors in ["raise", "ignore"] transpose = self.ndim == 2 values = self.values @@ -1185,9 +1181,8 @@ def where(self, other, cond, errors="raise") -> list[Block]: # or if we are a single block (ndim == 1) if not self._can_hold_element(other): # we cannot coerce, return a compat dtype - # we are explicitly ignoring errors block = self.coerce_to_target_dtype(other) - blocks = block.where(orig_other, cond, errors=errors) + blocks = block.where(orig_other, cond) return self._maybe_downcast(blocks, "infer") # error: Argument 1 to "setitem_datetimelike_compat" has incompatible type @@ -1586,7 +1581,7 @@ def shift(self, periods: int, axis: int = 0, fill_value: Any = None) -> list[Blo new_values = self.values.shift(periods=periods, fill_value=fill_value) return [self.make_block_same_class(new_values)] - def where(self, other, cond, errors="raise") -> list[Block]: + def where(self, other, cond) -> list[Block]: cond = extract_bool_array(cond) assert not isinstance(other, (ABCIndex, ABCSeries, ABCDataFrame)) @@ -1619,7 +1614,7 @@ def where(self, other, cond, errors="raise") -> list[Block]: # For now at least only support casting e.g. # Interval[int64]->Interval[float64] raise - return blk.where(other, cond, errors) + return blk.where(other, cond) raise return [self.make_block_same_class(result)] @@ -1704,7 +1699,7 @@ def putmask(self, mask, new) -> list[Block]: arr.T.putmask(mask, new) return [self] - def where(self, other, cond, errors="raise") -> list[Block]: + def where(self, other, cond) -> list[Block]: arr = self.values cond = extract_bool_array(cond) @@ -1712,7 +1707,7 @@ def where(self, other, cond, errors="raise") -> list[Block]: try: res_values = arr.T._where(cond, other).T except (ValueError, TypeError): - return Block.where(self, other, cond, errors=errors) + return Block.where(self, other, cond) nb = self.make_block_same_class(res_values) return [nb] diff --git a/pandas/core/internals/managers.py b/pandas/core/internals/managers.py index 9286238e81fc3..7db19eda0f2fb 100644 --- a/pandas/core/internals/managers.py +++ b/pandas/core/internals/managers.py @@ -315,7 +315,7 @@ def apply( out = type(self).from_blocks(result_blocks, self.axes) return out - def where(self: T, other, cond, align: bool, errors: str) -> T: + def where(self: T, other, cond, align: bool) -> T: if align: align_keys = ["other", "cond"] else: @@ -327,7 +327,6 @@ def where(self: T, other, cond, align: bool, errors: str) -> T: align_keys=align_keys, other=other, cond=cond, - errors=errors, ) def setitem(self: T, indexer, value) -> T: diff --git a/pandas/core/series.py b/pandas/core/series.py index b67f16008bb13..391169af598c2 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -5461,7 +5461,7 @@ def where( inplace=False, axis=None, level=None, - errors="raise", + errors=lib.no_default, try_cast=lib.no_default, ): return super().where(cond, other, inplace, axis, level, errors, try_cast) @@ -5476,7 +5476,7 @@ def mask( inplace=False, axis=None, level=None, - errors="raise", + errors=lib.no_default, try_cast=lib.no_default, ): return super().mask(cond, other, inplace, axis, level, errors, try_cast) diff --git a/pandas/tests/series/methods/test_fillna.py b/pandas/tests/series/methods/test_fillna.py index 2feaf4e951ab8..b132041f8afd0 100644 --- a/pandas/tests/series/methods/test_fillna.py +++ b/pandas/tests/series/methods/test_fillna.py @@ -147,15 +147,18 @@ def test_fillna_consistency(self): ) tm.assert_series_equal(result, expected) - # where (we ignore the errors=) - result = ser.where( - [True, False], Timestamp("20130101", tz="US/Eastern"), errors="ignore" - ) + msg = "The 'errors' keyword in " + with tm.assert_produces_warning(FutureWarning, match=msg): + # where (we ignore the errors=) + result = ser.where( + [True, False], Timestamp("20130101", tz="US/Eastern"), errors="ignore" + ) tm.assert_series_equal(result, expected) - result = ser.where( - [True, False], Timestamp("20130101", tz="US/Eastern"), errors="ignore" - ) + with tm.assert_produces_warning(FutureWarning, match=msg): + result = ser.where( + [True, False], Timestamp("20130101", tz="US/Eastern"), errors="ignore" + ) tm.assert_series_equal(result, expected) # with a non-datetime
- [ ] closes #xxxx - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/44294
2021-11-02T22:05:54Z
2021-11-05T00:31:48Z
2021-11-05T00:31:48Z
2021-11-05T01:01:10Z
Revert "CLN: DataFrame.__repr__"
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 2b0f7a36b6fa2..5c24c57925393 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -988,13 +988,15 @@ def __repr__(self) -> str: """ Return a string representation for a particular DataFrame. """ + buf = StringIO("") if self._info_repr(): - buf = StringIO("") self.info(buf=buf) return buf.getvalue() repr_params = fmt.get_dataframe_repr_params() - return self.to_string(**repr_params) + self.to_string(buf=buf, **repr_params) + + return buf.getvalue() def _repr_html_(self) -> str | None: """
Reverts pandas-dev/pandas#44271
https://api.github.com/repos/pandas-dev/pandas/pulls/44286
2021-11-02T08:55:05Z
2021-11-02T10:09:33Z
2021-11-02T10:09:33Z
2021-11-02T10:09:37Z
BUG: Period.__eq__ numpy scalar (#44182 (comment))
diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 337876d610c5e..f594e0a8bdafd 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1657,8 +1657,12 @@ cdef class _Period(PeriodMixin): elif other is NaT: return _nat_scalar_rules[op] elif util.is_array(other): - # in particular ndarray[object]; see test_pi_cmp_period - return np.array([PyObject_RichCompare(self, x, op) for x in other]) + # GH#44285 + if cnp.PyArray_IsZeroDim(other): + return PyObject_RichCompare(self, other.item(), op) + else: + # in particular ndarray[object]; see test_pi_cmp_period + return np.array([PyObject_RichCompare(self, x, op) for x in other]) return NotImplemented def __hash__(self): diff --git a/pandas/tests/arithmetic/test_period.py b/pandas/tests/arithmetic/test_period.py index d7cb314743e86..41c2cb2cc4f1e 100644 --- a/pandas/tests/arithmetic/test_period.py +++ b/pandas/tests/arithmetic/test_period.py @@ -189,6 +189,10 @@ def test_pi_cmp_period(self): result = idx.values.reshape(10, 2) < idx[10] tm.assert_numpy_array_equal(result, exp.reshape(10, 2)) + # Tests Period.__richcmp__ against ndarray[object, ndim=0] + result = idx < np.array(idx[10]) + tm.assert_numpy_array_equal(result, exp) + # TODO: moved from test_datetime64; de-duplicate with version below def test_parr_cmp_period_scalar2(self, box_with_array): xbox = get_expected_box(box_with_array) diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index f1b8c1cfdd39b..cd1bf21753249 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -1148,6 +1148,16 @@ def test_period_cmp_nat(self): assert not left <= right assert not left >= right + @pytest.mark.parametrize( + "zerodim_arr, expected", + ((np.array(0), False), (np.array(Period("2000-01", "M")), True)), + ) + def test_comparison_numpy_zerodim_arr(self, zerodim_arr, expected): + p = Period("2000-01", "M") + + assert (p == zerodim_arr) is expected + assert (zerodim_arr == p) is expected + class TestArithmetic: def test_sub_delta(self):
- [x] fixes https://github.com/pandas-dev/pandas/pull/44182#issuecomment-956851322 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/44285
2021-11-02T07:47:55Z
2021-11-04T00:43:43Z
2021-11-04T00:43:43Z
2021-11-04T07:33:15Z
BENCH: Add more numba rolling benchmarks
diff --git a/asv_bench/benchmarks/rolling.py b/asv_bench/benchmarks/rolling.py index 3d2273b6d7324..406b27dd37ea5 100644 --- a/asv_bench/benchmarks/rolling.py +++ b/asv_bench/benchmarks/rolling.py @@ -1,3 +1,5 @@ +import warnings + import numpy as np import pandas as pd @@ -44,29 +46,56 @@ def time_rolling(self, constructor, window, dtype, function, raw): self.roll.apply(function, raw=raw) -class Engine: +class NumbaEngine: params = ( ["DataFrame", "Series"], ["int", "float"], [np.sum, lambda x: np.sum(x) + 5], - ["cython", "numba"], ["sum", "max", "min", "median", "mean"], + [True, False], + [None, 100], ) - param_names = ["constructor", "dtype", "function", "engine", "method"] + param_names = ["constructor", "dtype", "function", "method", "parallel", "cols"] - def setup(self, constructor, dtype, function, engine, method): + def setup(self, constructor, dtype, function, method, parallel, cols): N = 10 ** 3 - arr = (100 * np.random.random(N)).astype(dtype) - self.data = getattr(pd, constructor)(arr) - - def time_rolling_apply(self, constructor, dtype, function, engine, method): - self.data.rolling(10).apply(function, raw=True, engine=engine) - - def time_expanding_apply(self, constructor, dtype, function, engine, method): - self.data.expanding().apply(function, raw=True, engine=engine) - - def time_rolling_methods(self, constructor, dtype, function, engine, method): - getattr(self.data.rolling(10), method)(engine=engine) + shape = (N, cols) if cols is not None and constructor != "Series" else N + arr = (100 * np.random.random(shape)).astype(dtype) + data = getattr(pd, constructor)(arr) + + # Warm the cache + with warnings.catch_warnings(record=True): + # Catch parallel=True not being applicable e.g. 1D data + self.roll = data.rolling(10) + self.roll.apply( + function, raw=True, engine="numba", engine_kwargs={"parallel": parallel} + ) + getattr(self.roll, method)( + engine="numba", engine_kwargs={"parallel": parallel} + ) + + self.expand = data.expanding() + self.expand.apply( + function, raw=True, engine="numba", engine_kwargs={"parallel": parallel} + ) + + def time_rolling_apply(self, constructor, dtype, function, method, parallel, col): + with warnings.catch_warnings(record=True): + self.roll.apply( + function, raw=True, engine="numba", engine_kwargs={"parallel": parallel} + ) + + def time_expanding_apply(self, constructor, dtype, function, method, parallel, col): + with warnings.catch_warnings(record=True): + self.expand.apply( + function, raw=True, engine="numba", engine_kwargs={"parallel": parallel} + ) + + def time_rolling_methods(self, constructor, dtype, function, method, parallel, col): + with warnings.catch_warnings(record=True): + getattr(self.roll, method)( + engine="numba", engine_kwargs={"parallel": parallel} + ) class ExpandingMethods:
- [x] xref #https://github.com/pandas-dev/pandas/pull/44176#issuecomment-953441787 - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/44283
2021-11-02T05:41:05Z
2021-11-05T01:00:19Z
2021-11-05T01:00:19Z
2021-11-05T02:51:10Z
BUG: Add fix for hashing timestamps with folds
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 3924191bebcfd..b93b210078a75 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -712,6 +712,7 @@ Datetimelike - Bug in :class:`DateOffset`` addition with :class:`Timestamp` where ``offset.nanoseconds`` would not be included in the result (:issue:`43968`, :issue:`36589`) - Bug in :meth:`Timestamp.fromtimestamp` not supporting the ``tz`` argument (:issue:`45083`) - Bug in :class:`DataFrame` construction from dict of :class:`Series` with mismatched index dtypes sometimes raising depending on the ordering of the passed dict (:issue:`44091`) +- Bug in :class:`Timestamp` hashing during some DST transitions caused a segmentation fault (:issue:`33931` and :issue:`40817`) - Timedelta diff --git a/pandas/_libs/tslibs/timestamps.pyx b/pandas/_libs/tslibs/timestamps.pyx index 304ac9405c5e1..03ee62e59aa3d 100644 --- a/pandas/_libs/tslibs/timestamps.pyx +++ b/pandas/_libs/tslibs/timestamps.pyx @@ -180,6 +180,8 @@ cdef class _Timestamp(ABCTimestamp): def __hash__(_Timestamp self): if self.nanosecond: return hash(self.value) + if self.fold: + return datetime.__hash__(self.replace(fold=0)) return datetime.__hash__(self) def __richcmp__(_Timestamp self, object other, int op): diff --git a/pandas/tests/frame/methods/test_reindex.py b/pandas/tests/frame/methods/test_reindex.py index bee8025275b42..b70ceea845ee8 100644 --- a/pandas/tests/frame/methods/test_reindex.py +++ b/pandas/tests/frame/methods/test_reindex.py @@ -8,6 +8,8 @@ import numpy as np import pytest +from pandas._libs.tslibs.timezones import dateutil_gettz as gettz + import pandas as pd from pandas import ( Categorical, @@ -78,6 +80,41 @@ def test_setitem_reset_index_dtypes(self): result = df2.reset_index() tm.assert_frame_equal(result, expected) + @pytest.mark.parametrize( + "timezone, year, month, day, hour", + [["America/Chicago", 2013, 11, 3, 1], ["America/Santiago", 2021, 4, 3, 23]], + ) + def test_reindex_timestamp_with_fold(self, timezone, year, month, day, hour): + # see gh-40817 + test_timezone = gettz(timezone) + transition_1 = pd.Timestamp( + year=year, + month=month, + day=day, + hour=hour, + minute=0, + fold=0, + tzinfo=test_timezone, + ) + transition_2 = pd.Timestamp( + year=year, + month=month, + day=day, + hour=hour, + minute=0, + fold=1, + tzinfo=test_timezone, + ) + df = ( + DataFrame({"index": [transition_1, transition_2], "vals": ["a", "b"]}) + .set_index("index") + .reindex(["1", "2"]) + ) + tm.assert_frame_equal( + df, + DataFrame({"index": ["1", "2"], "vals": [None, None]}).set_index("index"), + ) + class TestDataFrameSelectReindex: # These are specific reindex-based tests; other indexing tests should go in diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index 008731b13172e..4639a24d019fe 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -452,6 +452,33 @@ def test_hash_equivalent(self): stamp = Timestamp(datetime(2011, 1, 1)) assert d[stamp] == 5 + @pytest.mark.parametrize( + "timezone, year, month, day, hour", + [["America/Chicago", 2013, 11, 3, 1], ["America/Santiago", 2021, 4, 3, 23]], + ) + def test_hash_timestamp_with_fold(self, timezone, year, month, day, hour): + # see gh-33931 + test_timezone = gettz(timezone) + transition_1 = Timestamp( + year=year, + month=month, + day=day, + hour=hour, + minute=0, + fold=0, + tzinfo=test_timezone, + ) + transition_2 = Timestamp( + year=year, + month=month, + day=day, + hour=hour, + minute=0, + fold=1, + tzinfo=test_timezone, + ) + assert hash(transition_1) == hash(transition_2) + def test_tz_conversion_freq(self, tz_naive_fixture): # GH25241 with tm.assert_produces_warning(FutureWarning, match="freq"):
- [x] closes #33931, #40817 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry Edit: https://github.com/pandas-dev/pandas/issues/42305#issuecomment-895218386 This comment identifies the problem as being upstream in datetime's construction of timestamps which fails during some DST changes. The datetime hash function then being used tries to unset the fold representing the DST change, (https://github.com/python/cpython/blob/main/Lib/datetime.py#L2117). But it does this using the datetime replace function - this change fixes that problem by removing the fold prior to calling the datetime hash function using timestamp's replace function instead.
https://api.github.com/repos/pandas-dev/pandas/pulls/44282
2021-11-02T05:21:01Z
2022-01-04T00:25:24Z
2022-01-04T00:25:24Z
2022-01-04T00:30:29Z
DOC: Fix rolling apply raw default arg
diff --git a/pandas/core/window/doc.py b/pandas/core/window/doc.py index 9a645f55ffa39..2cc7962c6bd7b 100644 --- a/pandas/core/window/doc.py +++ b/pandas/core/window/doc.py @@ -59,7 +59,7 @@ def create_section_header(header: str) -> str: .. versionchanged:: 1.0.0 - raw : bool, default None + raw : bool, default False * ``False`` : passes each row or column as a Series to the function. * ``True`` : the passed function will receive ndarray
- [x] closes #44277 - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them
https://api.github.com/repos/pandas-dev/pandas/pulls/44281
2021-11-02T04:15:52Z
2021-11-05T00:59:40Z
2021-11-05T00:59:40Z
2021-11-05T02:47:16Z
CI: Revert splitting 3.10 tests
diff --git a/.github/workflows/python-dev.yml b/.github/workflows/python-dev.yml index d6647e8059306..824e7de3bde41 100644 --- a/.github/workflows/python-dev.yml +++ b/.github/workflows/python-dev.yml @@ -17,6 +17,7 @@ env: PANDAS_CI: 1 PATTERN: "not slow and not network and not clipboard" COVERAGE: true + PYTEST_TARGET: pandas jobs: build: @@ -24,12 +25,7 @@ jobs: strategy: fail-fast: false matrix: - os: [ubuntu-latest, macOS-latest] - pytest_target: ["pandas/tests/[a-h]*", "pandas/tests/[i-z]*"] - include: - # No need to split tests on windows - - os: windows-latest - pytest_target: pandas + os: [ubuntu-latest, macOS-latest, windows-latest] name: actions-310-dev timeout-minutes: 80 @@ -67,8 +63,6 @@ jobs: python -c "import pandas; pandas.show_versions();" - name: Test with pytest - env: - PYTEST_TARGET: ${{ matrix.pytest_target }} shell: bash run: | ci/run_tests.sh
Maths says this should work now. - [ ] closes #44173 - [ ] tests added / passed - [ ] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [ ] whatsnew entry Don't backport.
https://api.github.com/repos/pandas-dev/pandas/pulls/44280
2021-11-01T23:15:23Z
2021-11-06T21:30:23Z
2021-11-06T21:30:23Z
2021-11-06T22:01:14Z
CLN: missing f for f-string
diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index d8c58d1eaf4c7..c0ac9098ec7fc 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1590,7 +1590,7 @@ def try_timedelta(v: np.ndarray) -> np.ndarray: warnings.warn( f"Inferring {value.dtype} from data containing strings is deprecated " "and will be removed in a future version. To retain the old behavior " - "explicitly pass Series(data, dtype={value.dtype})", + f"explicitly pass Series(data, dtype={value.dtype})", FutureWarning, stacklevel=find_stack_level(), )
null
https://api.github.com/repos/pandas-dev/pandas/pulls/44278
2021-11-01T22:39:33Z
2021-11-01T23:27:33Z
2021-11-01T23:27:33Z
2022-04-01T01:36:45Z
BUG: broadcasting listlike values in Series.__setitem__ GH#44265
diff --git a/doc/source/whatsnew/v1.4.0.rst b/doc/source/whatsnew/v1.4.0.rst index 1b3be65ee66f2..05e7026b0faa3 100644 --- a/doc/source/whatsnew/v1.4.0.rst +++ b/doc/source/whatsnew/v1.4.0.rst @@ -540,6 +540,7 @@ Indexing - Bug in setting a scalar :class:`Interval` value into a :class:`Series` with ``IntervalDtype`` when the scalar's sides are floats and the values' sides are integers (:issue:`44201`) - Bug when setting string-backed :class:`Categorical` values that can be parsed to datetimes into a :class:`DatetimeArray` or :class:`Series` or :class:`DataFrame` column backed by :class:`DatetimeArray` failing to parse these strings (:issue:`44236`) - Bug in :meth:`Series.__setitem__` with an integer dtype other than ``int64`` setting with a ``range`` object unnecessarily upcasting to ``int64`` (:issue:`44261`) +- Bug in :meth:`Series.__setitem__` with a boolean mask indexer setting a listlike value of length 1 incorrectly broadcasting that value (:issue:`44265`) - Missing diff --git a/pandas/core/series.py b/pandas/core/series.py index 391169af598c2..02f4810bb1e6b 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1096,9 +1096,26 @@ def __setitem__(self, key, value) -> None: if com.is_bool_indexer(key): key = check_bool_indexer(self.index, key) key = np.asarray(key, dtype=bool) + + if ( + is_list_like(value) + and len(value) != len(self) + and not isinstance(value, Series) + and not is_object_dtype(self.dtype) + ): + # Series will be reindexed to have matching length inside + # _where call below + # GH#44265 + indexer = key.nonzero()[0] + self._set_values(indexer, value) + return + + # otherwise with listlike other we interpret series[mask] = other + # as series[mask] = other[mask] try: self._where(~key, value, inplace=True) except InvalidIndexError: + # test_where_dups self.iloc[key] = value return diff --git a/pandas/tests/series/indexing/test_setitem.py b/pandas/tests/series/indexing/test_setitem.py index 5f0710dfbb85a..4706025b70db6 100644 --- a/pandas/tests/series/indexing/test_setitem.py +++ b/pandas/tests/series/indexing/test_setitem.py @@ -1064,3 +1064,43 @@ def test_setitem_with_bool_indexer(): df.loc[[True, False, False], "a"] = 10 expected = DataFrame({"a": [10, 2, 3]}) tm.assert_frame_equal(df, expected) + + +@pytest.mark.parametrize("size", range(2, 6)) +@pytest.mark.parametrize( + "mask", [[True, False, False, False, False], [True, False], [False]] +) +@pytest.mark.parametrize( + "item", [2.0, np.nan, np.finfo(float).max, np.finfo(float).min] +) +# Test numpy arrays, lists and tuples as the input to be +# broadcast +@pytest.mark.parametrize( + "box", [lambda x: np.array([x]), lambda x: [x], lambda x: (x,)] +) +def test_setitem_bool_indexer_dont_broadcast_length1_values(size, mask, item, box): + # GH#44265 + # see also tests.series.indexing.test_where.test_broadcast + + selection = np.resize(mask, size) + + data = np.arange(size, dtype=float) + + ser = Series(data) + + if selection.sum() != 1: + msg = ( + "cannot set using a list-like indexer with a different " + "length than the value" + ) + with pytest.raises(ValueError, match=msg): + # GH#44265 + ser[selection] = box(item) + else: + # In this corner case setting is equivalent to setting with the unboxed + # item + ser[selection] = box(item) + + expected = Series(np.arange(size, dtype=float)) + expected[selection] = item + tm.assert_series_equal(ser, expected) diff --git a/pandas/tests/series/indexing/test_where.py b/pandas/tests/series/indexing/test_where.py index fc9d3a1e1e6ab..88b75164d2f3e 100644 --- a/pandas/tests/series/indexing/test_where.py +++ b/pandas/tests/series/indexing/test_where.py @@ -88,7 +88,7 @@ def test_where_unsafe(): s = Series(np.arange(10)) mask = s > 5 - msg = "cannot assign mismatch length to masked array" + msg = "cannot set using a list-like indexer with a different length than the value" with pytest.raises(ValueError, match=msg): s[mask] = [5, 4, 3, 2, 1] @@ -161,13 +161,10 @@ def test_where_error(): tm.assert_series_equal(s, expected) # failures - msg = "cannot assign mismatch length to masked array" + msg = "cannot set using a list-like indexer with a different length than the value" with pytest.raises(ValueError, match=msg): s[[True, False]] = [0, 2, 3] - msg = ( - "NumPy boolean array indexing assignment cannot assign 0 input " - "values to the 1 output values where the mask is true" - ) + with pytest.raises(ValueError, match=msg): s[[True, False]] = [] @@ -298,6 +295,7 @@ def test_where_setitem_invalid(): "box", [lambda x: np.array([x]), lambda x: [x], lambda x: (x,)] ) def test_broadcast(size, mask, item, box): + # GH#8801, GH#4195 selection = np.resize(mask, size) data = np.arange(size, dtype=float) @@ -309,7 +307,8 @@ def test_broadcast(size, mask, item, box): ) s = Series(data) - s[selection] = box(item) + + s[selection] = item tm.assert_series_equal(s, expected) s = Series(data)
- [x] closes #44265 - [x] tests added / passed - [x] Ensure all linting tests pass, see [here](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit) for how to run them - [x] whatsnew entry This should in turn allow us to avoid some special-casing that we do in internals/putmask_smart. Sits on top of #44261
https://api.github.com/repos/pandas-dev/pandas/pulls/44275
2021-11-01T19:36:00Z
2021-11-05T16:18:15Z
2021-11-05T16:18:14Z
2021-11-05T18:22:24Z
DOC: added examples to DataFrame.var #44162
diff --git a/pandas/core/generic.py b/pandas/core/generic.py index f3d7d6cee5446..cbfbd62975692 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -10661,12 +10661,12 @@ def sem( @doc( _num_ddof_doc, desc="Return unbiased variance over requested axis.\n\nNormalized by " - "N-1 by default. This can be changed using the ddof argument", + "N-1 by default. This can be changed using the ddof argument.", name1=name1, name2=name2, axis_descr=axis_descr, notes="", - examples="", + examples=_var_examples, ) def var( self, @@ -11221,6 +11221,32 @@ def _doc_params(cls): age 16.269219 height 0.205609""" +_var_examples = """ + +Examples +-------- +>>> df = pd.DataFrame({'person_id': [0, 1, 2, 3], +... 'age': [21, 25, 62, 43], +... 'height': [1.61, 1.87, 1.49, 2.01]} +... ).set_index('person_id') +>>> df + age height +person_id +0 21 1.61 +1 25 1.87 +2 62 1.49 +3 43 2.01 + +>>> df.var() +age 352.916667 +height 0.056367 + +Alternatively, ``ddof=0`` can be set to normalize by N instead of N-1: + +>>> df.var(ddof=0) +age 264.687500 +height 0.042275""" + _bool_doc = """ {desc}
- [x] closes #44162 by adding two examples to docstring of DataFrame.var - [x] tests added / passed - [x] All linting tests passed (pre-commit) Screenshot of locally built documentation: ![var](https://user-images.githubusercontent.com/58558211/139727701-f6c92ad1-948d-42bd-8989-2d874e3cfa58.PNG)
https://api.github.com/repos/pandas-dev/pandas/pulls/44274
2021-11-01T19:12:28Z
2021-11-06T20:51:37Z
2021-11-06T20:51:36Z
2021-11-06T20:51:44Z
TYP: use TYPE_CHECKING for import_optional_dependency("numba")
diff --git a/pandas/core/_numba/executor.py b/pandas/core/_numba/executor.py index c2b6191c05152..c9d3a9b1660ea 100644 --- a/pandas/core/_numba/executor.py +++ b/pandas/core/_numba/executor.py @@ -1,6 +1,9 @@ from __future__ import annotations -from typing import Callable +from typing import ( + TYPE_CHECKING, + Callable, +) import numpy as np @@ -42,10 +45,12 @@ def generate_shared_aggregator( if cache_key in NUMBA_FUNC_CACHE: return NUMBA_FUNC_CACHE[cache_key] - numba = import_optional_dependency("numba") + if TYPE_CHECKING: + import numba + else: + numba = import_optional_dependency("numba") - # error: Untyped decorator makes function "column_looper" untyped - @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) # type: ignore[misc] + @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) def column_looper( values: np.ndarray, start: np.ndarray, diff --git a/pandas/core/groupby/numba_.py b/pandas/core/groupby/numba_.py index ea295af8d7910..24d66725caa70 100644 --- a/pandas/core/groupby/numba_.py +++ b/pandas/core/groupby/numba_.py @@ -3,6 +3,7 @@ import inspect from typing import ( + TYPE_CHECKING, Any, Callable, ) @@ -90,10 +91,12 @@ def generate_numba_agg_func( return NUMBA_FUNC_CACHE[cache_key] numba_func = jit_user_function(func, nopython, nogil, parallel) - numba = import_optional_dependency("numba") + if TYPE_CHECKING: + import numba + else: + numba = import_optional_dependency("numba") - # error: Untyped decorator makes function "group_agg" untyped - @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) # type: ignore[misc] + @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) def group_agg( values: np.ndarray, index: np.ndarray, @@ -152,10 +155,12 @@ def generate_numba_transform_func( return NUMBA_FUNC_CACHE[cache_key] numba_func = jit_user_function(func, nopython, nogil, parallel) - numba = import_optional_dependency("numba") + if TYPE_CHECKING: + import numba + else: + numba = import_optional_dependency("numba") - # error: Untyped decorator makes function "group_transform" untyped - @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) # type: ignore[misc] + @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) def group_transform( values: np.ndarray, index: np.ndarray, diff --git a/pandas/core/util/numba_.py b/pandas/core/util/numba_.py index c738213d4c487..06630989444bb 100644 --- a/pandas/core/util/numba_.py +++ b/pandas/core/util/numba_.py @@ -1,9 +1,11 @@ """Common utilities for Numba operations""" -# pyright: reportUntypedFunctionDecorator = false from __future__ import annotations import types -from typing import Callable +from typing import ( + TYPE_CHECKING, + Callable, +) import numpy as np @@ -84,7 +86,10 @@ def jit_user_function( function Numba JITed function """ - numba = import_optional_dependency("numba") + if TYPE_CHECKING: + import numba + else: + numba = import_optional_dependency("numba") if numba.extending.is_jitted(func): # Don't jit a user passed jitted function diff --git a/pandas/core/window/numba_.py b/pandas/core/window/numba_.py index 74dc104b6db90..0e8eea3ec671e 100644 --- a/pandas/core/window/numba_.py +++ b/pandas/core/window/numba_.py @@ -1,8 +1,8 @@ -# pyright: reportUntypedFunctionDecorator = false from __future__ import annotations import functools from typing import ( + TYPE_CHECKING, Any, Callable, ) @@ -56,10 +56,12 @@ def generate_numba_apply_func( return NUMBA_FUNC_CACHE[cache_key] numba_func = jit_user_function(func, nopython, nogil, parallel) - numba = import_optional_dependency("numba") + if TYPE_CHECKING: + import numba + else: + numba = import_optional_dependency("numba") - # error: Untyped decorator makes function "roll_apply" untyped - @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) # type: ignore[misc] + @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) def roll_apply( values: np.ndarray, begin: np.ndarray, @@ -115,10 +117,12 @@ def generate_numba_ewm_func( if cache_key in NUMBA_FUNC_CACHE: return NUMBA_FUNC_CACHE[cache_key] - numba = import_optional_dependency("numba") + if TYPE_CHECKING: + import numba + else: + numba = import_optional_dependency("numba") - # error: Untyped decorator makes function "ewma" untyped - @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) # type: ignore[misc] + @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) def ewm( values: np.ndarray, begin: np.ndarray, @@ -217,10 +221,12 @@ def generate_numba_table_func( return NUMBA_FUNC_CACHE[cache_key] numba_func = jit_user_function(func, nopython, nogil, parallel) - numba = import_optional_dependency("numba") + if TYPE_CHECKING: + import numba + else: + numba = import_optional_dependency("numba") - # error: Untyped decorator makes function "roll_table" untyped - @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) # type: ignore[misc] + @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) def roll_table( values: np.ndarray, begin: np.ndarray, @@ -250,7 +256,10 @@ def roll_table( # https://github.com/numba/numba/issues/1269 @functools.lru_cache(maxsize=None) def generate_manual_numpy_nan_agg_with_axis(nan_func): - numba = import_optional_dependency("numba") + if TYPE_CHECKING: + import numba + else: + numba = import_optional_dependency("numba") @numba.jit(nopython=True, nogil=True, parallel=True) def nan_agg_with_axis(table): @@ -296,10 +305,12 @@ def generate_numba_ewm_table_func( if cache_key in NUMBA_FUNC_CACHE: return NUMBA_FUNC_CACHE[cache_key] - numba = import_optional_dependency("numba") + if TYPE_CHECKING: + import numba + else: + numba = import_optional_dependency("numba") - # error: Untyped decorator makes function "ewm_table" untyped - @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) # type: ignore[misc] + @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) def ewm_table( values: np.ndarray, begin: np.ndarray, diff --git a/pandas/core/window/online.py b/pandas/core/window/online.py index e8804936da78f..8ef4aee154db4 100644 --- a/pandas/core/window/online.py +++ b/pandas/core/window/online.py @@ -1,4 +1,5 @@ from typing import ( + TYPE_CHECKING, Dict, Optional, ) @@ -31,10 +32,12 @@ def generate_online_numba_ewma_func(engine_kwargs: Optional[Dict[str, bool]]): if cache_key in NUMBA_FUNC_CACHE: return NUMBA_FUNC_CACHE[cache_key] - numba = import_optional_dependency("numba") + if TYPE_CHECKING: + import numba + else: + numba = import_optional_dependency("numba") - # error: Untyped decorator makes function "online_ewma" untyped - @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) # type: ignore[misc] + @numba.jit(nopython=nopython, nogil=nogil, parallel=parallel) def online_ewma( values: np.ndarray, deltas: np.ndarray, diff --git a/typings/numba.pyi b/typings/numba.pyi index 526119951a000..f877cbf339a8b 100644 --- a/typings/numba.pyi +++ b/typings/numba.pyi @@ -40,3 +40,4 @@ def jit( ) -> Callable[[F], F]: ... njit = jit +generated_jit = jit
xref https://github.com/pandas-dev/pandas/pull/44233#issuecomment-955594933 or could go with https://github.com/pandas-dev/pandas/pull/44254#issuecomment-956450632 instead. cc @twoertwein
https://api.github.com/repos/pandas-dev/pandas/pulls/44273
2021-11-01T18:33:08Z
2021-11-29T01:08:35Z
2021-11-29T01:08:35Z
2021-11-29T01:08:40Z
Two tests didn't properly assert an exception was raised. Fixed.
diff --git a/pandas/tests/indexes/datetimes/test_indexing.py b/pandas/tests/indexes/datetimes/test_indexing.py index dd192db4b0eb3..8cffa035721b0 100644 --- a/pandas/tests/indexes/datetimes/test_indexing.py +++ b/pandas/tests/indexes/datetimes/test_indexing.py @@ -583,7 +583,6 @@ def test_get_indexer(self): def test_reasonable_keyerror(self): # GH#1062 index = DatetimeIndex(['1/3/2000']) - try: + with pytest.raises(KeyError) as excinfo: index.get_loc('1/1/2000') - except KeyError as e: - assert '2000' in str(e) + assert '2000' in str(excinfo.value) diff --git a/pandas/tests/io/parser/c_parser_only.py b/pandas/tests/io/parser/c_parser_only.py index e0422249289b7..9dc7b070f889d 100644 --- a/pandas/tests/io/parser/c_parser_only.py +++ b/pandas/tests/io/parser/c_parser_only.py @@ -23,21 +23,19 @@ class CParserTests(object): - def test_buffer_overflow(self): + @pytest.mark.parametrize( + 'malf', + ['1\r1\r1\r 1\r 1\r', + '1\r1\r1\r 1\r 1\r11\r', + '1\r1\r1\r 1\r 1\r11\r1\r'], + ids=['words pointer', 'stream pointer', 'lines pointer']) + def test_buffer_overflow(self, malf): # see gh-9205: test certain malformed input files that cause # buffer overflows in tokenizer.c - - malfw = "1\r1\r1\r 1\r 1\r" # buffer overflow in words pointer - malfs = "1\r1\r1\r 1\r 1\r11\r" # buffer overflow in stream pointer - malfl = "1\r1\r1\r 1\r 1\r11\r1\r" # buffer overflow in lines pointer - cperr = 'Buffer overflow caught - possible malformed input file.' - - for malf in (malfw, malfs, malfl): - try: - self.read_table(StringIO(malf)) - except Exception as err: - assert cperr in str(err) + with pytest.raises(pd.errors.ParserError) as excinfo: + self.read_table(StringIO(malf)) + assert cperr in str(excinfo.value) def test_buffer_rd_bytes(self): # see gh-12098: src->buffer in the C parser can be freed twice leading
- [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21409
2018-06-10T12:28:49Z
2018-06-12T11:37:01Z
2018-06-12T11:37:01Z
2018-06-17T12:58:45Z
BUG: Construct Timestamp with tz correctly near DST border
diff --git a/doc/source/whatsnew/v0.23.2.txt b/doc/source/whatsnew/v0.23.2.txt index c636e73fbd6c2..1de44ffeb4160 100644 --- a/doc/source/whatsnew/v0.23.2.txt +++ b/doc/source/whatsnew/v0.23.2.txt @@ -73,6 +73,10 @@ Bug Fixes - +**Timezones** +- Bug in :class:`Timestamp` and :class:`DatetimeIndex` where passing a :class:`Timestamp` localized after a DST transition would return a datetime before the DST transition (:issue:`20854`) +- Bug in comparing :class:`DataFrame`s with tz-aware :class:`DatetimeIndex` columns with a DST transition that raised a ``KeyError`` (:issue:`19970`) + **Other** - diff --git a/pandas/_libs/tslibs/conversion.pyx b/pandas/_libs/tslibs/conversion.pyx index f4841e6abb7e8..3cbef82437544 100644 --- a/pandas/_libs/tslibs/conversion.pyx +++ b/pandas/_libs/tslibs/conversion.pyx @@ -347,25 +347,11 @@ cdef _TSObject convert_datetime_to_tsobject(datetime ts, object tz, if tz is not None: tz = maybe_get_tz(tz) - # sort of a temporary hack if ts.tzinfo is not None: - if hasattr(tz, 'normalize') and hasattr(ts.tzinfo, '_utcoffset'): - ts = tz.normalize(ts) - obj.value = pydatetime_to_dt64(ts, &obj.dts) - obj.tzinfo = ts.tzinfo - else: - # tzoffset - try: - tz = ts.astimezone(tz).tzinfo - except: - pass - obj.value = pydatetime_to_dt64(ts, &obj.dts) - ts_offset = get_utcoffset(ts.tzinfo, ts) - obj.value -= int(ts_offset.total_seconds() * 1e9) - tz_offset = get_utcoffset(tz, ts) - obj.value += int(tz_offset.total_seconds() * 1e9) - dt64_to_dtstruct(obj.value, &obj.dts) - obj.tzinfo = tz + # Convert the current timezone to the passed timezone + ts = ts.astimezone(tz) + obj.value = pydatetime_to_dt64(ts, &obj.dts) + obj.tzinfo = ts.tzinfo elif not is_utc(tz): ts = _localize_pydatetime(ts, tz) obj.value = pydatetime_to_dt64(ts, &obj.dts) diff --git a/pandas/tests/frame/test_timezones.py b/pandas/tests/frame/test_timezones.py index fa589a0aa4817..3956968173070 100644 --- a/pandas/tests/frame/test_timezones.py +++ b/pandas/tests/frame/test_timezones.py @@ -133,3 +133,13 @@ def test_frame_reset_index(self, tz): 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/indexes/datetimes/test_construction.py b/pandas/tests/indexes/datetimes/test_construction.py index dae69a86910af..b138b79caac76 100644 --- a/pandas/tests/indexes/datetimes/test_construction.py +++ b/pandas/tests/indexes/datetimes/test_construction.py @@ -469,6 +469,15 @@ def test_constructor_with_non_normalized_pytz(self, tz): result = DatetimeIndex(['2010'], tz=non_norm_tz) assert pytz.timezone(tz) is result.tz + def test_constructor_timestamp_near_dst(self): + # GH 20854 + ts = [Timestamp('2016-10-30 03:00:00+0300', tz='Europe/Helsinki'), + Timestamp('2016-10-30 03:00:00+0200', tz='Europe/Helsinki')] + result = DatetimeIndex(ts) + expected = DatetimeIndex([ts[0].to_pydatetime(), + ts[1].to_pydatetime()]) + tm.assert_index_equal(result, expected) + class TestTimeSeries(object): diff --git a/pandas/tests/indexes/datetimes/test_date_range.py b/pandas/tests/indexes/datetimes/test_date_range.py index 193804b66395b..ec37bbbcb6c02 100644 --- a/pandas/tests/indexes/datetimes/test_date_range.py +++ b/pandas/tests/indexes/datetimes/test_date_range.py @@ -278,6 +278,20 @@ def test_wom_len(self, periods): res = date_range(start='20110101', periods=periods, freq='WOM-1MON') assert len(res) == periods + def test_construct_over_dst(self): + # GH 20854 + pre_dst = Timestamp('2010-11-07 01:00:00').tz_localize('US/Pacific', + ambiguous=True) + pst_dst = Timestamp('2010-11-07 01:00:00').tz_localize('US/Pacific', + ambiguous=False) + expect_data = [Timestamp('2010-11-07 00:00:00', tz='US/Pacific'), + pre_dst, + pst_dst] + expected = DatetimeIndex(expect_data) + result = date_range(start='2010-11-7', periods=3, + freq='H', tz='US/Pacific') + tm.assert_index_equal(result, expected) + class TestGenRangeGeneration(object): diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index ab87d98fca8eb..4689c7bea626f 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -528,6 +528,14 @@ def test_disallow_setting_tz(self, tz): with pytest.raises(AttributeError): ts.tz = tz + @pytest.mark.parametrize('offset', ['+0300', '+0200']) + def test_construct_timestamp_near_dst(self, offset): + # GH 20854 + expected = Timestamp('2016-10-30 03:00:00{}'.format(offset), + tz='Europe/Helsinki') + result = Timestamp(expected, tz='Europe/Helsinki') + assert result == expected + class TestTimestamp(object):
closes #19970 closes #20854 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry So I _think_ the reason we need to convert a `Timestamp` to `datetime` branch is because of how `Timestamp` behave with `normalize` explained by this https://github.com/pandas-dev/pandas/pull/18618#issuecomment-352271183
https://api.github.com/repos/pandas-dev/pandas/pulls/21407
2018-06-10T07:45:52Z
2018-06-13T10:51:43Z
2018-06-13T10:51:42Z
2018-06-29T14:47:48Z
BUG: `line terminator` and '\n to \r\n' problem in Windows(Issue #20353)
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 9159f7c8056ec..1940f22fd0661 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -235,6 +235,97 @@ If installed, we now require: | scipy | 0.18.1 | | +-----------------+-----------------+----------+ +.. _whatsnew_0240.api_breaking.csv_line_terminator: + +`os.linesep` is used for ``line_terminator`` of ``DataFrame.to_csv`` +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +:func:`DataFrame.to_csv` now uses :func:`os.linesep` rather than ``'\n'`` + for the default line terminator (:issue:`20353`). +This change only affects when running on Windows, where ``'\r\n'`` was used for line terminator +even when ``'\n'`` was passed in ``line_terminator``. + +Previous Behavior on Windows: + +.. code-block:: ipython + +In [1]: data = pd.DataFrame({ + ...: "string_with_lf": ["a\nbc"], + ...: "string_with_crlf": ["a\r\nbc"] + ...: }) + +In [2]: # When passing file PATH to to_csv, line_terminator does not work, and csv is saved with '\r\n'. + ...: # Also, this converts all '\n's in the data to '\r\n'. + ...: data.to_csv("test.csv", index=False, line_terminator='\n') + +In [3]: with open("test.csv", mode='rb') as f: + ...: print(f.read()) +b'string_with_lf,string_with_crlf\r\n"a\r\nbc","a\r\r\nbc"\r\n' + +In [4]: # When passing file OBJECT with newline option to to_csv, line_terminator works. + ...: with open("test2.csv", mode='w', newline='\n') as f: + ...: data.to_csv(f, index=False, line_terminator='\n') + +In [5]: with open("test2.csv", mode='rb') as f: + ...: print(f.read()) +b'string_with_lf,string_with_crlf\n"a\nbc","a\r\nbc"\n' + + +New Behavior on Windows: + +- By passing ``line_terminator`` explicitly, line terminator is set to that character. +- The value of ``line_terminator`` only affects the line terminator of CSV, + so it does not change the value inside the data. + +.. code-block:: ipython + +In [1]: data = pd.DataFrame({ + ...: "string_with_lf": ["a\nbc"], + ...: "string_with_crlf": ["a\r\nbc"] + ...: }) + +In [2]: data.to_csv("test.csv", index=False, line_terminator='\n') + +In [3]: with open("test.csv", mode='rb') as f: + ...: print(f.read()) +b'string_with_lf,string_with_crlf\n"a\nbc","a\r\nbc"\n' + + +- On Windows, the value of ``os.linesep`` is ``'\r\n'``, + so if ``line_terminator`` is not set, ``'\r\n'`` is used for line terminator. +- Again, it does not affect the value inside the data. + +.. code-block:: ipython + +In [1]: data = pd.DataFrame({ + ...: "string_with_lf": ["a\nbc"], + ...: "string_with_crlf": ["a\r\nbc"] + ...: }) + +In [2]: data.to_csv("test.csv", index=False) + +In [3]: with open("test.csv", mode='rb') as f: + ...: print(f.read()) +b'string_with_lf,string_with_crlf\r\n"a\nbc","a\r\nbc"\r\n' + + +- For files objects, specifying ``newline`` is not sufficient to set the line terminator. + You must pass in the ``line_terminator`` explicitly, even in this case. + +.. code-block:: ipython + +In [1]: data = pd.DataFrame({ + ...: "string_with_lf": ["a\nbc"], + ...: "string_with_crlf": ["a\r\nbc"] + ...: }) + +In [2]: with open("test2.csv", mode='w', newline='\n') as f: + ...: data.to_csv(f, index=False) + +In [3]: with open("test2.csv", mode='rb') as f: + ...: print(f.read()) +b'string_with_lf,string_with_crlf\r\n"a\nbc","a\r\nbc"\r\n' + .. _whatsnew_0240.api_breaking.interval_values: ``IntervalIndex.values`` is now an ``IntervalArray`` diff --git a/pandas/core/generic.py b/pandas/core/generic.py index ba050bfc8db77..e12a3f0d225eb 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -9518,7 +9518,7 @@ def last_valid_index(self): def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, mode='w', encoding=None, compression='infer', quoting=None, - quotechar='"', line_terminator='\n', chunksize=None, + quotechar='"', line_terminator=None, chunksize=None, tupleize_cols=None, date_format=None, doublequote=True, escapechar=None, decimal='.'): r""" @@ -9583,9 +9583,12 @@ def to_csv(self, path_or_buf=None, sep=",", na_rep='', float_format=None, will treat them as non-numeric. quotechar : str, default '\"' String of length 1. Character used to quote fields. - line_terminator : string, default ``'\n'`` + line_terminator : string, optional The newline character or character sequence to use in the output - file. + file. Defaults to `os.linesep`, which depends on the OS in which + this method is called ('\n' for linux, '\r\n' for Windows, i.e.). + + .. versionchanged:: 0.24.0 chunksize : int or None Rows to write at a time. tupleize_cols : bool, default False diff --git a/pandas/io/common.py b/pandas/io/common.py index 9bf7c5af2cd3a..2056c25ddc5f4 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -417,13 +417,14 @@ def _get_handle(path_or_buf, mode, encoding=None, compression=None, elif is_path: if compat.PY2: # Python 2 + mode = "wb" if mode == "w" else mode f = open(path_or_buf, mode) elif encoding: # Python 3 and encoding - f = open(path_or_buf, mode, encoding=encoding) + f = open(path_or_buf, mode, encoding=encoding, newline="") elif is_text: # Python 3 and no explicit encoding - f = open(path_or_buf, mode, errors='replace') + f = open(path_or_buf, mode, errors='replace', newline="") else: # Python 3 and binary mode f = open(path_or_buf, mode) diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py index 0344689183dbb..115e885a23b96 100644 --- a/pandas/io/formats/csvs.py +++ b/pandas/io/formats/csvs.py @@ -11,6 +11,7 @@ from zipfile import ZipFile import numpy as np +import os from pandas._libs import writers as libwriters @@ -73,7 +74,7 @@ def __init__(self, obj, path_or_buf=None, sep=",", na_rep='', self.doublequote = doublequote self.escapechar = escapechar - self.line_terminator = line_terminator + self.line_terminator = line_terminator or os.linesep self.date_format = date_format diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py index e1c3c29ef2846..aa91b7510a2b5 100644 --- a/pandas/tests/frame/test_to_csv.py +++ b/pandas/tests/frame/test_to_csv.py @@ -2,6 +2,7 @@ from __future__ import print_function +import os import csv import pytest @@ -841,11 +842,11 @@ def test_to_csv_unicodewriter_quoting(self): encoding='utf-8') result = buf.getvalue() - expected = ('"A","B"\n' - '1,"foo"\n' - '2,"bar"\n' - '3,"baz"\n') - + expected_rows = ['"A","B"', + '1,"foo"', + '2,"bar"', + '3,"baz"'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) assert result == expected def test_to_csv_quote_none(self): @@ -855,8 +856,12 @@ def test_to_csv_quote_none(self): buf = StringIO() df.to_csv(buf, quoting=csv.QUOTE_NONE, encoding=encoding, index=False) + result = buf.getvalue() - expected = 'A\nhello\n{"hello"}\n' + expected_rows = ['A', + 'hello', + '{"hello"}'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) assert result == expected def test_to_csv_index_no_leading_comma(self): @@ -865,31 +870,44 @@ def test_to_csv_index_no_leading_comma(self): buf = StringIO() df.to_csv(buf, index_label=False) - expected = ('A,B\n' - 'one,1,4\n' - 'two,2,5\n' - 'three,3,6\n') + + expected_rows = ['A,B', + 'one,1,4', + 'two,2,5', + 'three,3,6'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) assert buf.getvalue() == expected def test_to_csv_line_terminators(self): + # see gh-20353 df = DataFrame({'A': [1, 2, 3], 'B': [4, 5, 6]}, index=['one', 'two', 'three']) - buf = StringIO() - df.to_csv(buf, line_terminator='\r\n') - expected = (',A,B\r\n' - 'one,1,4\r\n' - 'two,2,5\r\n' - 'three,3,6\r\n') - assert buf.getvalue() == expected + with ensure_clean() as path: + # case 1: CRLF as line terminator + df.to_csv(path, line_terminator='\r\n') + expected = b',A,B\r\none,1,4\r\ntwo,2,5\r\nthree,3,6\r\n' - buf = StringIO() - df.to_csv(buf) # The default line terminator remains \n - expected = (',A,B\n' - 'one,1,4\n' - 'two,2,5\n' - 'three,3,6\n') - assert buf.getvalue() == expected + with open(path, mode='rb') as f: + assert f.read() == expected + + with ensure_clean() as path: + # case 2: LF as line terminator + df.to_csv(path, line_terminator='\n') + expected = b',A,B\none,1,4\ntwo,2,5\nthree,3,6\n' + + with open(path, mode='rb') as f: + assert f.read() == expected + + with ensure_clean() as path: + # case 3: The default line terminator(=os.linesep)(gh-21406) + df.to_csv(path) + os_linesep = os.linesep.encode('utf-8') + expected = (b',A,B' + os_linesep + b'one,1,4' + os_linesep + + b'two,2,5' + os_linesep + b'three,3,6' + os_linesep) + + with open(path, mode='rb') as f: + assert f.read() == expected def test_to_csv_from_csv_categorical(self): @@ -1069,35 +1087,39 @@ def test_to_csv_quoting(self): 'c_string': ['a', 'b,c'], }) - expected = """\ -,c_bool,c_float,c_int,c_string -0,True,1.0,42.0,a -1,False,3.2,,"b,c" -""" + expected_rows = [',c_bool,c_float,c_int,c_string', + '0,True,1.0,42.0,a', + '1,False,3.2,,"b,c"'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + result = df.to_csv() assert result == expected result = df.to_csv(quoting=None) assert result == expected + expected_rows = [',c_bool,c_float,c_int,c_string', + '0,True,1.0,42.0,a', + '1,False,3.2,,"b,c"'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + result = df.to_csv(quoting=csv.QUOTE_MINIMAL) assert result == expected - expected = """\ -"","c_bool","c_float","c_int","c_string" -"0","True","1.0","42.0","a" -"1","False","3.2","","b,c" -""" + expected_rows = ['"","c_bool","c_float","c_int","c_string"', + '"0","True","1.0","42.0","a"', + '"1","False","3.2","","b,c"'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + result = df.to_csv(quoting=csv.QUOTE_ALL) assert result == expected # see gh-12922, gh-13259: make sure changes to # the formatters do not break this behaviour - expected = """\ -"","c_bool","c_float","c_int","c_string" -0,True,1.0,42.0,"a" -1,False,3.2,"","b,c" -""" + expected_rows = ['"","c_bool","c_float","c_int","c_string"', + '0,True,1.0,42.0,"a"', + '1,False,3.2,"","b,c"'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) result = df.to_csv(quoting=csv.QUOTE_NONNUMERIC) assert result == expected @@ -1108,28 +1130,29 @@ def test_to_csv_quoting(self): quoting=csv.QUOTE_NONE, escapechar=None) - expected = """\ -,c_bool,c_float,c_int,c_string -0,True,1.0,42.0,a -1,False,3.2,,b!,c -""" + expected_rows = [',c_bool,c_float,c_int,c_string', + '0,True,1.0,42.0,a', + '1,False,3.2,,b!,c'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) result = df.to_csv(quoting=csv.QUOTE_NONE, escapechar='!') assert result == expected - expected = """\ -,c_bool,c_ffloat,c_int,c_string -0,True,1.0,42.0,a -1,False,3.2,,bf,c -""" + expected_rows = [',c_bool,c_ffloat,c_int,c_string', + '0,True,1.0,42.0,a', + '1,False,3.2,,bf,c'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) result = df.to_csv(quoting=csv.QUOTE_NONE, escapechar='f') assert result == expected # see gh-3503: quoting Windows line terminators # presents with encoding? - text = 'a,b,c\n1,"test \r\n",3\n' + text_rows = ['a,b,c', + '1,"test \r\n",3'] + text = tm.convert_rows_list_to_csv_str(text_rows) df = pd.read_csv(StringIO(text)) + buf = StringIO() df.to_csv(buf, encoding='utf-8', index=False) assert buf.getvalue() == text @@ -1138,7 +1161,11 @@ def test_to_csv_quoting(self): # with multi-indexes df = pd.DataFrame({'a': [1, 2], 'b': [3, 4], 'c': [5, 6]}) df = df.set_index(['a', 'b']) - expected = '"a","b","c"\n"1","3","5"\n"2","4","6"\n' + + expected_rows = ['"a","b","c"', + '"1","3","5"', + '"2","4","6"'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) assert df.to_csv(quoting=csv.QUOTE_ALL) == expected def test_period_index_date_overflow(self): @@ -1150,13 +1177,21 @@ def test_period_index_date_overflow(self): df = pd.DataFrame([4, 5, 6], index=index) result = df.to_csv() - expected = ',0\n1990-01-01,4\n2000-01-01,5\n3005-01-01,6\n' + expected_rows = [',0', + '1990-01-01,4', + '2000-01-01,5', + '3005-01-01,6'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) assert result == expected date_format = "%m-%d-%Y" result = df.to_csv(date_format=date_format) - expected = ',0\n01-01-1990,4\n01-01-2000,5\n01-01-3005,6\n' + expected_rows = [',0', + '01-01-1990,4', + '01-01-2000,5', + '01-01-3005,6'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) assert result == expected # Overflow with pd.NaT @@ -1166,7 +1201,11 @@ def test_period_index_date_overflow(self): df = pd.DataFrame([4, 5, 6], index=index) result = df.to_csv() - expected = ',0\n1990-01-01,4\n,5\n3005-01-01,6\n' + expected_rows = [',0', + '1990-01-01,4', + ',5', + '3005-01-01,6'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) assert result == expected def test_multi_index_header(self): @@ -1179,5 +1218,8 @@ def test_multi_index_header(self): header = ["a", "b", "c", "d"] result = df.to_csv(header=header) - expected = ",a,b,c,d\n0,1,2,3,4\n1,5,6,7,8\n" + expected_rows = [',a,b,c,d', + '0,1,2,3,4', + '1,5,6,7,8'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) assert result == expected diff --git a/pandas/tests/io/formats/test_to_csv.py b/pandas/tests/io/formats/test_to_csv.py index ea0b5f5cc0c66..7042cae526207 100644 --- a/pandas/tests/io/formats/test_to_csv.py +++ b/pandas/tests/io/formats/test_to_csv.py @@ -4,10 +4,11 @@ import pytest +import os import numpy as np import pandas as pd -from pandas import DataFrame +from pandas import DataFrame, compat from pandas.util import testing as tm @@ -132,29 +133,46 @@ def test_to_csv_escapechar(self): def test_csv_to_string(self): df = DataFrame({'col': [1, 2]}) - expected = ',col\n0,1\n1,2\n' + expected_rows = [',col', + '0,1', + '1,2'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) assert df.to_csv() == expected def test_to_csv_decimal(self): - # GH 781 + # see gh-781 df = DataFrame({'col1': [1], 'col2': ['a'], 'col3': [10.1]}) - expected_default = ',col1,col2,col3\n0,1,a,10.1\n' + expected_rows = [',col1,col2,col3', + '0,1,a,10.1'] + expected_default = tm.convert_rows_list_to_csv_str(expected_rows) assert df.to_csv() == expected_default - expected_european_excel = ';col1;col2;col3\n0;1;a;10,1\n' + expected_rows = [';col1;col2;col3', + '0;1;a;10,1'] + expected_european_excel = tm.convert_rows_list_to_csv_str( + expected_rows) assert df.to_csv(decimal=',', sep=';') == expected_european_excel - expected_float_format_default = ',col1,col2,col3\n0,1,a,10.10\n' + expected_rows = [',col1,col2,col3', + '0,1,a,10.10'] + expected_float_format_default = tm.convert_rows_list_to_csv_str( + expected_rows) assert df.to_csv(float_format='%.2f') == expected_float_format_default - expected_float_format = ';col1;col2;col3\n0;1;a;10,10\n' + expected_rows = [';col1;col2;col3', + '0;1;a;10,10'] + expected_float_format = tm.convert_rows_list_to_csv_str(expected_rows) assert df.to_csv(decimal=',', sep=';', float_format='%.2f') == expected_float_format - # GH 11553: testing if decimal is taken into account for '0.0' + # see gh-11553: testing if decimal is taken into account for '0.0' df = pd.DataFrame({'a': [0, 1.1], 'b': [2.2, 3.3], 'c': 1}) - expected = 'a,b,c\n0^0,2^2,1\n1^1,3^3,1\n' + + expected_rows = ['a,b,c', + '0^0,2^2,1', + '1^1,3^3,1'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) assert df.to_csv(index=False, decimal='^') == expected # same but for an index @@ -167,7 +185,11 @@ def test_to_csv_float_format(self): # testing if float_format is taken into account for the index # GH 11553 df = pd.DataFrame({'a': [0, 1], 'b': [2.2, 3.3], 'c': 1}) - expected = 'a,b,c\n0,2.20,1\n1,3.30,1\n' + + expected_rows = ['a,b,c', + '0,2.20,1', + '1,3.30,1'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) assert df.set_index('a').to_csv(float_format='%.2f') == expected # same for a multi-index @@ -175,22 +197,35 @@ def test_to_csv_float_format(self): float_format='%.2f') == expected def test_to_csv_na_rep(self): - # testing if NaN values are correctly represented in the index - # GH 11553 + # see gh-11553 + # + # Testing if NaN values are correctly represented in the index. df = DataFrame({'a': [0, np.NaN], 'b': [0, 1], 'c': [2, 3]}) - expected = "a,b,c\n0.0,0,2\n_,1,3\n" + expected_rows = ['a,b,c', + '0.0,0,2', + '_,1,3'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert df.set_index('a').to_csv(na_rep='_') == expected assert df.set_index(['a', 'b']).to_csv(na_rep='_') == expected # now with an index containing only NaNs df = DataFrame({'a': np.NaN, 'b': [0, 1], 'c': [2, 3]}) - expected = "a,b,c\n_,0,2\n_,1,3\n" + expected_rows = ['a,b,c', + '_,0,2', + '_,1,3'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert df.set_index('a').to_csv(na_rep='_') == expected assert df.set_index(['a', 'b']).to_csv(na_rep='_') == expected # check if na_rep parameter does not break anything when no NaN df = DataFrame({'a': 0, 'b': [0, 1], 'c': [2, 3]}) - expected = "a,b,c\n0,0,2\n0,1,3\n" + expected_rows = ['a,b,c', + '0,0,2', + '0,1,3'] + expected = tm.convert_rows_list_to_csv_str(expected_rows) + assert df.set_index('a').to_csv(na_rep='_') == expected assert df.set_index(['a', 'b']).to_csv(na_rep='_') == expected @@ -201,63 +236,93 @@ def test_to_csv_date_format(self): df_day = DataFrame({'A': pd.date_range('20130101', periods=5, freq='d') }) - expected_default_sec = (',A\n0,2013-01-01 00:00:00\n1,' - '2013-01-01 00:00:01\n2,2013-01-01 00:00:02' - '\n3,2013-01-01 00:00:03\n4,' - '2013-01-01 00:00:04\n') + expected_rows = [',A', + '0,2013-01-01 00:00:00', + '1,2013-01-01 00:00:01', + '2,2013-01-01 00:00:02', + '3,2013-01-01 00:00:03', + '4,2013-01-01 00:00:04'] + expected_default_sec = tm.convert_rows_list_to_csv_str(expected_rows) assert df_sec.to_csv() == expected_default_sec - expected_ymdhms_day = (',A\n0,2013-01-01 00:00:00\n1,' - '2013-01-02 00:00:00\n2,2013-01-03 00:00:00' - '\n3,2013-01-04 00:00:00\n4,' - '2013-01-05 00:00:00\n') + expected_rows = [',A', + '0,2013-01-01 00:00:00', + '1,2013-01-02 00:00:00', + '2,2013-01-03 00:00:00', + '3,2013-01-04 00:00:00', + '4,2013-01-05 00:00:00'] + expected_ymdhms_day = tm.convert_rows_list_to_csv_str(expected_rows) assert (df_day.to_csv(date_format='%Y-%m-%d %H:%M:%S') == expected_ymdhms_day) - expected_ymd_sec = (',A\n0,2013-01-01\n1,2013-01-01\n2,' - '2013-01-01\n3,2013-01-01\n4,2013-01-01\n') + expected_rows = [',A', + '0,2013-01-01', + '1,2013-01-01', + '2,2013-01-01', + '3,2013-01-01', + '4,2013-01-01'] + expected_ymd_sec = tm.convert_rows_list_to_csv_str(expected_rows) assert df_sec.to_csv(date_format='%Y-%m-%d') == expected_ymd_sec - expected_default_day = (',A\n0,2013-01-01\n1,2013-01-02\n2,' - '2013-01-03\n3,2013-01-04\n4,2013-01-05\n') + expected_rows = [',A', + '0,2013-01-01', + '1,2013-01-02', + '2,2013-01-03', + '3,2013-01-04', + '4,2013-01-05'] + expected_default_day = tm.convert_rows_list_to_csv_str(expected_rows) assert df_day.to_csv() == expected_default_day assert df_day.to_csv(date_format='%Y-%m-%d') == expected_default_day - # testing if date_format parameter is taken into account for - # multi-indexed dataframes (GH 7791) + # see gh-7791 + # + # Testing if date_format parameter is taken into account + # for multi-indexed DataFrames. df_sec['B'] = 0 df_sec['C'] = 1 - expected_ymd_sec = 'A,B,C\n2013-01-01,0,1\n' + + expected_rows = ['A,B,C', + '2013-01-01,0,1'] + expected_ymd_sec = tm.convert_rows_list_to_csv_str(expected_rows) + df_sec_grouped = df_sec.groupby([pd.Grouper(key='A', freq='1h'), 'B']) assert (df_sec_grouped.mean().to_csv(date_format='%Y-%m-%d') == expected_ymd_sec) def test_to_csv_multi_index(self): - # GH 6618 + # see gh-6618 df = DataFrame([1], columns=pd.MultiIndex.from_arrays([[1], [2]])) - exp = ",1\n,2\n0,1\n" + exp_rows = [',1', + ',2', + '0,1'] + exp = tm.convert_rows_list_to_csv_str(exp_rows) assert df.to_csv() == exp - exp = "1\n2\n1\n" + exp_rows = ['1', '2', '1'] + exp = tm.convert_rows_list_to_csv_str(exp_rows) assert df.to_csv(index=False) == exp df = DataFrame([1], columns=pd.MultiIndex.from_arrays([[1], [2]]), index=pd.MultiIndex.from_arrays([[1], [2]])) - exp = ",,1\n,,2\n1,2,1\n" + exp_rows = [',,1', ',,2', '1,2,1'] + exp = tm.convert_rows_list_to_csv_str(exp_rows) assert df.to_csv() == exp - exp = "1\n2\n1\n" + exp_rows = ['1', '2', '1'] + exp = tm.convert_rows_list_to_csv_str(exp_rows) assert df.to_csv(index=False) == exp df = DataFrame( [1], columns=pd.MultiIndex.from_arrays([['foo'], ['bar']])) - exp = ",foo\n,bar\n0,1\n" + exp_rows = [',foo', ',bar', '0,1'] + exp = tm.convert_rows_list_to_csv_str(exp_rows) assert df.to_csv() == exp - exp = "foo\nbar\n1\n" + exp_rows = ['foo', 'bar', '1'] + exp = tm.convert_rows_list_to_csv_str(exp_rows) assert df.to_csv(index=False) == exp def test_to_csv_string_array_ascii(self): @@ -289,21 +354,113 @@ def test_to_csv_string_array_utf8(self): with open(path, 'r') as f: assert f.read() == expected_utf8 + def test_to_csv_string_with_lf(self): + # GH 20353 + data = { + 'int': [1, 2, 3], + 'str_lf': ['abc', 'd\nef', 'g\nh\n\ni'] + } + df = pd.DataFrame(data) + with tm.ensure_clean('lf_test.csv') as path: + # case 1: The default line terminator(=os.linesep)(PR 21406) + os_linesep = os.linesep.encode('utf-8') + expected_noarg = ( + b'int,str_lf' + os_linesep + + b'1,abc' + os_linesep + + b'2,"d\nef"' + os_linesep + + b'3,"g\nh\n\ni"' + os_linesep + ) + df.to_csv(path, index=False) + with open(path, 'rb') as f: + assert f.read() == expected_noarg + with tm.ensure_clean('lf_test.csv') as path: + # case 2: LF as line terminator + expected_lf = ( + b'int,str_lf\n' + b'1,abc\n' + b'2,"d\nef"\n' + b'3,"g\nh\n\ni"\n' + ) + df.to_csv(path, line_terminator='\n', index=False) + with open(path, 'rb') as f: + assert f.read() == expected_lf + with tm.ensure_clean('lf_test.csv') as path: + # case 3: CRLF as line terminator + # 'line_terminator' should not change inner element + expected_crlf = ( + b'int,str_lf\r\n' + b'1,abc\r\n' + b'2,"d\nef"\r\n' + b'3,"g\nh\n\ni"\r\n' + ) + df.to_csv(path, line_terminator='\r\n', index=False) + with open(path, 'rb') as f: + assert f.read() == expected_crlf + + def test_to_csv_string_with_crlf(self): + # GH 20353 + data = { + 'int': [1, 2, 3], + 'str_crlf': ['abc', 'd\r\nef', 'g\r\nh\r\n\r\ni'] + } + df = pd.DataFrame(data) + with tm.ensure_clean('crlf_test.csv') as path: + # case 1: The default line terminator(=os.linesep)(PR 21406) + os_linesep = os.linesep.encode('utf-8') + expected_noarg = ( + b'int,str_crlf' + os_linesep + + b'1,abc' + os_linesep + + b'2,"d\r\nef"' + os_linesep + + b'3,"g\r\nh\r\n\r\ni"' + os_linesep + ) + df.to_csv(path, index=False) + with open(path, 'rb') as f: + assert f.read() == expected_noarg + with tm.ensure_clean('crlf_test.csv') as path: + # case 2: LF as line terminator + expected_lf = ( + b'int,str_crlf\n' + b'1,abc\n' + b'2,"d\r\nef"\n' + b'3,"g\r\nh\r\n\r\ni"\n' + ) + df.to_csv(path, line_terminator='\n', index=False) + with open(path, 'rb') as f: + assert f.read() == expected_lf + with tm.ensure_clean('crlf_test.csv') as path: + # case 3: CRLF as line terminator + # 'line_terminator' should not change inner element + expected_crlf = ( + b'int,str_crlf\r\n' + b'1,abc\r\n' + b'2,"d\r\nef"\r\n' + b'3,"g\r\nh\r\n\r\ni"\r\n' + ) + df.to_csv(path, line_terminator='\r\n', index=False) + with open(path, 'rb') as f: + assert f.read() == expected_crlf + @tm.capture_stdout def test_to_csv_stdout_file(self): # GH 21561 df = pd.DataFrame([['foo', 'bar'], ['baz', 'qux']], columns=['name_1', 'name_2']) - expected_ascii = '''\ -,name_1,name_2 -0,foo,bar -1,baz,qux -''' + expected_rows = [',name_1,name_2', + '0,foo,bar', + '1,baz,qux'] + expected_ascii = tm.convert_rows_list_to_csv_str(expected_rows) + df.to_csv(sys.stdout, encoding='ascii') output = sys.stdout.getvalue() + assert output == expected_ascii assert not sys.stdout.closed + @pytest.mark.xfail( + compat.is_platform_windows(), + reason=("Especially in Windows, file stream should not be passed" + "to csv writer without newline='' option." + "(https://docs.python.org/3.6/library/csv.html#csv.writer)")) def test_to_csv_write_to_open_file(self): # GH 21696 df = pd.DataFrame({'a': ['x', 'y', 'z']}) @@ -320,6 +477,42 @@ def test_to_csv_write_to_open_file(self): with open(path, 'r') as f: assert f.read() == expected + @pytest.mark.skipif(compat.PY2, reason="Test case for python3") + def test_to_csv_write_to_open_file_with_newline_py3(self): + # see gh-21696 + # see gh-20353 + df = pd.DataFrame({'a': ['x', 'y', 'z']}) + expected_rows = ["x", + "y", + "z"] + expected = ("manual header\n" + + tm.convert_rows_list_to_csv_str(expected_rows)) + with tm.ensure_clean('test.txt') as path: + with open(path, 'w', newline='') as f: + f.write('manual header\n') + df.to_csv(f, header=None, index=None) + + with open(path, 'rb') as f: + assert f.read() == bytes(expected, 'utf-8') + + @pytest.mark.skipif(compat.PY3, reason="Test case for python2") + def test_to_csv_write_to_open_file_with_newline_py2(self): + # see gh-21696 + # see gh-20353 + df = pd.DataFrame({'a': ['x', 'y', 'z']}) + expected_rows = ["x", + "y", + "z"] + expected = ("manual header\n" + + tm.convert_rows_list_to_csv_str(expected_rows)) + with tm.ensure_clean('test.txt') as path: + with open(path, 'wb') as f: + f.write('manual header\n') + df.to_csv(f, header=None, index=None) + + with open(path, 'rb') as f: + assert f.read() == expected + @pytest.mark.parametrize("to_infer", [True, False]) @pytest.mark.parametrize("read_infer", [True, False]) def test_to_csv_compression(self, compression_only, diff --git a/pandas/tests/io/test_html.py b/pandas/tests/io/test_html.py index e08899a03d2d7..b748e9aa5ef5b 100644 --- a/pandas/tests/io/test_html.py +++ b/pandas/tests/io/test_html.py @@ -270,7 +270,7 @@ def test_invalid_url(self): self.read_html('http://www.a23950sdfa908sd.com', match='.*Water.*') except ValueError as e: - assert str(e) == 'No tables found' + assert 'No tables found' in str(e) @pytest.mark.slow def test_file_url(self): diff --git a/pandas/tests/util/test_testing.py b/pandas/tests/util/test_testing.py index da84973274933..d968005a25006 100644 --- a/pandas/tests/util/test_testing.py +++ b/pandas/tests/util/test_testing.py @@ -12,6 +12,7 @@ assert_index_equal, assert_series_equal, assert_frame_equal, assert_numpy_array_equal, RNGContext) +from pandas import compat class TestAssertAlmostEqual(object): @@ -164,6 +165,17 @@ def test_raise_with_traceback(self): _, _, traceback = sys.exc_info() raise_with_traceback(e, traceback) + def test_convert_rows_list_to_csv_str(self): + rows_list = ["aaa", "bbb", "ccc"] + ret = tm.convert_rows_list_to_csv_str(rows_list) + + if compat.is_platform_windows(): + expected = "aaa\r\nbbb\r\nccc\r\n" + else: + expected = "aaa\nbbb\nccc\n" + + assert ret == expected + class TestAssertNumpyArrayEqual(object): diff --git a/pandas/util/testing.py b/pandas/util/testing.py index 1bd9043f42634..b5ec0912c5c26 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -2983,3 +2983,24 @@ def skipna_wrapper(x): return alternative(nona) return skipna_wrapper + + +def convert_rows_list_to_csv_str(rows_list): + """ + Convert list of CSV rows to single CSV-formatted string for current OS. + + This method is used for creating expected value of to_csv() method. + + Parameters + ---------- + rows_list : list + The list of string. Each element represents the row of csv. + + Returns + ------- + expected : string + Expected output of to_csv() in current OS + """ + sep = os.linesep + expected = sep.join(rows_list) + sep + return expected
- [ ] closes #20353 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21406
2018-06-10T07:01:37Z
2018-10-19T12:55:28Z
2018-10-19T12:55:27Z
2018-10-19T12:55:35Z
parametrize tests, unify repeated tests
diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 5369b1a94a956..e310feba9f700 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -89,6 +89,7 @@ def test_to_m8(): class Base(object): _offset = None + d = Timestamp(datetime(2008, 1, 2)) timezones = [None, 'UTC', 'Asia/Tokyo', 'US/Eastern', 'dateutil/Asia/Tokyo', 'dateutil/US/Pacific'] @@ -148,6 +149,56 @@ def test_apply_out_of_range(self, tz): # so ignore pass + def test_offsets_compare_equal(self): + # root cause of GH#456: __ne__ was not implemented + if self._offset is None: + return + offset1 = self._offset() + offset2 = self._offset() + assert not offset1 != offset2 + assert offset1 == offset2 + + def test_rsub(self): + if self._offset is None or not hasattr(self, "offset2"): + # i.e. skip for TestCommon and YQM subclasses that do not have + # offset2 attr + return + assert self.d - self.offset2 == (-self.offset2).apply(self.d) + + def test_radd(self): + if self._offset is None or not hasattr(self, "offset2"): + # i.e. skip for TestCommon and YQM subclasses that do not have + # offset2 attr + return + assert self.d + self.offset2 == self.offset2 + self.d + + def test_sub(self): + if self._offset is None or not hasattr(self, "offset2"): + # i.e. skip for TestCommon and YQM subclasses that do not have + # offset2 attr + return + off = self.offset2 + with pytest.raises(Exception): + off - self.d + + assert 2 * off - off == off + assert self.d - self.offset2 == self.d + self._offset(-2) + assert self.d - self.offset2 == self.d - (2 * off - off) + + def testMult1(self): + if self._offset is None or not hasattr(self, "offset1"): + # i.e. skip for TestCommon and YQM subclasses that do not have + # offset1 attr + return + assert self.d + 10 * self.offset1 == self.d + self._offset(10) + assert self.d + 5 * self.offset1 == self.d + self._offset(5) + + def testMult2(self): + if self._offset is None: + return + assert self.d + (-5 * self._offset(-10)) == self.d + self._offset(50) + assert self.d + (-3 * self._offset(-2)) == self.d + self._offset(6) + class TestCommon(Base): # exected value created by Base._get_offset @@ -515,6 +566,7 @@ def setup_method(self, method): self.d = datetime(2008, 1, 1) self.offset = BDay() + self.offset1 = self.offset self.offset2 = BDay(2) def test_different_normalize_equals(self): @@ -536,7 +588,7 @@ def test_with_offset(self): assert (self.d + offset) == datetime(2008, 1, 2, 2) - def testEQ(self): + def test_eq(self): assert self.offset2 == self.offset2 def test_mul(self): @@ -545,28 +597,9 @@ def test_mul(self): def test_hash(self): assert hash(self.offset2) == hash(self.offset2) - def testCall(self): + def test_call(self): assert self.offset2(self.d) == datetime(2008, 1, 3) - def testRAdd(self): - assert self.d + self.offset2 == self.offset2 + self.d - - def testSub(self): - off = self.offset2 - pytest.raises(Exception, off.__sub__, self.d) - assert 2 * off - off == off - - assert self.d - self.offset2 == self.d + BDay(-2) - - def testRSub(self): - assert self.d - self.offset2 == (-self.offset2).apply(self.d) - - def testMult1(self): - assert self.d + 10 * self.offset == self.d + BDay(10) - - def testMult2(self): - assert self.d + (-5 * BDay(-10)) == self.d + BDay(50) - def testRollback1(self): assert BDay(10).rollback(self.d) == self.d @@ -678,12 +711,6 @@ def test_apply_large_n(self): def test_apply_corner(self): pytest.raises(TypeError, BDay().apply, BMonthEnd()) - def test_offsets_compare_equal(self): - # root cause of #456 - offset1 = BDay() - offset2 = BDay() - assert not offset1 != offset2 - class TestBusinessHour(Base): _offset = BusinessHour @@ -735,7 +762,7 @@ def test_with_offset(self): assert self.d + BusinessHour() * 3 == expected assert self.d + BusinessHour(n=3) == expected - def testEQ(self): + def test_eq(self): for offset in [self.offset1, self.offset2, self.offset3, self.offset4]: assert offset == offset @@ -749,31 +776,22 @@ def test_hash(self): for offset in [self.offset1, self.offset2, self.offset3, self.offset4]: assert hash(offset) == hash(offset) - def testCall(self): + def test_call(self): assert self.offset1(self.d) == datetime(2014, 7, 1, 11) assert self.offset2(self.d) == datetime(2014, 7, 1, 13) assert self.offset3(self.d) == datetime(2014, 6, 30, 17) assert self.offset4(self.d) == datetime(2014, 6, 30, 14) - def testRAdd(self): - assert self.d + self.offset2 == self.offset2 + self.d - - def testSub(self): + def test_sub(self): + # we have to override test_sub here becasue self.offset2 is not + # defined as self._offset(2) off = self.offset2 - pytest.raises(Exception, off.__sub__, self.d) + with pytest.raises(Exception): + off - self.d assert 2 * off - off == off assert self.d - self.offset2 == self.d + self._offset(-3) - def testRSub(self): - assert self.d - self.offset2 == (-self.offset2).apply(self.d) - - def testMult1(self): - assert self.d + 5 * self.offset1 == self.d + self._offset(5) - - def testMult2(self): - assert self.d + (-3 * self._offset(-2)) == self.d + self._offset(6) - def testRollback1(self): assert self.offset1.rollback(self.d) == self.d assert self.offset2.rollback(self.d) == self.d @@ -1323,12 +1341,6 @@ def test_apply_nanoseconds(self): for base, expected in compat.iteritems(cases): assert_offset_equal(offset, base, expected) - def test_offsets_compare_equal(self): - # root cause of #456 - offset1 = self._offset() - offset2 = self._offset() - assert not offset1 != offset2 - def test_datetimeindex(self): idx1 = DatetimeIndex(start='2014-07-04 15:00', end='2014-07-08 10:00', freq='BH') @@ -1367,6 +1379,8 @@ def test_datetimeindex(self): class TestCustomBusinessHour(Base): _offset = CustomBusinessHour + holidays = ['2014-06-27', datetime(2014, 6, 30), + np.datetime64('2014-07-02')] def setup_method(self, method): # 2014 Calendar to check custom holidays @@ -1377,8 +1391,6 @@ def setup_method(self, method): self.d = datetime(2014, 7, 1, 10, 00) self.offset1 = CustomBusinessHour(weekmask='Tue Wed Thu Fri') - self.holidays = ['2014-06-27', datetime(2014, 6, 30), - np.datetime64('2014-07-02')] self.offset2 = CustomBusinessHour(holidays=self.holidays) def test_constructor_errors(self): @@ -1407,7 +1419,7 @@ def test_with_offset(self): assert self.d + CustomBusinessHour() * 3 == expected assert self.d + CustomBusinessHour(n=3) == expected - def testEQ(self): + def test_eq(self): for offset in [self.offset1, self.offset2]: assert offset == offset @@ -1424,33 +1436,19 @@ def testEQ(self): assert (CustomBusinessHour(holidays=['2014-06-27']) != CustomBusinessHour(holidays=['2014-06-28'])) + def test_sub(self): + # override the Base.test_sub implementation because self.offset2 is + # defined differently in this class than the test expects + pass + def test_hash(self): assert hash(self.offset1) == hash(self.offset1) assert hash(self.offset2) == hash(self.offset2) - def testCall(self): + def test_call(self): assert self.offset1(self.d) == datetime(2014, 7, 1, 11) assert self.offset2(self.d) == datetime(2014, 7, 1, 11) - def testRAdd(self): - assert self.d + self.offset2 == self.offset2 + self.d - - def testSub(self): - off = self.offset2 - pytest.raises(Exception, off.__sub__, self.d) - assert 2 * off - off == off - - assert self.d - self.offset2 == self.d - (2 * off - off) - - def testRSub(self): - assert self.d - self.offset2 == (-self.offset2).apply(self.d) - - def testMult1(self): - assert self.d + 5 * self.offset1 == self.d + self._offset(5) - - def testMult2(self): - assert self.d + (-3 * self._offset(-2)) == self.d + self._offset(6) - def testRollback1(self): assert self.offset1.rollback(self.d) == self.d assert self.offset2.rollback(self.d) == self.d @@ -1490,49 +1488,51 @@ def test_roll_date_object(self): result = offset.rollforward(dt) assert result == datetime(2014, 7, 7, 9) - def test_normalize(self): - tests = [] - - tests.append((CustomBusinessHour(normalize=True, - holidays=self.holidays), - {datetime(2014, 7, 1, 8): datetime(2014, 7, 1), - datetime(2014, 7, 1, 17): datetime(2014, 7, 3), - datetime(2014, 7, 1, 16): datetime(2014, 7, 3), - datetime(2014, 7, 1, 23): datetime(2014, 7, 3), - datetime(2014, 7, 1, 0): datetime(2014, 7, 1), - datetime(2014, 7, 4, 15): datetime(2014, 7, 4), - datetime(2014, 7, 4, 15, 59): datetime(2014, 7, 4), - datetime(2014, 7, 4, 16, 30): datetime(2014, 7, 7), - datetime(2014, 7, 5, 23): datetime(2014, 7, 7), - datetime(2014, 7, 6, 10): datetime(2014, 7, 7)})) - - tests.append((CustomBusinessHour(-1, normalize=True, - holidays=self.holidays), - {datetime(2014, 7, 1, 8): datetime(2014, 6, 26), - datetime(2014, 7, 1, 17): datetime(2014, 7, 1), - datetime(2014, 7, 1, 16): datetime(2014, 7, 1), - datetime(2014, 7, 1, 10): datetime(2014, 6, 26), - datetime(2014, 7, 1, 0): datetime(2014, 6, 26), - datetime(2014, 7, 7, 10): datetime(2014, 7, 4), - datetime(2014, 7, 7, 10, 1): datetime(2014, 7, 7), - datetime(2014, 7, 5, 23): datetime(2014, 7, 4), - datetime(2014, 7, 6, 10): datetime(2014, 7, 4)})) - - tests.append((CustomBusinessHour(1, normalize=True, start='17:00', - end='04:00', holidays=self.holidays), - {datetime(2014, 7, 1, 8): datetime(2014, 7, 1), - datetime(2014, 7, 1, 17): datetime(2014, 7, 1), - datetime(2014, 7, 1, 23): datetime(2014, 7, 2), - datetime(2014, 7, 2, 2): datetime(2014, 7, 2), - datetime(2014, 7, 2, 3): datetime(2014, 7, 3), - datetime(2014, 7, 4, 23): datetime(2014, 7, 5), - datetime(2014, 7, 5, 2): datetime(2014, 7, 5), - datetime(2014, 7, 7, 2): datetime(2014, 7, 7), - datetime(2014, 7, 7, 17): datetime(2014, 7, 7)})) - - for offset, cases in tests: - for dt, expected in compat.iteritems(cases): - assert offset.apply(dt) == expected + normalize_cases = [] + normalize_cases.append(( + CustomBusinessHour(normalize=True, holidays=holidays), + {datetime(2014, 7, 1, 8): datetime(2014, 7, 1), + datetime(2014, 7, 1, 17): datetime(2014, 7, 3), + datetime(2014, 7, 1, 16): datetime(2014, 7, 3), + datetime(2014, 7, 1, 23): datetime(2014, 7, 3), + datetime(2014, 7, 1, 0): datetime(2014, 7, 1), + datetime(2014, 7, 4, 15): datetime(2014, 7, 4), + datetime(2014, 7, 4, 15, 59): datetime(2014, 7, 4), + datetime(2014, 7, 4, 16, 30): datetime(2014, 7, 7), + datetime(2014, 7, 5, 23): datetime(2014, 7, 7), + datetime(2014, 7, 6, 10): datetime(2014, 7, 7)})) + + normalize_cases.append(( + CustomBusinessHour(-1, normalize=True, holidays=holidays), + {datetime(2014, 7, 1, 8): datetime(2014, 6, 26), + datetime(2014, 7, 1, 17): datetime(2014, 7, 1), + datetime(2014, 7, 1, 16): datetime(2014, 7, 1), + datetime(2014, 7, 1, 10): datetime(2014, 6, 26), + datetime(2014, 7, 1, 0): datetime(2014, 6, 26), + datetime(2014, 7, 7, 10): datetime(2014, 7, 4), + datetime(2014, 7, 7, 10, 1): datetime(2014, 7, 7), + datetime(2014, 7, 5, 23): datetime(2014, 7, 4), + datetime(2014, 7, 6, 10): datetime(2014, 7, 4)})) + + normalize_cases.append(( + CustomBusinessHour(1, normalize=True, + start='17:00', end='04:00', + holidays=holidays), + {datetime(2014, 7, 1, 8): datetime(2014, 7, 1), + datetime(2014, 7, 1, 17): datetime(2014, 7, 1), + datetime(2014, 7, 1, 23): datetime(2014, 7, 2), + datetime(2014, 7, 2, 2): datetime(2014, 7, 2), + datetime(2014, 7, 2, 3): datetime(2014, 7, 3), + datetime(2014, 7, 4, 23): datetime(2014, 7, 5), + datetime(2014, 7, 5, 2): datetime(2014, 7, 5), + datetime(2014, 7, 7, 2): datetime(2014, 7, 7), + datetime(2014, 7, 7, 17): datetime(2014, 7, 7)})) + + @pytest.mark.parametrize('norm_cases', normalize_cases) + def test_normalize(self, norm_cases): + offset, cases = norm_cases + for dt, expected in compat.iteritems(cases): + assert offset.apply(dt) == expected def test_onOffset(self): tests = [] @@ -1550,75 +1550,75 @@ def test_onOffset(self): for dt, expected in compat.iteritems(cases): assert offset.onOffset(dt) == expected - def test_apply(self): - tests = [] - - tests.append(( - CustomBusinessHour(holidays=self.holidays), - {datetime(2014, 7, 1, 11): datetime(2014, 7, 1, 12), - datetime(2014, 7, 1, 13): datetime(2014, 7, 1, 14), - datetime(2014, 7, 1, 15): datetime(2014, 7, 1, 16), - datetime(2014, 7, 1, 19): datetime(2014, 7, 3, 10), - datetime(2014, 7, 1, 16): datetime(2014, 7, 3, 9), - datetime(2014, 7, 1, 16, 30, 15): datetime(2014, 7, 3, 9, 30, 15), - datetime(2014, 7, 1, 17): datetime(2014, 7, 3, 10), - datetime(2014, 7, 2, 11): datetime(2014, 7, 3, 10), - # out of business hours - datetime(2014, 7, 2, 8): datetime(2014, 7, 3, 10), - datetime(2014, 7, 2, 19): datetime(2014, 7, 3, 10), - datetime(2014, 7, 2, 23): datetime(2014, 7, 3, 10), - datetime(2014, 7, 3, 0): datetime(2014, 7, 3, 10), - # saturday - datetime(2014, 7, 5, 15): datetime(2014, 7, 7, 10), - datetime(2014, 7, 4, 17): datetime(2014, 7, 7, 10), - datetime(2014, 7, 4, 16, 30): datetime(2014, 7, 7, 9, 30), - datetime(2014, 7, 4, 16, 30, 30): datetime(2014, 7, 7, 9, 30, - 30)})) - - tests.append(( - CustomBusinessHour(4, holidays=self.holidays), - {datetime(2014, 7, 1, 11): datetime(2014, 7, 1, 15), - datetime(2014, 7, 1, 13): datetime(2014, 7, 3, 9), - datetime(2014, 7, 1, 15): datetime(2014, 7, 3, 11), - datetime(2014, 7, 1, 16): datetime(2014, 7, 3, 12), - datetime(2014, 7, 1, 17): datetime(2014, 7, 3, 13), - datetime(2014, 7, 2, 11): datetime(2014, 7, 3, 13), - datetime(2014, 7, 2, 8): datetime(2014, 7, 3, 13), - datetime(2014, 7, 2, 19): datetime(2014, 7, 3, 13), - datetime(2014, 7, 2, 23): datetime(2014, 7, 3, 13), - datetime(2014, 7, 3, 0): datetime(2014, 7, 3, 13), - datetime(2014, 7, 5, 15): datetime(2014, 7, 7, 13), - datetime(2014, 7, 4, 17): datetime(2014, 7, 7, 13), - datetime(2014, 7, 4, 16, 30): datetime(2014, 7, 7, 12, 30), - datetime(2014, 7, 4, 16, 30, 30): datetime(2014, 7, 7, 12, 30, - 30)})) - - for offset, cases in tests: - for base, expected in compat.iteritems(cases): - assert_offset_equal(offset, base, expected) - - def test_apply_nanoseconds(self): - tests = [] - - tests.append((CustomBusinessHour(holidays=self.holidays), - {Timestamp('2014-07-01 15:00') + Nano(5): Timestamp( - '2014-07-01 16:00') + Nano(5), - Timestamp('2014-07-01 16:00') + Nano(5): Timestamp( - '2014-07-03 09:00') + Nano(5), - Timestamp('2014-07-01 16:00') - Nano(5): Timestamp( - '2014-07-01 17:00') - Nano(5)})) - - tests.append((CustomBusinessHour(-1, holidays=self.holidays), - {Timestamp('2014-07-01 15:00') + Nano(5): Timestamp( - '2014-07-01 14:00') + Nano(5), - Timestamp('2014-07-01 10:00') + Nano(5): Timestamp( - '2014-07-01 09:00') + Nano(5), - Timestamp('2014-07-01 10:00') - Nano(5): Timestamp( - '2014-06-26 17:00') - Nano(5), })) + apply_cases = [] + apply_cases.append(( + CustomBusinessHour(holidays=holidays), + {datetime(2014, 7, 1, 11): datetime(2014, 7, 1, 12), + datetime(2014, 7, 1, 13): datetime(2014, 7, 1, 14), + datetime(2014, 7, 1, 15): datetime(2014, 7, 1, 16), + datetime(2014, 7, 1, 19): datetime(2014, 7, 3, 10), + datetime(2014, 7, 1, 16): datetime(2014, 7, 3, 9), + datetime(2014, 7, 1, 16, 30, 15): datetime(2014, 7, 3, 9, 30, 15), + datetime(2014, 7, 1, 17): datetime(2014, 7, 3, 10), + datetime(2014, 7, 2, 11): datetime(2014, 7, 3, 10), + # out of business hours + datetime(2014, 7, 2, 8): datetime(2014, 7, 3, 10), + datetime(2014, 7, 2, 19): datetime(2014, 7, 3, 10), + datetime(2014, 7, 2, 23): datetime(2014, 7, 3, 10), + datetime(2014, 7, 3, 0): datetime(2014, 7, 3, 10), + # saturday + datetime(2014, 7, 5, 15): datetime(2014, 7, 7, 10), + datetime(2014, 7, 4, 17): datetime(2014, 7, 7, 10), + datetime(2014, 7, 4, 16, 30): datetime(2014, 7, 7, 9, 30), + datetime(2014, 7, 4, 16, 30, 30): datetime(2014, 7, 7, 9, 30, 30)})) + + apply_cases.append(( + CustomBusinessHour(4, holidays=holidays), + {datetime(2014, 7, 1, 11): datetime(2014, 7, 1, 15), + datetime(2014, 7, 1, 13): datetime(2014, 7, 3, 9), + datetime(2014, 7, 1, 15): datetime(2014, 7, 3, 11), + datetime(2014, 7, 1, 16): datetime(2014, 7, 3, 12), + datetime(2014, 7, 1, 17): datetime(2014, 7, 3, 13), + datetime(2014, 7, 2, 11): datetime(2014, 7, 3, 13), + datetime(2014, 7, 2, 8): datetime(2014, 7, 3, 13), + datetime(2014, 7, 2, 19): datetime(2014, 7, 3, 13), + datetime(2014, 7, 2, 23): datetime(2014, 7, 3, 13), + datetime(2014, 7, 3, 0): datetime(2014, 7, 3, 13), + datetime(2014, 7, 5, 15): datetime(2014, 7, 7, 13), + datetime(2014, 7, 4, 17): datetime(2014, 7, 7, 13), + datetime(2014, 7, 4, 16, 30): datetime(2014, 7, 7, 12, 30), + datetime(2014, 7, 4, 16, 30, 30): datetime(2014, 7, 7, 12, 30, 30)})) + + @pytest.mark.parametrize('apply_case', apply_cases) + def test_apply(self, apply_case): + offset, cases = apply_case + for base, expected in compat.iteritems(cases): + assert_offset_equal(offset, base, expected) - for offset, cases in tests: - for base, expected in compat.iteritems(cases): - assert_offset_equal(offset, base, expected) + nano_cases = [] + nano_cases.append( + (CustomBusinessHour(holidays=holidays), + {Timestamp('2014-07-01 15:00') + Nano(5): + Timestamp('2014-07-01 16:00') + Nano(5), + Timestamp('2014-07-01 16:00') + Nano(5): + Timestamp('2014-07-03 09:00') + Nano(5), + Timestamp('2014-07-01 16:00') - Nano(5): + Timestamp('2014-07-01 17:00') - Nano(5)})) + + nano_cases.append( + (CustomBusinessHour(-1, holidays=holidays), + {Timestamp('2014-07-01 15:00') + Nano(5): + Timestamp('2014-07-01 14:00') + Nano(5), + Timestamp('2014-07-01 10:00') + Nano(5): + Timestamp('2014-07-01 09:00') + Nano(5), + Timestamp('2014-07-01 10:00') - Nano(5): + Timestamp('2014-06-26 17:00') - Nano(5)})) + + @pytest.mark.parametrize('nano_case', nano_cases) + def test_apply_nanoseconds(self, nano_case): + offset, cases = nano_case + for base, expected in compat.iteritems(cases): + assert_offset_equal(offset, base, expected) class TestCustomBusinessDay(Base): @@ -1629,6 +1629,7 @@ def setup_method(self, method): self.nd = np_datetime64_compat('2008-01-01 00:00:00Z') self.offset = CDay() + self.offset1 = self.offset self.offset2 = CDay(2) def test_different_normalize_equals(self): @@ -1650,7 +1651,7 @@ def test_with_offset(self): assert (self.d + offset) == datetime(2008, 1, 2, 2) - def testEQ(self): + def test_eq(self): assert self.offset2 == self.offset2 def test_mul(self): @@ -1659,29 +1660,10 @@ def test_mul(self): def test_hash(self): assert hash(self.offset2) == hash(self.offset2) - def testCall(self): + def test_call(self): assert self.offset2(self.d) == datetime(2008, 1, 3) assert self.offset2(self.nd) == datetime(2008, 1, 3) - def testRAdd(self): - assert self.d + self.offset2 == self.offset2 + self.d - - def testSub(self): - off = self.offset2 - pytest.raises(Exception, off.__sub__, self.d) - assert 2 * off - off == off - - assert self.d - self.offset2 == self.d + CDay(-2) - - def testRSub(self): - assert self.d - self.offset2 == (-self.offset2).apply(self.d) - - def testMult1(self): - assert self.d + 10 * self.offset == self.d + CDay(10) - - def testMult2(self): - assert self.d + (-5 * CDay(-10)) == self.d + CDay(50) - def testRollback1(self): assert CDay(10).rollback(self.d) == self.d @@ -1789,12 +1771,6 @@ def test_apply_large_n(self): def test_apply_corner(self): pytest.raises(Exception, CDay().apply, BMonthEnd()) - def test_offsets_compare_equal(self): - # root cause of #456 - offset1 = CDay() - offset2 = CDay() - assert not offset1 != offset2 - def test_holidays(self): # Define a TradingDay offset holidays = ['2012-05-01', datetime(2013, 5, 1), @@ -1863,10 +1839,11 @@ class CustomBusinessMonthBase(object): def setup_method(self, method): self.d = datetime(2008, 1, 1) - self.offset = self._object() - self.offset2 = self._object(2) + self.offset = self._offset() + self.offset1 = self.offset + self.offset2 = self._offset(2) - def testEQ(self): + def test_eq(self): assert self.offset2 == self.offset2 def test_mul(self): @@ -1875,47 +1852,23 @@ def test_mul(self): def test_hash(self): assert hash(self.offset2) == hash(self.offset2) - def testRAdd(self): - assert self.d + self.offset2 == self.offset2 + self.d - - def testSub(self): - off = self.offset2 - pytest.raises(Exception, off.__sub__, self.d) - assert 2 * off - off == off - - assert self.d - self.offset2 == self.d + self._object(-2) - - def testRSub(self): - assert self.d - self.offset2 == (-self.offset2).apply(self.d) - - def testMult1(self): - assert self.d + 10 * self.offset == self.d + self._object(10) - - def testMult2(self): - assert self.d + (-5 * self._object(-10)) == self.d + self._object(50) - - def test_offsets_compare_equal(self): - offset1 = self._object() - offset2 = self._object() - assert not offset1 != offset2 - def test_roundtrip_pickle(self): def _check_roundtrip(obj): unpickled = tm.round_trip_pickle(obj) assert unpickled == obj - _check_roundtrip(self._object()) - _check_roundtrip(self._object(2)) - _check_roundtrip(self._object() * 2) + _check_roundtrip(self._offset()) + _check_roundtrip(self._offset(2)) + _check_roundtrip(self._offset() * 2) def test_copy(self): # GH 17452 - off = self._object(weekmask='Mon Wed Fri') + off = self._offset(weekmask='Mon Wed Fri') assert off == off.copy() class TestCustomBusinessMonthEnd(CustomBusinessMonthBase, Base): - _object = CBMonthEnd + _offset = CBMonthEnd def test_different_normalize_equals(self): # equivalent in this special case @@ -2032,7 +1985,7 @@ def test_datetimeindex(self): class TestCustomBusinessMonthBegin(CustomBusinessMonthBase, Base): - _object = CBMonthBegin + _offset = CBMonthBegin def test_different_normalize_equals(self): # equivalent in this special case @@ -2150,6 +2103,9 @@ def test_datetimeindex(self): class TestWeek(Base): _offset = Week + d = Timestamp(datetime(2008, 1, 2)) + offset1 = _offset() + offset2 = _offset(2) def test_repr(self): assert repr(Week(weekday=0)) == "<Week: weekday=0>" @@ -2157,9 +2113,11 @@ def test_repr(self): assert repr(Week(n=-2, weekday=0)) == "<-2 * Weeks: weekday=0>" def test_corner(self): - pytest.raises(ValueError, Week, weekday=7) - tm.assert_raises_regex( - ValueError, "Day must be", Week, weekday=-1) + with pytest.raises(ValueError): + Week(weekday=7) + + with pytest.raises(ValueError, match="Day must be"): + Week(weekday=-1) def test_isAnchored(self): assert Week(weekday=0).isAnchored() @@ -2204,38 +2162,37 @@ def test_offset(self, case): for base, expected in compat.iteritems(cases): assert_offset_equal(offset, base, expected) - def test_onOffset(self): - for weekday in range(7): - offset = Week(weekday=weekday) - - for day in range(1, 8): - date = datetime(2008, 1, day) + @pytest.mark.parametrize('weekday', range(7)) + def test_onOffset(self, weekday): + offset = Week(weekday=weekday) - if day % 7 == weekday: - expected = True - else: - expected = False - assert_onOffset(offset, date, expected) + for day in range(1, 8): + date = datetime(2008, 1, day) - def test_offsets_compare_equal(self): - # root cause of #456 - offset1 = Week() - offset2 = Week() - assert not offset1 != offset2 + if day % 7 == weekday: + expected = True + else: + expected = False + assert_onOffset(offset, date, expected) class TestWeekOfMonth(Base): _offset = WeekOfMonth + offset1 = _offset() + offset2 = _offset(2) def test_constructor(self): - tm.assert_raises_regex(ValueError, "^Week", WeekOfMonth, - n=1, week=4, weekday=0) - tm.assert_raises_regex(ValueError, "^Week", WeekOfMonth, - n=1, week=-1, weekday=0) - tm.assert_raises_regex(ValueError, "^Day", WeekOfMonth, - n=1, week=0, weekday=-1) - tm.assert_raises_regex(ValueError, "^Day", WeekOfMonth, - n=1, week=0, weekday=7) + with pytest.raises(ValueError, match="^Week"): + WeekOfMonth(n=1, week=4, weekday=0) + + with pytest.raises(ValueError, match="^Week"): + WeekOfMonth(n=1, week=-1, weekday=0) + + with pytest.raises(ValueError, match="^Day"): + WeekOfMonth(n=1, week=0, weekday=-1) + + with pytest.raises(ValueError, match="^Day"): + WeekOfMonth(n=1, week=0, weekday=-7) def test_repr(self): assert (repr(WeekOfMonth(weekday=1, week=2)) == @@ -2322,15 +2279,18 @@ def test_onOffset(self, case): class TestLastWeekOfMonth(Base): _offset = LastWeekOfMonth + offset1 = _offset() + offset2 = _offset(2) def test_constructor(self): - tm.assert_raises_regex(ValueError, "^N cannot be 0", - LastWeekOfMonth, n=0, weekday=1) + with pytest.raises(ValueError, match="^N cannot be 0"): + LastWeekOfMonth(n=0, weekday=1) + + with pytest.raises(ValueError, match="^Day"): + LastWeekOfMonth(n=1, weekday=-1) - tm.assert_raises_regex(ValueError, "^Day", LastWeekOfMonth, n=1, - weekday=-1) - tm.assert_raises_regex( - ValueError, "^Day", LastWeekOfMonth, n=1, weekday=7) + with pytest.raises(ValueError, match="^Day"): + LastWeekOfMonth(n=1, weekday=7) def test_offset(self): # Saturday @@ -2396,6 +2356,8 @@ def test_onOffset(self, case): class TestSemiMonthEnd(Base): _offset = SemiMonthEnd + offset1 = _offset() + offset2 = _offset(2) def test_offset_whole_year(self): dates = (datetime(2007, 12, 31), @@ -2566,6 +2528,8 @@ def test_vectorized_offset_addition(self, klass, assert_func): class TestSemiMonthBegin(Base): _offset = SemiMonthBegin + offset1 = _offset() + offset2 = _offset(2) def test_offset_whole_year(self): dates = (datetime(2007, 12, 15), @@ -2773,9 +2737,9 @@ def test_get_offset_name(self): def test_get_offset(): - with tm.assert_raises_regex(ValueError, _INVALID_FREQ_ERROR): + with pytest.raises(ValueError, match=_INVALID_FREQ_ERROR): get_offset('gibberish') - with tm.assert_raises_regex(ValueError, _INVALID_FREQ_ERROR): + with pytest.raises(ValueError, match=_INVALID_FREQ_ERROR): get_offset('QS-JAN-B') pairs = [ @@ -2793,7 +2757,7 @@ def test_get_offset(): def test_get_offset_legacy(): pairs = [('w@Sat', Week(weekday=5))] for name, expected in pairs: - with tm.assert_raises_regex(ValueError, _INVALID_FREQ_ERROR): + with pytest.raises(ValueError, match=_INVALID_FREQ_ERROR): get_offset(name)
There's more to do, but the diff is already pretty big as it is. There are a handful of test methods that are defined in 5-6 test classes. By moving those to the base class we a) get rid of duplicate code and b) run the tests for all (well, most) `DateOffset` subclasses.
https://api.github.com/repos/pandas-dev/pandas/pulls/21405
2018-06-10T02:57:10Z
2018-06-13T10:54:56Z
2018-06-13T10:54:56Z
2018-06-22T03:27:40Z
fix DateOffset eq to depend on normalize attr
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 68c1839221508..6d5e40d37c8df 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -91,7 +91,7 @@ Categorical Datetimelike ^^^^^^^^^^^^ -- +- Fixed bug where two :class:`DateOffset` objects with different ``normalize`` attributes could evaluate as equal (:issue:`21404`) - - diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 8bf0d9f915d04..6fd525f02f55c 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -564,11 +564,10 @@ def setup_method(self, method): self.offset2 = BDay(2) def test_different_normalize_equals(self): - # equivalent in this special case - offset = BDay() - offset2 = BDay() - offset2.normalize = True - assert offset == offset2 + # GH#21404 changed __eq__ to return False when `normalize` doesnt match + offset = self._offset() + offset2 = self._offset(normalize=True) + assert offset != offset2 def test_repr(self): assert repr(self.offset) == '<BusinessDay>' @@ -734,11 +733,10 @@ def test_constructor_errors(self): BusinessHour(start='14:00:05') def test_different_normalize_equals(self): - # equivalent in this special case + # GH#21404 changed __eq__ to return False when `normalize` doesnt match offset = self._offset() - offset2 = self._offset() - offset2.normalize = True - assert offset == offset2 + offset2 = self._offset(normalize=True) + assert offset != offset2 def test_repr(self): assert repr(self.offset1) == '<BusinessHour: BH=09:00-17:00>' @@ -1397,11 +1395,10 @@ def test_constructor_errors(self): CustomBusinessHour(start='14:00:05') def test_different_normalize_equals(self): - # equivalent in this special case + # GH#21404 changed __eq__ to return False when `normalize` doesnt match offset = self._offset() - offset2 = self._offset() - offset2.normalize = True - assert offset == offset2 + offset2 = self._offset(normalize=True) + assert offset != offset2 def test_repr(self): assert repr(self.offset1) == '<CustomBusinessHour: CBH=09:00-17:00>' @@ -1627,11 +1624,10 @@ def setup_method(self, method): self.offset2 = CDay(2) def test_different_normalize_equals(self): - # equivalent in this special case - offset = CDay() - offset2 = CDay() - offset2.normalize = True - assert offset == offset2 + # GH#21404 changed __eq__ to return False when `normalize` doesnt match + offset = self._offset() + offset2 = self._offset(normalize=True) + assert offset != offset2 def test_repr(self): assert repr(self.offset) == '<CustomBusinessDay>' @@ -1865,11 +1861,10 @@ class TestCustomBusinessMonthEnd(CustomBusinessMonthBase, Base): _offset = CBMonthEnd def test_different_normalize_equals(self): - # equivalent in this special case - offset = CBMonthEnd() - offset2 = CBMonthEnd() - offset2.normalize = True - assert offset == offset2 + # GH#21404 changed __eq__ to return False when `normalize` doesnt match + offset = self._offset() + offset2 = self._offset(normalize=True) + assert offset != offset2 def test_repr(self): assert repr(self.offset) == '<CustomBusinessMonthEnd>' @@ -1982,11 +1977,10 @@ class TestCustomBusinessMonthBegin(CustomBusinessMonthBase, Base): _offset = CBMonthBegin def test_different_normalize_equals(self): - # equivalent in this special case - offset = CBMonthBegin() - offset2 = CBMonthBegin() - offset2.normalize = True - assert offset == offset2 + # GH#21404 changed __eq__ to return False when `normalize` doesnt match + offset = self._offset() + offset2 = self._offset(normalize=True) + assert offset != offset2 def test_repr(self): assert repr(self.offset) == '<CustomBusinessMonthBegin>' diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index a5a983bf94bb8..99f97d8fc7bc0 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -290,7 +290,7 @@ def _params(self): all_paras = self.__dict__.copy() if 'holidays' in all_paras and not all_paras['holidays']: all_paras.pop('holidays') - exclude = ['kwds', 'name', 'normalize', 'calendar'] + exclude = ['kwds', 'name', 'calendar'] attrs = [(k, v) for k, v in all_paras.items() if (k not in exclude) and (k[0] != '_')] attrs = sorted(set(attrs))
This has a bullet point in #18854 but doesn't appear to have its own issue. Current: ``` now = pd.Timestamp.now() off = pd.offsets.Week(n=1, normalize=False) normed = pd.offsets.Week(n=1, normalize=True) >>> now + off == now + normed False >>> off == normed # PR changes this comparison to False True ``` - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21404
2018-06-10T02:09:11Z
2018-06-13T19:59:20Z
2018-06-13T19:59:20Z
2018-06-22T03:27:33Z
DOC: isin() docstring change DataFrame to pd.DataFrame
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ca572e2e56b6c..21e3cfcdd195e 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -7283,11 +7283,11 @@ def isin(self, values): When ``values`` is a Series or DataFrame: >>> df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'f']}) - >>> other = DataFrame({'A': [1, 3, 3, 2], 'B': ['e', 'f', 'f', 'e']}) - >>> df.isin(other) + >>> df2 = pd.DataFrame({'A': [1, 3, 3, 2], 'B': ['e', 'f', 'f', 'e']}) + >>> df.isin(df2) A B 0 True False - 1 False False # Column A in `other` has a 3, but not at index 1. + 1 False False # Column A in `df2` has a 3, but not at index 1. 2 True True """ if isinstance(values, dict):
isin() docstring change DataFrame to pd.DataFrame
https://api.github.com/repos/pandas-dev/pandas/pulls/21403
2018-06-09T20:49:25Z
2018-06-13T12:12:38Z
2018-06-13T12:12:38Z
2018-06-13T12:13:27Z
ENH: to_sql() add parameter "method" to control insertions method (#8…
diff --git a/doc/source/io.rst b/doc/source/io.rst index 9aff1e54d8e98..fa6a8b1d01530 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -4989,6 +4989,54 @@ with respect to the timezone. timezone aware or naive. When reading ``TIMESTAMP WITH TIME ZONE`` types, pandas will convert the data to UTC. +.. _io.sql.method: + +Insertion Method +++++++++++++++++ + +.. versionadded:: 0.24.0 + +The parameter ``method`` controls the SQL insertion clause used. +Possible values are: + +- ``None``: Uses standard SQL ``INSERT`` clause (one per row). +- ``'multi'``: Pass multiple values in a single ``INSERT`` clause. + It uses a *special* SQL syntax not supported by all backends. + This usually provides better performance for analytic databases + like *Presto* and *Redshift*, but has worse performance for + traditional SQL backend if the table contains many columns. + For more information check the SQLAlchemy `documention + <http://docs.sqlalchemy.org/en/latest/core/dml.html#sqlalchemy.sql.expression.Insert.values.params.*args>`__. +- callable with signature ``(pd_table, conn, keys, data_iter)``: + This can be used to implement a more performant insertion method based on + specific backend dialect features. + +Example of a callable using PostgreSQL `COPY clause +<https://www.postgresql.org/docs/current/static/sql-copy.html>`__:: + + # Alternative to_sql() *method* for DBs that support COPY FROM + import csv + from io import StringIO + + def psql_insert_copy(table, conn, keys, data_iter): + # gets a DBAPI connection that can provide a cursor + dbapi_conn = conn.connection + with dbapi_conn.cursor() as cur: + s_buf = StringIO() + writer = csv.writer(s_buf) + writer.writerows(data_iter) + s_buf.seek(0) + + columns = ', '.join('"{}"'.format(k) for k in keys) + if table.schema: + table_name = '{}.{}'.format(table.schema, table.name) + else: + table_name = table.name + + sql = 'COPY {} ({}) FROM STDIN WITH CSV'.format( + table_name, columns) + cur.copy_expert(sql=sql, file=s_buf) + Reading Tables '''''''''''''' diff --git a/doc/source/whatsnew/v0.24.0.rst b/doc/source/whatsnew/v0.24.0.rst index 018820b09dba4..6cb08afadec31 100644 --- a/doc/source/whatsnew/v0.24.0.rst +++ b/doc/source/whatsnew/v0.24.0.rst @@ -373,6 +373,7 @@ Other Enhancements - :meth:`DataFrame.between_time` and :meth:`DataFrame.at_time` have gained the an ``axis`` parameter (:issue:`8839`) - The ``scatter_matrix``, ``andrews_curves``, ``parallel_coordinates``, ``lag_plot``, ``autocorrelation_plot``, ``bootstrap_plot``, and ``radviz`` plots from the ``pandas.plotting`` module are now accessible from calling :meth:`DataFrame.plot` (:issue:`11978`) - :class:`IntervalIndex` has gained the :attr:`~IntervalIndex.is_overlapping` attribute to indicate if the ``IntervalIndex`` contains any overlapping intervals (:issue:`23309`) +- :func:`pandas.DataFrame.to_sql` has gained the ``method`` argument to control SQL insertion clause. See the :ref:`insertion method <io.sql.method>` section in the documentation. (:issue:`8953`) .. _whatsnew_0240.api_breaking: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 63d9b5265cdc7..3c28fef024b79 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -2386,7 +2386,7 @@ def to_msgpack(self, path_or_buf=None, encoding='utf-8', **kwargs): **kwargs) def to_sql(self, name, con, schema=None, if_exists='fail', index=True, - index_label=None, chunksize=None, dtype=None): + index_label=None, chunksize=None, dtype=None, method=None): """ Write records stored in a DataFrame to a SQL database. @@ -2424,6 +2424,17 @@ def to_sql(self, name, con, schema=None, if_exists='fail', index=True, Specifying the datatype for columns. The keys should be the column names and the values should be the SQLAlchemy types or strings for the sqlite3 legacy mode. + method : {None, 'multi', callable}, default None + Controls the SQL insertion clause used: + + * None : Uses standard SQL ``INSERT`` clause (one per row). + * 'multi': Pass multiple values in a single ``INSERT`` clause. + * callable with signature ``(pd_table, conn, keys, data_iter)``. + + Details and a sample callable implementation can be found in the + section :ref:`insert method <io.sql.method>`. + + .. versionadded:: 0.24.0 Raises ------ @@ -2505,7 +2516,7 @@ def to_sql(self, name, con, schema=None, if_exists='fail', index=True, from pandas.io import sql sql.to_sql(self, name, con, schema=schema, if_exists=if_exists, index=index, index_label=index_label, chunksize=chunksize, - dtype=dtype) + dtype=dtype, method=method) def to_pickle(self, path, compression='infer', protocol=pkl.HIGHEST_PROTOCOL): diff --git a/pandas/io/sql.py b/pandas/io/sql.py index e54d29148c6d0..6093c6c3fd0fc 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -8,6 +8,7 @@ from contextlib import contextmanager from datetime import date, datetime, time +from functools import partial import re import warnings @@ -395,7 +396,7 @@ def read_sql(sql, con, index_col=None, coerce_float=True, params=None, def to_sql(frame, name, con, schema=None, if_exists='fail', index=True, - index_label=None, chunksize=None, dtype=None): + index_label=None, chunksize=None, dtype=None, method=None): """ Write records stored in a DataFrame to a SQL database. @@ -429,6 +430,17 @@ def to_sql(frame, name, con, schema=None, if_exists='fail', index=True, Optional specifying the datatype for columns. The SQL type should be a SQLAlchemy type, or a string for sqlite3 fallback connection. If all columns are of the same type, one single value can be used. + method : {None, 'multi', callable}, default None + Controls the SQL insertion clause used: + + - None : Uses standard SQL ``INSERT`` clause (one per row). + - 'multi': Pass multiple values in a single ``INSERT`` clause. + - callable with signature ``(pd_table, conn, keys, data_iter)``. + + Details and a sample callable implementation can be found in the + section :ref:`insert method <io.sql.method>`. + + .. versionadded:: 0.24.0 """ if if_exists not in ('fail', 'replace', 'append'): raise ValueError("'{0}' is not valid for if_exists".format(if_exists)) @@ -443,7 +455,7 @@ def to_sql(frame, name, con, schema=None, if_exists='fail', index=True, pandas_sql.to_sql(frame, name, if_exists=if_exists, index=index, index_label=index_label, schema=schema, - chunksize=chunksize, dtype=dtype) + chunksize=chunksize, dtype=dtype, method=method) def has_table(table_name, con, schema=None): @@ -568,8 +580,29 @@ def create(self): else: self._execute_create() - def insert_statement(self): - return self.table.insert() + def _execute_insert(self, conn, keys, data_iter): + """Execute SQL statement inserting data + + Parameters + ---------- + conn : sqlalchemy.engine.Engine or sqlalchemy.engine.Connection + keys : list of str + Column names + data_iter : generator of list + Each item contains a list of values to be inserted + """ + data = [dict(zip(keys, row)) for row in data_iter] + conn.execute(self.table.insert(), data) + + def _execute_insert_multi(self, conn, keys, data_iter): + """Alternative to _execute_insert for DBs support multivalue INSERT. + + Note: multi-value insert is usually faster for analytics DBs + and tables containing a few columns + but performance degrades quickly with increase of columns. + """ + data = [dict(zip(keys, row)) for row in data_iter] + conn.execute(self.table.insert(data)) def insert_data(self): if self.index is not None: @@ -612,11 +645,18 @@ def insert_data(self): return column_names, data_list - def _execute_insert(self, conn, keys, data_iter): - data = [dict(zip(keys, row)) for row in data_iter] - conn.execute(self.insert_statement(), data) + def insert(self, chunksize=None, method=None): + + # set insert method + if method is None: + exec_insert = self._execute_insert + elif method == 'multi': + exec_insert = self._execute_insert_multi + elif callable(method): + exec_insert = partial(method, self) + else: + raise ValueError('Invalid parameter `method`: {}'.format(method)) - def insert(self, chunksize=None): keys, data_list = self.insert_data() nrows = len(self.frame) @@ -639,7 +679,7 @@ def insert(self, chunksize=None): break chunk_iter = zip(*[arr[start_i:end_i] for arr in data_list]) - self._execute_insert(conn, keys, chunk_iter) + exec_insert(conn, keys, chunk_iter) def _query_iterator(self, result, chunksize, columns, coerce_float=True, parse_dates=None): @@ -1085,7 +1125,8 @@ def read_query(self, sql, index_col=None, coerce_float=True, read_sql = read_query def to_sql(self, frame, name, if_exists='fail', index=True, - index_label=None, schema=None, chunksize=None, dtype=None): + index_label=None, schema=None, chunksize=None, dtype=None, + method=None): """ Write records stored in a DataFrame to a SQL database. @@ -1115,7 +1156,17 @@ def to_sql(self, frame, name, if_exists='fail', index=True, Optional specifying the datatype for columns. The SQL type should be a SQLAlchemy type. If all columns are of the same type, one single value can be used. + method : {None', 'multi', callable}, default None + Controls the SQL insertion clause used: + + * None : Uses standard SQL ``INSERT`` clause (one per row). + * 'multi': Pass multiple values in a single ``INSERT`` clause. + * callable with signature ``(pd_table, conn, keys, data_iter)``. + + Details and a sample callable implementation can be found in the + section :ref:`insert method <io.sql.method>`. + .. versionadded:: 0.24.0 """ if dtype and not is_dict_like(dtype): dtype = {col_name: dtype for col_name in frame} @@ -1131,7 +1182,7 @@ def to_sql(self, frame, name, if_exists='fail', index=True, if_exists=if_exists, index_label=index_label, schema=schema, dtype=dtype) table.create() - table.insert(chunksize) + table.insert(chunksize, method=method) if (not name.isdigit() and not name.islower()): # check for potentially case sensitivity issues (GH7815) # Only check when name is not a number and name is not lower case @@ -1442,7 +1493,8 @@ def _fetchall_as_list(self, cur): return result def to_sql(self, frame, name, if_exists='fail', index=True, - index_label=None, schema=None, chunksize=None, dtype=None): + index_label=None, schema=None, chunksize=None, dtype=None, + method=None): """ Write records stored in a DataFrame to a SQL database. @@ -1471,7 +1523,17 @@ def to_sql(self, frame, name, if_exists='fail', index=True, Optional specifying the datatype for columns. The SQL type should be a string. If all columns are of the same type, one single value can be used. + method : {None, 'multi', callable}, default None + Controls the SQL insertion clause used: + + * None : Uses standard SQL ``INSERT`` clause (one per row). + * 'multi': Pass multiple values in a single ``INSERT`` clause. + * callable with signature ``(pd_table, conn, keys, data_iter)``. + + Details and a sample callable implementation can be found in the + section :ref:`insert method <io.sql.method>`. + .. versionadded:: 0.24.0 """ if dtype and not is_dict_like(dtype): dtype = {col_name: dtype for col_name in frame} @@ -1486,7 +1548,7 @@ def to_sql(self, frame, name, if_exists='fail', index=True, if_exists=if_exists, index_label=index_label, dtype=dtype) table.create() - table.insert(chunksize) + table.insert(chunksize, method) def has_table(self, name, schema=None): # TODO(wesm): unused? diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index eeeb55cb8e70c..c346103a70c98 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -375,12 +375,16 @@ def _read_sql_iris_named_parameter(self): iris_frame = self.pandasSQL.read_query(query, params=params) self._check_iris_loaded_frame(iris_frame) - def _to_sql(self): + def _to_sql(self, method=None): self.drop_table('test_frame1') - self.pandasSQL.to_sql(self.test_frame1, 'test_frame1') + self.pandasSQL.to_sql(self.test_frame1, 'test_frame1', method=method) assert self.pandasSQL.has_table('test_frame1') + num_entries = len(self.test_frame1) + num_rows = self._count_rows('test_frame1') + assert num_rows == num_entries + # Nuke table self.drop_table('test_frame1') @@ -434,6 +438,25 @@ def _to_sql_append(self): assert num_rows == num_entries self.drop_table('test_frame1') + def _to_sql_method_callable(self): + check = [] # used to double check function below is really being used + + def sample(pd_table, conn, keys, data_iter): + check.append(1) + data = [dict(zip(keys, row)) for row in data_iter] + conn.execute(pd_table.table.insert(), data) + self.drop_table('test_frame1') + + self.pandasSQL.to_sql(self.test_frame1, 'test_frame1', method=sample) + assert self.pandasSQL.has_table('test_frame1') + + assert check == [1] + num_entries = len(self.test_frame1) + num_rows = self._count_rows('test_frame1') + assert num_rows == num_entries + # Nuke table + self.drop_table('test_frame1') + def _roundtrip(self): self.drop_table('test_frame_roundtrip') self.pandasSQL.to_sql(self.test_frame1, 'test_frame_roundtrip') @@ -1193,7 +1216,7 @@ def setup_connect(self): pytest.skip( "Can't connect to {0} server".format(self.flavor)) - def test_aread_sql(self): + def test_read_sql(self): self._read_sql_iris() def test_read_sql_parameter(self): @@ -1217,6 +1240,12 @@ def test_to_sql_replace(self): def test_to_sql_append(self): self._to_sql_append() + def test_to_sql_method_multi(self): + self._to_sql(method='multi') + + def test_to_sql_method_callable(self): + self._to_sql_method_callable() + def test_create_table(self): temp_conn = self.connect() temp_frame = DataFrame( @@ -1930,6 +1959,36 @@ def test_schema_support(self): res2 = pdsql.read_table('test_schema_other2') tm.assert_frame_equal(res1, res2) + def test_copy_from_callable_insertion_method(self): + # GH 8953 + # Example in io.rst found under _io.sql.method + # not available in sqlite, mysql + def psql_insert_copy(table, conn, keys, data_iter): + # gets a DBAPI connection that can provide a cursor + dbapi_conn = conn.connection + with dbapi_conn.cursor() as cur: + s_buf = compat.StringIO() + writer = csv.writer(s_buf) + writer.writerows(data_iter) + s_buf.seek(0) + + columns = ', '.join('"{}"'.format(k) for k in keys) + if table.schema: + table_name = '{}.{}'.format(table.schema, table.name) + else: + table_name = table.name + + sql_query = 'COPY {} ({}) FROM STDIN WITH CSV'.format( + table_name, columns) + cur.copy_expert(sql=sql_query, file=s_buf) + + expected = DataFrame({'col1': [1, 2], 'col2': [0.1, 0.2], + 'col3': ['a', 'n']}) + expected.to_sql('test_copy_insert', self.conn, index=False, + method=psql_insert_copy) + result = sql.read_sql_table('test_copy_insert', self.conn) + tm.assert_frame_equal(result, expected) + @pytest.mark.single class TestMySQLAlchemy(_TestMySQLAlchemy, _TestSQLAlchemy):
…953) - [x] closes #8953 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21401
2018-06-09T11:01:04Z
2018-12-28T21:03:13Z
2018-12-28T21:03:13Z
2019-01-04T11:20:54Z
MAINT: Deprecate encoding from stata reader/writer
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index de985d4db5fa3..68c1839221508 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -45,7 +45,7 @@ Other API Changes Deprecations ~~~~~~~~~~~~ -- +- :meth:`DataFrame.to_stata`, :meth:`read_stata`, :class:`StataReader` and :class:`StataWriter` have deprecated the ``encoding`` argument. The encoding of a Stata dta file is determined by the file type and cannot be changed (:issue:`21244`). - - diff --git a/pandas/core/frame.py b/pandas/core/frame.py index ca572e2e56b6c..0985de3126c5a 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -80,7 +80,8 @@ from pandas.compat import PY36 from pandas.compat.numpy import function as nv from pandas.util._decorators import (Appender, Substitution, - rewrite_axis_style_signature) + rewrite_axis_style_signature, + deprecate_kwarg) from pandas.util._validators import (validate_bool_kwarg, validate_axis_style_args) @@ -1764,6 +1765,7 @@ def to_excel(self, excel_writer, sheet_name='Sheet1', na_rep='', startcol=startcol, freeze_panes=freeze_panes, engine=engine) + @deprecate_kwarg(old_arg_name='encoding', new_arg_name=None) def to_stata(self, fname, convert_dates=None, write_index=True, encoding="latin-1", byteorder=None, time_stamp=None, data_label=None, variable_labels=None, version=114, @@ -1869,9 +1871,8 @@ def to_stata(self, fname, convert_dates=None, write_index=True, kwargs['convert_strl'] = convert_strl writer = statawriter(fname, self, convert_dates=convert_dates, - encoding=encoding, byteorder=byteorder, - time_stamp=time_stamp, data_label=data_label, - write_index=write_index, + byteorder=byteorder, time_stamp=time_stamp, + data_label=data_label, write_index=write_index, variable_labels=variable_labels, **kwargs) writer.write_file() diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 8584e1f0e3f14..b2a5bec2a4837 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -33,11 +33,7 @@ from pandas.core.series import Series from pandas.io.common import (get_filepath_or_buffer, BaseIterator, _stringify_path) -from pandas.util._decorators import Appender -from pandas.util._decorators import deprecate_kwarg - -VALID_ENCODINGS = ('ascii', 'us-ascii', 'latin-1', 'latin_1', 'iso-8859-1', - 'iso8859-1', '8859', 'cp819', 'latin', 'latin1', 'L1') +from pandas.util._decorators import Appender, deprecate_kwarg _version_error = ("Version of given Stata file is not 104, 105, 108, " "111 (Stata 7SE), 113 (Stata 8/9), 114 (Stata 10/11), " @@ -169,6 +165,7 @@ @Appender(_read_stata_doc) +@deprecate_kwarg(old_arg_name='encoding', new_arg_name=None) @deprecate_kwarg(old_arg_name='index', new_arg_name='index_col') def read_stata(filepath_or_buffer, convert_dates=True, convert_categoricals=True, encoding=None, index_col=None, @@ -952,6 +949,7 @@ def __init__(self): class StataReader(StataParser, BaseIterator): __doc__ = _stata_reader_doc + @deprecate_kwarg(old_arg_name='encoding', new_arg_name=None) @deprecate_kwarg(old_arg_name='index', new_arg_name='index_col') def __init__(self, path_or_buf, convert_dates=True, convert_categoricals=True, index_col=None, @@ -970,7 +968,7 @@ def __init__(self, path_or_buf, convert_dates=True, self._preserve_dtypes = preserve_dtypes self._columns = columns self._order_categoricals = order_categoricals - self._encoding = encoding + self._encoding = None self._chunksize = chunksize # State variables for the file @@ -1962,17 +1960,14 @@ class StataWriter(StataParser): _max_string_length = 244 + @deprecate_kwarg(old_arg_name='encoding', new_arg_name=None) def __init__(self, fname, data, convert_dates=None, write_index=True, encoding="latin-1", byteorder=None, time_stamp=None, data_label=None, variable_labels=None): super(StataWriter, self).__init__() self._convert_dates = {} if convert_dates is None else convert_dates self._write_index = write_index - if encoding is not None: - if encoding not in VALID_ENCODINGS: - raise ValueError('Unknown encoding. Only latin-1 and ascii ' - 'supported.') - self._encoding = encoding + self._encoding = 'latin-1' self._time_stamp = time_stamp self._data_label = data_label self._variable_labels = variable_labels @@ -2731,6 +2726,7 @@ class StataWriter117(StataWriter): _max_string_length = 2045 + @deprecate_kwarg(old_arg_name='encoding', new_arg_name=None) def __init__(self, fname, data, convert_dates=None, write_index=True, encoding="latin-1", byteorder=None, time_stamp=None, data_label=None, variable_labels=None, convert_strl=None): @@ -2738,9 +2734,10 @@ def __init__(self, fname, data, convert_dates=None, write_index=True, self._convert_strl = [] if convert_strl is None else convert_strl[:] super(StataWriter117, self).__init__(fname, data, convert_dates, - write_index, encoding, byteorder, - time_stamp, data_label, - variable_labels) + write_index, byteorder=byteorder, + time_stamp=time_stamp, + data_label=data_label, + variable_labels=variable_labels) self._map = None self._strl_blob = None diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index e5585902a9dd6..bfb72be80400e 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -361,7 +361,8 @@ def test_encoding(self, version): # GH 4626, proper encoding handling raw = read_stata(self.dta_encoding) - encoded = read_stata(self.dta_encoding, encoding="latin-1") + with tm.assert_produces_warning(FutureWarning): + encoded = read_stata(self.dta_encoding, encoding='latin-1') result = encoded.kreis1849[0] expected = raw.kreis1849[0] @@ -369,8 +370,9 @@ def test_encoding(self, version): assert isinstance(result, compat.string_types) with tm.ensure_clean() as path: - encoded.to_stata(path, encoding='latin-1', - write_index=False, version=version) + with tm.assert_produces_warning(FutureWarning): + encoded.to_stata(path, write_index=False, version=version, + encoding='latin-1') reread_encoded = read_stata(path) tm.assert_frame_equal(encoded, reread_encoded) @@ -1349,13 +1351,6 @@ def test_out_of_range_float(self): assert 'ColumnTooBig' in cm.exception assert 'infinity' in cm.exception - def test_invalid_encoding(self): - # GH15723, validate encoding - original = self.read_csv(self.csv3) - with pytest.raises(ValueError): - with tm.ensure_clean() as path: - original.to_stata(path, encoding='utf-8') - def test_path_pathlib(self): df = tm.makeDataFrame() df.index.name = 'index'
Deprecate the encoding parameter from all Stata reading and writing methods and classes. The encoding depends only on the file format and cannot be changed by users. - [X] closes #21244 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21400
2018-06-09T10:22:35Z
2018-06-12T00:05:45Z
2018-06-12T00:05:45Z
2018-09-20T15:49:38Z
DOC: Loading sphinxcontrib.spelling to sphinx only if it's available (#21396)
diff --git a/ci/environment-dev.yaml b/ci/environment-dev.yaml index f9f9208519d61..5733857b55dd4 100644 --- a/ci/environment-dev.yaml +++ b/ci/environment-dev.yaml @@ -13,3 +13,4 @@ dependencies: - pytz - setuptools>=24.2.0 - sphinx + - sphinxcontrib-spelling diff --git a/ci/requirements_dev.txt b/ci/requirements_dev.txt index 3430e778a4573..83ee30b52071d 100644 --- a/ci/requirements_dev.txt +++ b/ci/requirements_dev.txt @@ -9,3 +9,4 @@ python-dateutil>=2.5.0 pytz setuptools>=24.2.0 sphinx +sphinxcontrib-spelling \ No newline at end of file diff --git a/doc/source/conf.py b/doc/source/conf.py index 97081bec863b7..909bd5a80b76e 100644 --- a/doc/source/conf.py +++ b/doc/source/conf.py @@ -16,9 +16,11 @@ import re import inspect import importlib -from sphinx.ext.autosummary import _import_by_name +import logging import warnings +from sphinx.ext.autosummary import _import_by_name +logger = logging.getLogger(__name__) try: raw_input # Python 2 @@ -73,9 +75,16 @@ 'sphinx.ext.ifconfig', 'sphinx.ext.linkcode', 'nbsphinx', - 'sphinxcontrib.spelling' ] +try: + import sphinxcontrib.spelling +except ImportError as err: + logger.warn(('sphinxcontrib.spelling failed to import with error "{}". ' + '`spellcheck` command is not available.'.format(err))) +else: + extensions.append('sphinxcontrib.spelling') + exclude_patterns = ['**.ipynb_checkpoints'] spelling_word_list_filename = ['spelling_wordlist.txt', 'names_wordlist.txt']
- [X] closes #21396 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry I think the optional dependencies go directly into the `.txt` files for pip and conda, and not into the yaml file. Please correct me if I'm wrong. Seems like besides `sphinxcontrib-spelling`, a binary program `enchant` is required, and it's not available in conda for what I've seen. Not sure what's the right approach for it.
https://api.github.com/repos/pandas-dev/pandas/pulls/21397
2018-06-08T23:11:07Z
2018-06-12T07:57:04Z
2018-06-12T07:57:04Z
2018-06-20T15:22:33Z
Bugfix timedelta notimplemented eq
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 7a10e8d1073d0..308748a1856d8 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -193,6 +193,7 @@ Other Enhancements - :func:`~DataFrame.to_csv`, :func:`~Series.to_csv`, :func:`~DataFrame.to_json`, and :func:`~Series.to_json` now support ``compression='infer'`` to infer compression based on filename extension (:issue:`15008`). The default compression for ``to_csv``, ``to_json``, and ``to_pickle`` methods has been updated to ``'infer'`` (:issue:`22004`). - :func:`to_timedelta` now supports iso-formated timedelta strings (:issue:`21877`) +- Comparing :class:`Timedelta` with unknown types now return ``NotImplemented`` instead of ``False`` (:issue:`20829`) - :class:`Series` and :class:`DataFrame` now support :class:`Iterable` in constructor (:issue:`2193`) - :class:`DatetimeIndex` gained :attr:`DatetimeIndex.timetz` attribute. Returns local time with timezone information. (:issue:`21358`) - :meth:`round`, :meth:`ceil`, and meth:`floor` for :class:`DatetimeIndex` and :class:`Timestamp` now support an ``ambiguous`` argument for handling datetimes that are rounded to ambiguous times (:issue:`18946`) @@ -1009,7 +1010,7 @@ Timedelta - Bug in :class:`TimedeltaIndex` incorrectly allowing indexing with ``Timestamp`` object (:issue:`20464`) - Fixed bug where subtracting :class:`Timedelta` from an object-dtyped array would raise ``TypeError`` (:issue:`21980`) - Fixed bug in adding a :class:`DataFrame` with all-`timedelta64[ns]` dtypes to a :class:`DataFrame` with all-integer dtypes returning incorrect results instead of raising ``TypeError`` (:issue:`22696`) -- + Timezones ^^^^^^^^^ diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index 9c8be1901d1dc..b5b3abd01328c 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -724,27 +724,12 @@ cdef class _Timedelta(timedelta): if is_timedelta64_object(other): other = Timedelta(other) else: - if op == Py_EQ: - return False - elif op == Py_NE: - return True - - # only allow ==, != ops - raise TypeError('Cannot compare type {cls} with ' - 'type {other}' - .format(cls=type(self).__name__, - other=type(other).__name__)) + return NotImplemented if util.is_array(other): return PyObject_RichCompare(np.array([self]), other, op) return PyObject_RichCompare(other, self, reverse_ops[op]) else: - if op == Py_EQ: - return False - elif op == Py_NE: - return True - raise TypeError('Cannot compare type {cls} with type {other}' - .format(cls=type(self).__name__, - other=type(other).__name__)) + return NotImplemented return cmp_scalar(self.value, ots.value, op) diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index 017606dc42d59..0cac1119f76b5 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -42,8 +42,10 @@ def test_ops_error_str(self): with pytest.raises(TypeError): left + right - with pytest.raises(TypeError): - left > right + # GH 20829: python 2 comparison naturally does not raise TypeError + if compat.PY3: + with pytest.raises(TypeError): + left > right assert not left == right assert left != right @@ -103,6 +105,55 @@ def test_compare_timedelta_ndarray(self): expected = np.array([False, False]) tm.assert_numpy_array_equal(result, expected) + def test_compare_custom_object(self): + """Make sure non supported operations on Timedelta returns NonImplemented + and yields to other operand (GH20829).""" + class CustomClass(object): + + def __init__(self, cmp_result=None): + self.cmp_result = cmp_result + + def generic_result(self): + if self.cmp_result is None: + return NotImplemented + else: + return self.cmp_result + + def __eq__(self, other): + return self.generic_result() + + def __gt__(self, other): + return self.generic_result() + + t = Timedelta('1s') + + assert not (t == "string") + assert not (t == 1) + assert not (t == CustomClass()) + assert not (t == CustomClass(cmp_result=False)) + + assert t < CustomClass(cmp_result=True) + assert not (t < CustomClass(cmp_result=False)) + + assert t == CustomClass(cmp_result=True) + + @pytest.mark.skipif(compat.PY2, + reason="python 2 does not raise TypeError for \ + comparisons of different types") + @pytest.mark.parametrize("val", [ + "string", 1]) + def test_compare_unknown_type(self, val): + # GH20829 + t = Timedelta('1s') + with pytest.raises(TypeError): + t >= val + with pytest.raises(TypeError): + t > val + with pytest.raises(TypeError): + t <= val + with pytest.raises(TypeError): + t < val + class TestTimedeltas(object):
- [x] closes #20829 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21394
2018-06-08T20:21:47Z
2018-10-24T16:25:39Z
2018-10-24T16:25:38Z
2018-10-26T08:34:41Z
TST: adding test cases for verifying correct values shown by pivot_table() #21378
diff --git a/pandas/tests/reshape/test_pivot.py b/pandas/tests/reshape/test_pivot.py index 3ec60d50f2792..ca95dde1a20c9 100644 --- a/pandas/tests/reshape/test_pivot.py +++ b/pandas/tests/reshape/test_pivot.py @@ -161,6 +161,24 @@ def test_pivot_with_non_observable_dropna(self, dropna): tm.assert_frame_equal(result, expected) + # gh-21378 + df = pd.DataFrame( + {'A': pd.Categorical(['left', 'low', 'high', 'low', 'high'], + categories=['low', 'high', 'left'], + ordered=True), + 'B': range(5)}) + + result = df.pivot_table(index='A', values='B', dropna=dropna) + expected = pd.DataFrame( + {'B': [2, 3, 0]}, + index=pd.Index( + pd.Categorical.from_codes([0, 1, 2], + categories=['low', 'high', 'left'], + ordered=True), + name='A')) + + tm.assert_frame_equal(result, expected) + def test_pass_array(self): result = self.data.pivot_table( 'D', index=self.data.A, columns=self.data.C)
BUG: Incorrect values shown by pivot_table() #21378 - [x] closes #21378 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Just added a new test to verify the included patch in `master` branch
https://api.github.com/repos/pandas-dev/pandas/pulls/21393
2018-06-08T19:31:00Z
2018-06-15T17:33:36Z
2018-06-15T17:33:35Z
2018-06-15T17:33:43Z
Release 0.23.1 backports part I
diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py index ae1d7029217a4..5464e7cba22c3 100644 --- a/asv_bench/benchmarks/categoricals.py +++ b/asv_bench/benchmarks/categoricals.py @@ -173,3 +173,23 @@ def setup(self, dtype): def time_isin_categorical(self, dtype): self.series.isin(self.sample) + + +class IsMonotonic(object): + + def setup(self): + N = 1000 + self.c = pd.CategoricalIndex(list('a' * N + 'b' * N + 'c' * N)) + self.s = pd.Series(self.c) + + def time_categorical_index_is_monotonic_increasing(self): + self.c.is_monotonic_increasing + + def time_categorical_index_is_monotonic_decreasing(self): + self.c.is_monotonic_decreasing + + def time_categorical_series_is_monotonic_increasing(self): + self.s.is_monotonic_increasing + + def time_categorical_series_is_monotonic_decreasing(self): + self.s.is_monotonic_decreasing diff --git a/ci/travis-36.yaml b/ci/travis-36.yaml index fe057e714761e..006276ba1a65f 100644 --- a/ci/travis-36.yaml +++ b/ci/travis-36.yaml @@ -18,12 +18,10 @@ dependencies: - numexpr - numpy - openpyxl - - pandas-datareader - psycopg2 - pyarrow - pymysql - pytables - - python-dateutil - python-snappy - python=3.6* - pytz @@ -45,3 +43,5 @@ dependencies: - pip: - brotlipy - coverage + - pandas-datareader + - python-dateutil diff --git a/doc/source/advanced.rst b/doc/source/advanced.rst index c81842d3d9212..ec517d3e07bdf 100644 --- a/doc/source/advanced.rst +++ b/doc/source/advanced.rst @@ -924,6 +924,55 @@ bins, with ``NaN`` representing a missing value similar to other dtypes. pd.cut([0, 3, 5, 1], bins=c.categories) + +Generating Ranges of Intervals +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +If we need intervals on a regular frequency, we can use the :func:`interval_range` function +to create an ``IntervalIndex`` using various combinations of ``start``, ``end``, and ``periods``. +The default frequency for ``interval_range`` is a 1 for numeric intervals, and calendar day for +datetime-like intervals: + +.. ipython:: python + + pd.interval_range(start=0, end=5) + + pd.interval_range(start=pd.Timestamp('2017-01-01'), periods=4) + + pd.interval_range(end=pd.Timedelta('3 days'), periods=3) + +The ``freq`` parameter can used to specify non-default frequencies, and can utilize a variety +of :ref:`frequency aliases <timeseries.offset_aliases>` with datetime-like intervals: + +.. ipython:: python + + pd.interval_range(start=0, periods=5, freq=1.5) + + pd.interval_range(start=pd.Timestamp('2017-01-01'), periods=4, freq='W') + + pd.interval_range(start=pd.Timedelta('0 days'), periods=3, freq='9H') + +Additionally, the ``closed`` parameter can be used to specify which side(s) the intervals +are closed on. Intervals are closed on the right side by default. + +.. ipython:: python + + pd.interval_range(start=0, end=4, closed='both') + + pd.interval_range(start=0, end=4, closed='neither') + +.. versionadded:: 0.23.0 + +Specifying ``start``, ``end``, and ``periods`` will generate a range of evenly spaced +intervals from ``start`` to ``end`` inclusively, with ``periods`` number of elements +in the resulting ``IntervalIndex``: + +.. ipython:: python + + pd.interval_range(start=0, end=6, periods=4) + + pd.interval_range(pd.Timestamp('2018-01-01'), pd.Timestamp('2018-02-28'), periods=3) + Miscellaneous indexing FAQ -------------------------- diff --git a/doc/source/timedeltas.rst b/doc/source/timedeltas.rst index 5f3a01f0725d4..745810704f665 100644 --- a/doc/source/timedeltas.rst +++ b/doc/source/timedeltas.rst @@ -352,8 +352,8 @@ You can convert a ``Timedelta`` to an `ISO 8601 Duration`_ string with the TimedeltaIndex -------------- -To generate an index with time delta, you can use either the ``TimedeltaIndex`` or -the ``timedelta_range`` constructor. +To generate an index with time delta, you can use either the :class:`TimedeltaIndex` or +the :func:`timedelta_range` constructor. Using ``TimedeltaIndex`` you can pass string-like, ``Timedelta``, ``timedelta``, or ``np.timedelta64`` objects. Passing ``np.nan/pd.NaT/nat`` will represent missing values. @@ -363,13 +363,47 @@ or ``np.timedelta64`` objects. Passing ``np.nan/pd.NaT/nat`` will represent miss pd.TimedeltaIndex(['1 days', '1 days, 00:00:05', np.timedelta64(2,'D'), datetime.timedelta(days=2,seconds=2)]) -Similarly to ``date_range``, you can construct regular ranges of a ``TimedeltaIndex``: +Generating Ranges of Time Deltas +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Similar to :func:`date_range`, you can construct regular ranges of a ``TimedeltaIndex`` +using :func:`timedelta_range`. The default frequency for ``timedelta_range`` is +calendar day: + +.. ipython:: python + + pd.timedelta_range(start='1 days', periods=5) + +Various combinations of ``start``, ``end``, and ``periods`` can be used with +``timedelta_range``: + +.. ipython:: python + + pd.timedelta_range(start='1 days', end='5 days') + + pd.timedelta_range(end='10 days', periods=4) + +The ``freq`` parameter can passed a variety of :ref:`frequency aliases <timeseries.offset_aliases>`: .. ipython:: python - pd.timedelta_range(start='1 days', periods=5, freq='D') pd.timedelta_range(start='1 days', end='2 days', freq='30T') + pd.timedelta_range(start='1 days', periods=5, freq='2D5H') + + +.. versionadded:: 0.23.0 + +Specifying ``start``, ``end``, and ``periods`` will generate a range of evenly spaced +timedeltas from ``start`` to ``end`` inclusively, with ``periods`` number of elements +in the resulting ``TimedeltaIndex``: + +.. ipython:: python + + pd.timedelta_range('0 days', '4 days', periods=5) + + pd.timedelta_range('0 days', '4 days', periods=10) + Using the TimedeltaIndex ~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/timeseries.rst b/doc/source/timeseries.rst index 73e3e721aad71..1b0cf86995a39 100644 --- a/doc/source/timeseries.rst +++ b/doc/source/timeseries.rst @@ -393,6 +393,18 @@ of those specified will not be generated: pd.bdate_range(start=start, periods=20) +.. versionadded:: 0.23.0 + +Specifying ``start``, ``end``, and ``periods`` will generate a range of evenly spaced +dates from ``start`` to ``end`` inclusively, with ``periods`` number of elements in the +resulting ``DatetimeIndex``: + +.. ipython:: python + + pd.date_range('2018-01-01', '2018-01-05', periods=5) + + pd.date_range('2018-01-01', '2018-01-05', periods=10) + .. _timeseries.custom-freq-ranges: Custom Frequency Ranges diff --git a/doc/source/whatsnew/v0.23.0.txt b/doc/source/whatsnew/v0.23.0.txt index 3f89de1dc22d8..feba9d856789b 100644 --- a/doc/source/whatsnew/v0.23.0.txt +++ b/doc/source/whatsnew/v0.23.0.txt @@ -1,6 +1,6 @@ .. _whatsnew_0230: -v0.23.0 (May 15, 2017) +v0.23.0 (May 15, 2018) ---------------------- This is a major release from 0.22.0 and includes a number of API changes, diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt new file mode 100644 index 0000000000000..b3c1dbc86525d --- /dev/null +++ b/doc/source/whatsnew/v0.23.1.txt @@ -0,0 +1,111 @@ +.. _whatsnew_0231: + +v0.23.1 +------- + +This is a minor bug-fix release in the 0.23.x series and includes some small regression fixes +and bug fixes. We recommend that all users upgrade to this version. + +.. contents:: What's new in v0.23.1 + :local: + :backlinks: none + +.. _whatsnew_0231.enhancements: + +New features +~~~~~~~~~~~~ + + +.. _whatsnew_0231.deprecations: + +Deprecations +~~~~~~~~~~~~ + +- +- + +.. _whatsnew_0231.performance: + +Performance Improvements +~~~~~~~~~~~~~~~~~~~~~~~~ + +- Improved performance of :meth:`CategoricalIndex.is_monotonic_increasing`, :meth:`CategoricalIndex.is_monotonic_decreasing` and :meth:`CategoricalIndex.is_monotonic` (:issue:`21025`) +- +- + +Documentation Changes +~~~~~~~~~~~~~~~~~~~~~ + +- +- + +.. _whatsnew_0231.bug_fixes: + +Bug Fixes +~~~~~~~~~ + +Groupby/Resample/Rolling +^^^^^^^^^^^^^^^^^^^^^^^^ + +- Bug in :func:`DataFrame.agg` where applying multiple aggregation functions to a :class:`DataFrame` with duplicated column names would cause a stack overflow (:issue:`21063`) +- Bug in :func:`pandas.core.groupby.GroupBy.ffill` and :func:`pandas.core.groupby.GroupBy.bfill` where the fill within a grouping would not always be applied as intended due to the implementations' use of a non-stable sort (:issue:`21207`) +- Bug in :func:`pandas.core.groupby.GroupBy.rank` where results did not scale to 100% when specifying ``method='dense'`` and ``pct=True`` + +Strings +^^^^^^^ + +- Bug in :meth:`Series.str.replace()` where the method throws `TypeError` on Python 3.5.2 (:issue: `21078`) + +Timedelta +^^^^^^^^^ +- Bug in :class:`Timedelta`: where passing a float with a unit would prematurely round the float precision (:issue: `14156`) + +Categorical +^^^^^^^^^^^ + +- Bug in :func:`pandas.util.testing.assert_index_equal` which raised ``AssertionError`` incorrectly, when comparing two :class:`CategoricalIndex` objects with param ``check_categorical=False`` (:issue:`19776`) +- Bug in :meth:`Categorical.fillna` incorrectly raising a ``TypeError`` when `value` the individual categories are iterable and `value` is an iterable (:issue:`21097`, :issue:`19788`) + +Sparse +^^^^^^ + +- Bug in :attr:`SparseArray.shape` which previously only returned the shape :attr:`SparseArray.sp_values` (:issue:`21126`) + +Conversion +^^^^^^^^^^ + +- +- + +Indexing +^^^^^^^^ + +- Bug in :meth:`Series.reset_index` where appropriate error was not raised with an invalid level name (:issue:`20925`) +- Bug in :func:`interval_range` when ``start``/``periods`` or ``end``/``periods`` are specified with float ``start`` or ``end`` (:issue:`21161`) +- Bug in :meth:`MultiIndex.set_names` where error raised for a ``MultiIndex`` with ``nlevels == 1`` (:issue:`21149`) +- + +I/O +^^^ + +- Bug in IO methods specifying ``compression='zip'`` which produced uncompressed zip archives (:issue:`17778`, :issue:`21144`) +- Bug in :meth:`DataFrame.to_stata` which prevented exporting DataFrames to buffers and most file-like objects (:issue:`21041`) +- + +Plotting +^^^^^^^^ + +- +- + +Reshaping +^^^^^^^^^ + +- Bug in :func:`concat` where error was raised in concatenating :class:`Series` with numpy scalar and tuple names (:issue:`21015`) +- + +Other +^^^^^ + +- Tab completion on :class:`Index` in IPython no longer outputs deprecation warnings (:issue:`21125`) +- Bug preventing pandas from being importable with -OO optimization (:issue:`21071`) diff --git a/pandas/_libs/groupby.pyx b/pandas/_libs/groupby.pyx index 43afd1e0f5969..a6dbaff17e543 100644 --- a/pandas/_libs/groupby.pyx +++ b/pandas/_libs/groupby.pyx @@ -297,7 +297,8 @@ def group_fillna_indexer(ndarray[int64_t] out, ndarray[int64_t] labels, # Make sure all arrays are the same size assert N == len(labels) == len(mask) - sorted_labels = np.argsort(labels).astype(np.int64, copy=False) + sorted_labels = np.argsort(labels, kind='mergesort').astype( + np.int64, copy=False) if direction == 'bfill': sorted_labels = sorted_labels[::-1] diff --git a/pandas/_libs/groupby_helper.pxi.in b/pandas/_libs/groupby_helper.pxi.in index 6a33e4a09476d..b3e9b7c9e69ee 100644 --- a/pandas/_libs/groupby_helper.pxi.in +++ b/pandas/_libs/groupby_helper.pxi.in @@ -418,7 +418,7 @@ def group_rank_{{name}}(ndarray[float64_t, ndim=2] out, bint is_datetimelike, object ties_method, bint ascending, bint pct, object na_option): """ - Provides the rank of values within each group. + Provides the rank of values within each group. Parameters ---------- @@ -451,8 +451,8 @@ def group_rank_{{name}}(ndarray[float64_t, ndim=2] out, """ cdef: TiebreakEnumType tiebreak - Py_ssize_t i, j, N, K, val_start=0, grp_start=0, dups=0, sum_ranks=0 - Py_ssize_t grp_vals_seen=1, grp_na_count=0 + Py_ssize_t i, j, N, K, grp_start=0, dups=0, sum_ranks=0 + Py_ssize_t grp_vals_seen=1, grp_na_count=0, grp_tie_count=0 ndarray[int64_t] _as ndarray[float64_t, ndim=2] grp_sizes ndarray[{{c_type}}] masked_vals @@ -563,6 +563,7 @@ def group_rank_{{name}}(ndarray[float64_t, ndim=2] out, dups = sum_ranks = 0 val_start = i grp_vals_seen += 1 + grp_tie_count +=1 # Similar to the previous conditional, check now if we are moving # to a new group. If so, keep track of the index where the new @@ -571,11 +572,16 @@ def group_rank_{{name}}(ndarray[float64_t, ndim=2] out, # (used by pct calculations later). also be sure to reset any of # the items helping to calculate dups if i == N - 1 or labels[_as[i]] != labels[_as[i+1]]: - for j in range(grp_start, i + 1): - grp_sizes[_as[j], 0] = i - grp_start + 1 - grp_na_count + if tiebreak != TIEBREAK_DENSE: + for j in range(grp_start, i + 1): + grp_sizes[_as[j], 0] = i - grp_start + 1 - grp_na_count + else: + for j in range(grp_start, i + 1): + grp_sizes[_as[j], 0] = (grp_tie_count - + (grp_na_count > 0)) dups = sum_ranks = 0 grp_na_count = 0 - val_start = i + 1 + grp_tie_count = 0 grp_start = i + 1 grp_vals_seen = 1 diff --git a/pandas/_libs/tslibs/timedeltas.pyx b/pandas/_libs/tslibs/timedeltas.pyx index d17d4e7139d72..e2b0b33053f83 100644 --- a/pandas/_libs/tslibs/timedeltas.pyx +++ b/pandas/_libs/tslibs/timedeltas.pyx @@ -202,22 +202,22 @@ cpdef inline int64_t cast_from_unit(object ts, object unit) except? -1: if unit == 'D' or unit == 'd': m = 1000000000L * 86400 - p = 6 + p = 9 elif unit == 'h': m = 1000000000L * 3600 - p = 6 + p = 9 elif unit == 'm': m = 1000000000L * 60 - p = 6 + p = 9 elif unit == 's': m = 1000000000L - p = 6 + p = 9 elif unit == 'ms': m = 1000000L - p = 3 + p = 6 elif unit == 'us': m = 1000L - p = 0 + p = 3 elif unit == 'ns' or unit is None: m = 1L p = 0 @@ -231,10 +231,10 @@ cpdef inline int64_t cast_from_unit(object ts, object unit) except? -1: # cast the unit, multiply base/frace separately # to avoid precision issues from float -> int base = <int64_t> ts - frac = ts -base + frac = ts - base if p: frac = round(frac, p) - return <int64_t> (base *m) + <int64_t> (frac *m) + return <int64_t> (base * m) + <int64_t> (frac * m) cdef inline _decode_if_necessary(object ts): @@ -760,7 +760,32 @@ cdef class _Timedelta(timedelta): @property def delta(self): - """ return out delta in ns (for internal compat) """ + """ + Return the timedelta in nanoseconds (ns), for internal compatibility. + + Returns + ------- + int + Timedelta in nanoseconds. + + Examples + -------- + >>> td = pd.Timedelta('1 days 42 ns') + >>> td.delta + 86400000000042 + + >>> td = pd.Timedelta('3 s') + >>> td.delta + 3000000000 + + >>> td = pd.Timedelta('3 ms 5 us') + >>> td.delta + 3005000 + + >>> td = pd.Timedelta(42, unit='ns') + >>> td.delta + 42 + """ return self.value @property @@ -791,9 +816,32 @@ cdef class _Timedelta(timedelta): @property def nanoseconds(self): """ - Number of nanoseconds (>= 0 and less than 1 microsecond). + Return the number of nanoseconds (n), where 0 <= n < 1 microsecond. + + Returns + ------- + int + Number of nanoseconds. + + See Also + -------- + Timedelta.components : Return all attributes with assigned values + (i.e. days, hours, minutes, seconds, milliseconds, microseconds, + nanoseconds). + + Examples + -------- + **Using string input** + + >>> td = pd.Timedelta('1 days 2 min 3 us 42 ns') + >>> td.nanoseconds + 42 + + **Using integer input** - .components will return the shown components + >>> td = pd.Timedelta(42, unit='ns') + >>> td.nanoseconds + 42 """ self._ensure_components() return self._ns @@ -1198,7 +1246,7 @@ class Timedelta(_Timedelta): deprecated. Use 'array // timedelta.value' instead. If you want to obtain epochs from an array of timestamps, you can rather use - 'array - pd.Timestamp("1970-01-01")) // pd.Timedelta("1s")'. + '(array - pd.Timestamp("1970-01-01")) // pd.Timedelta("1s")'. """) warnings.warn(msg, FutureWarning) return other // self.value diff --git a/pandas/compat/__init__.py b/pandas/compat/__init__.py index 12517372fedd1..5ae22694d0da7 100644 --- a/pandas/compat/__init__.py +++ b/pandas/compat/__init__.py @@ -425,7 +425,7 @@ def raise_with_traceback(exc, traceback=Ellipsis): # In Python 3.7, the private re._pattern_type is removed. # Python 3.5+ have typing.re.Pattern -if PY35: +if PY36: import typing re_type = typing.re.Pattern else: diff --git a/pandas/core/accessor.py b/pandas/core/accessor.py index c638b9e4ea117..7a853d575aa69 100644 --- a/pandas/core/accessor.py +++ b/pandas/core/accessor.py @@ -12,7 +12,8 @@ class DirNamesMixin(object): _accessors = frozenset([]) - _deprecations = frozenset(['asobject']) + _deprecations = frozenset( + ['asobject', 'base', 'data', 'flags', 'itemsize', 'strides']) def _dir_deletions(self): """ delete unwanted __dir__ for this object """ diff --git a/pandas/core/arrays/categorical.py b/pandas/core/arrays/categorical.py index abcb9ae3494b5..a1a8f098b582e 100644 --- a/pandas/core/arrays/categorical.py +++ b/pandas/core/arrays/categorical.py @@ -12,6 +12,7 @@ from pandas.core.dtypes.generic import ( ABCSeries, ABCIndexClass, ABCCategoricalIndex) from pandas.core.dtypes.missing import isna, notna +from pandas.core.dtypes.inference import is_hashable from pandas.core.dtypes.cast import ( maybe_infer_to_datetimelike, coerce_indexer_dtype) @@ -1751,7 +1752,7 @@ def fillna(self, value=None, method=None, limit=None): values[indexer] = values_codes[values_codes != -1] # If value is not a dict or Series it should be a scalar - elif is_scalar(value): + elif is_hashable(value): if not isna(value) and value not in self.categories: raise ValueError("fill value must be in categories") diff --git a/pandas/core/base.py b/pandas/core/base.py index fa78c89ed4ee7..c331ead8d2fef 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -114,7 +114,7 @@ def _reset_cache(self, key=None): def __sizeof__(self): """ - Generates the total memory usage for a object that returns + Generates the total memory usage for an object that returns either a value or Series of values """ if hasattr(self, 'memory_usage'): @@ -590,9 +590,10 @@ def _aggregate_multiple_funcs(self, arg, _level, _axis): # multiples else: - for col in obj: + for index, col in enumerate(obj): try: - colg = self._gotitem(col, ndim=1, subset=obj[col]) + colg = self._gotitem(col, ndim=1, + subset=obj.iloc[:, index]) results.append(colg.aggregate(arg)) keys.append(col) except (TypeError, DataError): @@ -675,7 +676,6 @@ def _gotitem(self, key, ndim, subset=None): subset : object, default None subset to act on """ - # create a new object to prevent aliasing if subset is None: subset = self.obj diff --git a/pandas/core/common.py b/pandas/core/common.py index b9182bfd2cbe2..1de8269c9a0c6 100644 --- a/pandas/core/common.py +++ b/pandas/core/common.py @@ -55,8 +55,11 @@ def flatten(l): def _consensus_name_attr(objs): name = objs[0].name for obj in objs[1:]: - if obj.name != name: - return None + try: + if obj.name != name: + name = None + except ValueError: + name = None return name diff --git a/pandas/core/frame.py b/pandas/core/frame.py index dccc840f5affd..9f6e834f0a25f 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -1774,8 +1774,11 @@ def to_stata(self, fname, convert_dates=None, write_index=True, Parameters ---------- - fname : str or buffer - String path of file-like object. + fname : path (string), buffer or path object + string, path object (pathlib.Path or py._path.local.LocalPath) or + object implementing a binary write() functions. If using a buffer + then the buffer will not be automatically closed after the file + data has been written. convert_dates : dict Dictionary mapping columns containing datetime types to stata internal format to use when writing the dates. Options are 'tc', @@ -3718,7 +3721,7 @@ def rename(self, *args, **kwargs): copy : boolean, default True Also copy underlying data inplace : boolean, default False - Whether to return a new %(klass)s. If True then value of copy is + Whether to return a new DataFrame. If True then value of copy is ignored. level : int or level name, default None In case of a MultiIndex, only rename labels in the specified @@ -4454,7 +4457,10 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False, axis = self._get_axis_number(axis) labels = self._get_axis(axis) - if level: + # make sure that the axis is lexsorted to start + # if not we need to reconstruct to get the correct indexer + labels = labels._sort_levels_monotonic() + if level is not None: new_axis, indexer = labels.sortlevel(level, ascending=ascending, sort_remaining=sort_remaining) @@ -4462,9 +4468,6 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False, elif isinstance(labels, MultiIndex): from pandas.core.sorting import lexsort_indexer - # make sure that the axis is lexsorted to start - # if not we need to reconstruct to get the correct indexer - labels = labels._sort_levels_monotonic() indexer = lexsort_indexer(labels._get_labels_for_sorting(), orders=ascending, na_position=na_position) @@ -5731,7 +5734,12 @@ def diff(self, periods=1, axis=0): # ---------------------------------------------------------------------- # Function application - def _gotitem(self, key, ndim, subset=None): + def _gotitem(self, + key, # type: Union[str, List[str]] + ndim, # type: int + subset=None # type: Union[Series, DataFrame, None] + ): + # type: (...) -> Union[Series, DataFrame] """ sub-classes to define return a sliced object @@ -5746,9 +5754,11 @@ def _gotitem(self, key, ndim, subset=None): """ if subset is None: subset = self + elif subset.ndim == 1: # is Series + return subset # TODO: _shallow_copy(subset)? - return self[key] + return subset[key] _agg_doc = dedent(""" The aggregation operations are always performed over an axis, either the @@ -7079,6 +7089,9 @@ def quantile(self, q=0.5, axis=0, numeric_only=True, 0 <= q <= 1, the quantile(s) to compute axis : {0, 1, 'index', 'columns'} (default 0) 0 or 'index' for row-wise, 1 or 'columns' for column-wise + numeric_only : boolean, default True + If False, the quantile of datetime and timedelta data will be + computed as well interpolation : {'linear', 'lower', 'higher', 'midpoint', 'nearest'} .. versionadded:: 0.18.0 @@ -7106,7 +7119,7 @@ def quantile(self, q=0.5, axis=0, numeric_only=True, -------- >>> df = pd.DataFrame(np.array([[1, 1], [2, 10], [3, 100], [4, 100]]), - columns=['a', 'b']) + columns=['a', 'b']) >>> df.quantile(.1) a 1.3 b 3.7 @@ -7116,6 +7129,20 @@ def quantile(self, q=0.5, axis=0, numeric_only=True, 0.1 1.3 3.7 0.5 2.5 55.0 + Specifying `numeric_only=False` will also compute the quantile of + datetime and timedelta data. + + >>> df = pd.DataFrame({'A': [1, 2], + 'B': [pd.Timestamp('2010'), + pd.Timestamp('2011')], + 'C': [pd.Timedelta('1 days'), + pd.Timedelta('2 days')]}) + >>> df.quantile(0.5, numeric_only=False) + A 1.5 + B 2010-07-02 12:00:00 + C 1 days 12:00:00 + Name: 0.5, dtype: object + See Also -------- pandas.core.window.Rolling.quantile diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index df39eb5fd8312..90238af9b3632 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -1384,7 +1384,8 @@ def set_names(self, names, level=None, inplace=False): names=[u'baz', u'bar']) """ - if level is not None and self.nlevels == 1: + from .multi import MultiIndex + if level is not None and not isinstance(self, MultiIndex): raise ValueError('Level must be None for non-MultiIndex') if level is not None and not is_list_like(level) and is_list_like( diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 3ffef5804acf7..78b7ae7054248 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -382,11 +382,11 @@ def is_unique(self): @property def is_monotonic_increasing(self): - return Index(self.codes).is_monotonic_increasing + return self._engine.is_monotonic_increasing @property def is_monotonic_decreasing(self): - return Index(self.codes).is_monotonic_decreasing + return self._engine.is_monotonic_decreasing @Appender(_index_shared_docs['index_unique'] % _index_doc_kwargs) def unique(self, level=None): diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 408a8cc435b63..8f8d8760583ce 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -1572,6 +1572,10 @@ def interval_range(start=None, end=None, periods=None, freq=None, periods += 1 if is_number(endpoint): + # force consistency between start/end/freq (lower end if freq skips it) + if com._all_not_none(start, end, freq): + end -= (end - start) % freq + # compute the period/start/end if unspecified (at most one) if periods is None: periods = int((end - start) // freq) + 1 @@ -1580,10 +1584,6 @@ def interval_range(start=None, end=None, periods=None, freq=None, elif end is None: end = start + (periods - 1) * freq - # force end to be consistent with freq (lower if freq skips end) - if freq is not None: - end -= end % freq - breaks = np.linspace(start, end, periods) if all(is_integer(x) for x in com._not_none(start, end, freq)): # np.linspace always produces float output diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 0829aa8f5a509..2757e0797a410 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -725,7 +725,7 @@ def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, ---------- data : array-like, Series, or DataFrame prefix : string, list of strings, or dict of strings, default None - String to append DataFrame column names + String to append DataFrame column names. Pass a list with length equal to the number of columns when calling get_dummies on a DataFrame. Alternatively, `prefix` can be a dictionary mapping column names to prefixes. diff --git a/pandas/core/series.py b/pandas/core/series.py index 0e2ae22f35af7..c5caafa07fb8e 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1195,12 +1195,13 @@ def reset_index(self, level=None, drop=False, name=None, inplace=False): inplace = validate_bool_kwarg(inplace, 'inplace') if drop: new_index = com._default_index(len(self)) - if level is not None and isinstance(self.index, MultiIndex): + if level is not None: if not isinstance(level, (tuple, list)): level = [level] level = [self.index._get_level_number(lev) for lev in level] - if len(level) < len(self.index.levels): - new_index = self.index.droplevel(level) + if isinstance(self.index, MultiIndex): + if len(level) < self.index.nlevels: + new_index = self.index.droplevel(level) if inplace: self.index = new_index @@ -2616,7 +2617,7 @@ def sort_index(self, axis=0, level=None, ascending=True, inplace=False, axis = self._get_axis_number(axis) index = self.index - if level: + if level is not None: new_index, indexer = index.sortlevel(level, ascending=ascending, sort_remaining=sort_remaining) elif isinstance(index, MultiIndex): @@ -3268,7 +3269,7 @@ def rename(self, index=None, **kwargs): copy : boolean, default True Also copy underlying data inplace : boolean, default False - Whether to return a new %(klass)s. If True then value of copy is + Whether to return a new Series. If True then value of copy is ignored. level : int or level name, default None In case of a MultiIndex, only rename labels in the specified diff --git a/pandas/core/sparse/array.py b/pandas/core/sparse/array.py index 5532d7522cd2d..ff58f7d104ff9 100644 --- a/pandas/core/sparse/array.py +++ b/pandas/core/sparse/array.py @@ -290,6 +290,7 @@ def __reduce__(self): """Necessary for making this object picklable""" object_state = list(np.ndarray.__reduce__(self)) subclass_state = self.fill_value, self.sp_index + object_state[2] = self.sp_values.__reduce__()[2] object_state[2] = (object_state[2], subclass_state) return tuple(object_state) @@ -339,6 +340,10 @@ def values(self): output.put(int_index.indices, self) return output + @property + def shape(self): + return (len(self),) + @property def sp_values(self): # caching not an option, leaks memory diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 81d775157cf62..5d50c45fe7eca 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -241,7 +241,7 @@ def str_count(arr, pat, flags=0): Escape ``'$'`` to find the literal dollar sign. >>> s = pd.Series(['$', 'B', 'Aab$', '$$ca', 'C$B$', 'cat']) - >>> s.str.count('\$') + >>> s.str.count('\\$') 0 1 1 0 2 1 @@ -358,7 +358,7 @@ def str_contains(arr, pat, case=True, flags=0, na=np.nan, regex=True): Returning any digit using regular expression. - >>> s1.str.contains('\d', regex=True) + >>> s1.str.contains('\\d', regex=True) 0 False 1 False 2 False diff --git a/pandas/io/common.py b/pandas/io/common.py index 0827216975f15..a492b7c0b8e8e 100644 --- a/pandas/io/common.py +++ b/pandas/io/common.py @@ -5,7 +5,7 @@ import codecs import mmap from contextlib import contextmanager, closing -from zipfile import ZipFile +import zipfile from pandas.compat import StringIO, BytesIO, string_types, text_type from pandas import compat @@ -428,7 +428,7 @@ def _get_handle(path_or_buf, mode, encoding=None, compression=None, return f, handles -class BytesZipFile(ZipFile, BytesIO): +class BytesZipFile(zipfile.ZipFile, BytesIO): """ Wrapper for standard library class ZipFile and allow the returned file-like handle to accept byte strings via `write` method. @@ -437,10 +437,10 @@ class BytesZipFile(ZipFile, BytesIO): bytes strings into a member of the archive. """ # GH 17778 - def __init__(self, file, mode='r', **kwargs): + def __init__(self, file, mode, compression=zipfile.ZIP_DEFLATED, **kwargs): if mode in ['wb', 'rb']: mode = mode.replace('b', '') - super(BytesZipFile, self).__init__(file, mode, **kwargs) + super(BytesZipFile, self).__init__(file, mode, compression, **kwargs) def write(self, data): super(BytesZipFile, self).writestr(self.filename, data) diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 8f91c7a497e2d..2797924985c70 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -1758,11 +1758,25 @@ def value_labels(self): return self.value_label_dict -def _open_file_binary_write(fname, encoding): +def _open_file_binary_write(fname): + """ + Open a binary file or no-op if file-like + + Parameters + ---------- + fname : string path, path object or buffer + + Returns + ------- + file : file-like object + File object supporting write + own : bool + True if the file was created, otherwise False + """ if hasattr(fname, 'write'): # if 'b' not in fname.mode: - return fname - return open(fname, "wb") + return fname, False + return open(fname, "wb"), True def _set_endianness(endianness): @@ -1899,7 +1913,9 @@ class StataWriter(StataParser): ---------- fname : path (string), buffer or path object string, path object (pathlib.Path or py._path.local.LocalPath) or - object implementing a binary write() functions. + object implementing a binary write() functions. If using a buffer + then the buffer will not be automatically closed after the file + is written. .. versionadded:: 0.23.0 support for pathlib, py.path. @@ -1970,6 +1986,7 @@ def __init__(self, fname, data, convert_dates=None, write_index=True, self._time_stamp = time_stamp self._data_label = data_label self._variable_labels = variable_labels + self._own_file = True # attach nobs, nvars, data, varlist, typlist self._prepare_pandas(data) @@ -2183,9 +2200,7 @@ def _prepare_pandas(self, data): self.fmtlist[key] = self._convert_dates[key] def write_file(self): - self._file = _open_file_binary_write( - self._fname, self._encoding or self._default_encoding - ) + self._file, self._own_file = _open_file_binary_write(self._fname) try: self._write_header(time_stamp=self._time_stamp, data_label=self._data_label) @@ -2205,6 +2220,23 @@ def write_file(self): self._write_file_close_tag() self._write_map() finally: + self._close() + + def _close(self): + """ + Close the file if it was created by the writer. + + If a buffer or file-like object was passed in, for example a GzipFile, + then leave this file open for the caller to close. In either case, + attempt to flush the file contents to ensure they are written to disk + (if supported) + """ + # Some file-like objects might not support flush + try: + self._file.flush() + except AttributeError: + pass + if self._own_file: self._file.close() def _write_map(self): @@ -2374,7 +2406,7 @@ def _prepare_data(self): def _write_data(self): data = self.data - data.tofile(self._file) + self._file.write(data.tobytes()) def _null_terminate(self, s, as_string=False): null_byte = '\x00' @@ -2641,7 +2673,9 @@ class StataWriter117(StataWriter): ---------- fname : path (string), buffer or path object string, path object (pathlib.Path or py._path.local.LocalPath) or - object implementing a binary write() functions. + object implementing a binary write() functions. If using a buffer + then the buffer will not be automatically closed after the file + is written. data : DataFrame Input to save convert_dates : dict @@ -2879,7 +2913,7 @@ def _write_data(self): self._update_map('data') data = self.data self._file.write(b'<data>') - data.tofile(self._file) + self._file.write(data.tobytes()) self._file.write(b'</data>') def _write_strls(self): diff --git a/pandas/tests/categorical/test_missing.py b/pandas/tests/categorical/test_missing.py index 5133c97d8b590..c78f02245a5b4 100644 --- a/pandas/tests/categorical/test_missing.py +++ b/pandas/tests/categorical/test_missing.py @@ -1,4 +1,6 @@ # -*- coding: utf-8 -*- +import collections + import numpy as np import pytest @@ -68,3 +70,16 @@ def test_fillna_raises(self, fillna_kwargs, msg): with tm.assert_raises_regex(ValueError, msg): cat.fillna(**fillna_kwargs) + + @pytest.mark.parametrize("named", [True, False]) + def test_fillna_iterable_category(self, named): + # https://github.com/pandas-dev/pandas/issues/21097 + if named: + Point = collections.namedtuple("Point", "x y") + else: + Point = lambda *args: args # tuple + cat = Categorical([Point(0, 0), Point(0, 1), None]) + result = cat.fillna(Point(0, 0)) + expected = Categorical([Point(0, 0), Point(0, 1), Point(0, 0)]) + + tm.assert_categorical_equal(result, expected) diff --git a/pandas/tests/extension/base/missing.py b/pandas/tests/extension/base/missing.py index 32cf29818e069..af26d83df3fe2 100644 --- a/pandas/tests/extension/base/missing.py +++ b/pandas/tests/extension/base/missing.py @@ -18,6 +18,11 @@ def test_isna(self, data_missing): expected = pd.Series(expected) self.assert_series_equal(result, expected) + # GH 21189 + result = pd.Series(data_missing).drop([0, 1]).isna() + expected = pd.Series([], dtype=bool) + self.assert_series_equal(result, expected) + def test_dropna_series(self, data_missing): ser = pd.Series(data_missing) result = ser.dropna() diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index e9431bd0c233c..90f0181beab0d 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -90,7 +90,7 @@ def nbytes(self): return 0 def isna(self): - return np.array([x.is_nan() for x in self._data]) + return np.array([x.is_nan() for x in self._data], dtype=bool) @property def _na_value(self): diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 88bb66f38b35c..10be7836cb8d7 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -108,7 +108,8 @@ def nbytes(self): return sys.getsizeof(self.data) def isna(self): - return np.array([x == self.dtype.na_value for x in self.data]) + return np.array([x == self.dtype.na_value for x in self.data], + dtype=bool) def take(self, indexer, allow_fill=False, fill_value=None): # re-implement here, since NumPy has trouble setting diff --git a/pandas/tests/frame/test_apply.py b/pandas/tests/frame/test_apply.py index ac46f02d00773..dfb2961befe35 100644 --- a/pandas/tests/frame/test_apply.py +++ b/pandas/tests/frame/test_apply.py @@ -554,6 +554,14 @@ def test_apply_non_numpy_dtype(self): result = df.apply(lambda x: x) assert_frame_equal(result, df) + def test_apply_dup_names_multi_agg(self): + # GH 21063 + df = pd.DataFrame([[0, 1], [2, 3]], columns=['a', 'a']) + expected = pd.DataFrame([[0, 1]], columns=['a', 'a'], index=['min']) + result = df.agg(['min']) + + tm.assert_frame_equal(result, expected) + class TestInferOutputShape(object): # the user has supplied an opaque UDF where diff --git a/pandas/tests/frame/test_reshape.py b/pandas/tests/frame/test_reshape.py index d89731dc09044..d05321abefca6 100644 --- a/pandas/tests/frame/test_reshape.py +++ b/pandas/tests/frame/test_reshape.py @@ -861,6 +861,23 @@ def test_stack_preserve_categorical_dtype(self): tm.assert_series_equal(result, expected) + @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']) + df = pd.DataFrame([[0, 2], [1, 3]], index=mi, columns=['B', 'A']) + df.columns.name = 'foo' + + expected = pd.DataFrame([ + [3, 1, 2, 0]], columns=pd.MultiIndex.from_tuples([ + ('c', 'A'), ('c', 'B'), ('d', 'A'), ('d', 'B')], names=[ + 'baz', 'foo'])) + expected.index.name = 'bar' + + result = df.unstack().swaplevel(axis=1).sort_index(axis=1, level=level) + tm.assert_frame_equal(result, expected) + def test_unstack_fill_frame_object(): # GH12815 Test unstacking with object. diff --git a/pandas/tests/frame/test_sorting.py b/pandas/tests/frame/test_sorting.py index b60eb89e87da5..599ae683f914b 100644 --- a/pandas/tests/frame/test_sorting.py +++ b/pandas/tests/frame/test_sorting.py @@ -550,18 +550,36 @@ def test_sort_index(self): expected = frame.iloc[:, ::-1] assert_frame_equal(result, expected) - def test_sort_index_multiindex(self): + @pytest.mark.parametrize("level", ['A', 0]) # GH 21052 + def test_sort_index_multiindex(self, level): # GH13496 # sort rows by specified level of multi-index - mi = MultiIndex.from_tuples([[2, 1, 3], [1, 1, 1]], names=list('ABC')) - df = DataFrame([[1, 2], [3, 4]], mi) + mi = MultiIndex.from_tuples([ + [2, 1, 3], [2, 1, 2], [1, 1, 1]], names=list('ABC')) + df = DataFrame([[1, 2], [3, 4], [5, 6]], index=mi) + + expected_mi = MultiIndex.from_tuples([ + [1, 1, 1], + [2, 1, 2], + [2, 1, 3]], names=list('ABC')) + expected = pd.DataFrame([ + [5, 6], + [3, 4], + [1, 2]], index=expected_mi) + result = df.sort_index(level=level) + assert_frame_equal(result, expected) - # MI sort, but no level: sort_level has no effect - mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list('ABC')) - df = DataFrame([[1, 2], [3, 4]], mi) - result = df.sort_index(sort_remaining=False) - expected = df.sort_index() + # sort_remaining=False + expected_mi = MultiIndex.from_tuples([ + [1, 1, 1], + [2, 1, 3], + [2, 1, 2]], names=list('ABC')) + expected = pd.DataFrame([ + [5, 6], + [1, 2], + [3, 4]], index=expected_mi) + result = df.sort_index(level=level, sort_remaining=False) assert_frame_equal(result, expected) def test_sort_index_intervalindex(self): diff --git a/pandas/tests/groupby/test_rank.py b/pandas/tests/groupby/test_rank.py index 6ad8b4905abff..203c3c73bec94 100644 --- a/pandas/tests/groupby/test_rank.py +++ b/pandas/tests/groupby/test_rank.py @@ -59,9 +59,9 @@ def test_rank_apply(): ('first', False, False, [3., 4., 1., 5., 2.]), ('first', False, True, [.6, .8, .2, 1., .4]), ('dense', True, False, [1., 1., 3., 1., 2.]), - ('dense', True, True, [0.2, 0.2, 0.6, 0.2, 0.4]), + ('dense', True, True, [1. / 3., 1. / 3., 3. / 3., 1. / 3., 2. / 3.]), ('dense', False, False, [3., 3., 1., 3., 2.]), - ('dense', False, True, [.6, .6, .2, .6, .4]), + ('dense', False, True, [3. / 3., 3. / 3., 1. / 3., 3. / 3., 2. / 3.]), ]) def test_rank_args(grps, vals, ties_method, ascending, pct, exp): key = np.repeat(grps, len(vals)) @@ -126,7 +126,7 @@ def test_infs_n_nans(grps, vals, ties_method, ascending, na_option, exp): @pytest.mark.parametrize("grps", [ ['qux'], ['qux', 'quux']]) @pytest.mark.parametrize("vals", [ - [2, 2, np.nan, 8, 2, 6, np.nan, np.nan], # floats + [2, 2, np.nan, 8, 2, 6, np.nan, np.nan], [pd.Timestamp('2018-01-02'), pd.Timestamp('2018-01-02'), np.nan, pd.Timestamp('2018-01-08'), pd.Timestamp('2018-01-02'), pd.Timestamp('2018-01-06'), np.nan, np.nan] @@ -167,11 +167,11 @@ def test_infs_n_nans(grps, vals, ties_method, ascending, na_option, exp): ('dense', True, 'keep', False, [1., 1., np.nan, 3., 1., 2., np.nan, np.nan]), ('dense', True, 'keep', True, - [0.2, 0.2, np.nan, 0.6, 0.2, 0.4, np.nan, np.nan]), + [1. / 3., 1. / 3., np.nan, 3. / 3., 1. / 3., 2. / 3., np.nan, np.nan]), ('dense', False, 'keep', False, [3., 3., np.nan, 1., 3., 2., np.nan, np.nan]), ('dense', False, 'keep', True, - [.6, 0.6, np.nan, 0.2, 0.6, 0.4, np.nan, np.nan]), + [3. / 3., 3. / 3., np.nan, 1. / 3., 3. / 3., 2. / 3., np.nan, np.nan]), ('average', True, 'no_na', False, [2., 2., 7., 5., 2., 4., 7., 7.]), ('average', True, 'no_na', True, [0.25, 0.25, 0.875, 0.625, 0.25, 0.5, 0.875, 0.875]), @@ -198,10 +198,10 @@ def test_infs_n_nans(grps, vals, ties_method, ascending, na_option, exp): [0.375, 0.5, 0.75, 0.125, 0.625, 0.25, 0.875, 1.]), ('dense', True, 'no_na', False, [1., 1., 4., 3., 1., 2., 4., 4.]), ('dense', True, 'no_na', True, - [0.125, 0.125, 0.5, 0.375, 0.125, 0.25, 0.5, 0.5]), + [0.25, 0.25, 1., 0.75, 0.25, 0.5, 1., 1.]), ('dense', False, 'no_na', False, [3., 3., 4., 1., 3., 2., 4., 4.]), ('dense', False, 'no_na', True, - [0.375, 0.375, 0.5, 0.125, 0.375, 0.25, 0.5, 0.5]) + [0.75, 0.75, 1., 0.25, 0.75, 0.5, 1., 1.]) ]) def test_rank_args_missing(grps, vals, ties_method, ascending, na_option, pct, exp): diff --git a/pandas/tests/groupby/test_transform.py b/pandas/tests/groupby/test_transform.py index 626057c1ea760..7fccf1f57a886 100644 --- a/pandas/tests/groupby/test_transform.py +++ b/pandas/tests/groupby/test_transform.py @@ -721,6 +721,23 @@ def interweave(list_obj): assert_frame_equal(result, exp) +@pytest.mark.parametrize("fill_method", ['ffill', 'bfill']) +def test_pad_stable_sorting(fill_method): + # GH 21207 + x = [0] * 20 + y = [np.nan] * 10 + [1] * 10 + + if fill_method == 'bfill': + y = y[::-1] + + df = pd.DataFrame({'x': x, 'y': y}) + expected = df.copy() + + result = getattr(df.groupby('x'), fill_method)() + + tm.assert_frame_equal(result, expected) + + @pytest.mark.parametrize("test_series", [True, False]) @pytest.mark.parametrize("periods,fill_method,limit", [ (1, 'ffill', None), (1, 'ffill', 1), diff --git a/pandas/tests/indexes/datetimes/test_tools.py b/pandas/tests/indexes/datetimes/test_tools.py index 45be3974dad63..8b0514764b0c0 100644 --- a/pandas/tests/indexes/datetimes/test_tools.py +++ b/pandas/tests/indexes/datetimes/test_tools.py @@ -650,6 +650,14 @@ def test_unit_mixed(self, cache): with pytest.raises(ValueError): pd.to_datetime(arr, errors='raise', cache=cache) + @pytest.mark.parametrize('cache', [True, False]) + def test_unit_rounding(self, cache): + # GH 14156: 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.877000093') + assert result == expected + @pytest.mark.parametrize('cache', [True, False]) def test_dataframe(self, cache): diff --git a/pandas/tests/indexes/interval/test_interval_range.py b/pandas/tests/indexes/interval/test_interval_range.py index 0fadfcf0c7f28..29fe2b0185662 100644 --- a/pandas/tests/indexes/interval/test_interval_range.py +++ b/pandas/tests/indexes/interval/test_interval_range.py @@ -110,6 +110,8 @@ def test_constructor_timedelta(self, closed, name, freq, periods): @pytest.mark.parametrize('start, end, freq, expected_endpoint', [ (0, 10, 3, 9), + (0, 10, 1.5, 9), + (0.5, 10, 3, 9.5), (Timedelta('0D'), Timedelta('10D'), '2D4H', Timedelta('8D16H')), (Timestamp('2018-01-01'), Timestamp('2018-02-09'), @@ -125,6 +127,22 @@ def test_early_truncation(self, start, end, freq, expected_endpoint): result_endpoint = result.right[-1] assert result_endpoint == expected_endpoint + @pytest.mark.parametrize('start, end, freq', [ + (0.5, None, None), + (None, 4.5, None), + (0.5, None, 1.5), + (None, 6.5, 1.5)]) + def test_no_invalid_float_truncation(self, start, end, freq): + # GH 21161 + if freq is None: + breaks = [0.5, 1.5, 2.5, 3.5, 4.5] + else: + breaks = [0.5, 2.0, 3.5, 5.0, 6.5] + expected = IntervalIndex.from_breaks(breaks) + + result = interval_range(start=start, end=end, periods=4, freq=freq) + tm.assert_index_equal(result, expected) + @pytest.mark.parametrize('start, mid, end', [ (Timestamp('2018-03-10', tz='US/Eastern'), Timestamp('2018-03-10 23:30:00', tz='US/Eastern'), diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index f4fa547574b9e..1e4dd2921b3f5 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -2088,6 +2088,17 @@ def test_get_duplicates_deprecated(self): with tm.assert_produces_warning(FutureWarning): index.get_duplicates() + def test_tab_complete_warning(self, ip): + # https://github.com/pandas-dev/pandas/issues/16409 + pytest.importorskip('IPython', minversion="6.0.0") + from IPython.core.completer import provisionalcompleter + + code = "import pandas as pd; idx = pd.Index([1, 2])" + ip.run_code(code) + with tm.assert_produces_warning(None): + with provisionalcompleter('ignore'): + list(ip.Completer.completions('idx.', 4)) + class TestMixedIntIndex(Base): # Mostly the tests from common.py for which the results differ diff --git a/pandas/tests/indexes/test_category.py b/pandas/tests/indexes/test_category.py index 6a1a1a5bdba4f..0e630f69b1a32 100644 --- a/pandas/tests/indexes/test_category.py +++ b/pandas/tests/indexes/test_category.py @@ -543,35 +543,41 @@ def test_reindex_empty_index(self): tm.assert_numpy_array_equal(indexer, np.array([-1, -1], dtype=np.intp)) - def test_is_monotonic(self): - c = CategoricalIndex([1, 2, 3]) + @pytest.mark.parametrize('data, non_lexsorted_data', [ + [[1, 2, 3], [9, 0, 1, 2, 3]], + [list('abc'), list('fabcd')], + ]) + def test_is_monotonic(self, data, non_lexsorted_data): + c = CategoricalIndex(data) assert c.is_monotonic_increasing assert not c.is_monotonic_decreasing - c = CategoricalIndex([1, 2, 3], ordered=True) + c = CategoricalIndex(data, ordered=True) assert c.is_monotonic_increasing assert not c.is_monotonic_decreasing - c = CategoricalIndex([1, 2, 3], categories=[3, 2, 1]) + c = CategoricalIndex(data, categories=reversed(data)) assert not c.is_monotonic_increasing assert c.is_monotonic_decreasing - c = CategoricalIndex([1, 3, 2], categories=[3, 2, 1]) + c = CategoricalIndex(data, categories=reversed(data), ordered=True) assert not c.is_monotonic_increasing - assert not c.is_monotonic_decreasing + assert c.is_monotonic_decreasing - c = CategoricalIndex([1, 2, 3], categories=[3, 2, 1], ordered=True) + # test when data is neither monotonic increasing nor decreasing + reordered_data = [data[0], data[2], data[1]] + c = CategoricalIndex(reordered_data, categories=reversed(data)) assert not c.is_monotonic_increasing - assert c.is_monotonic_decreasing + assert not c.is_monotonic_decreasing # non lexsorted categories - categories = [9, 0, 1, 2, 3] + categories = non_lexsorted_data - c = CategoricalIndex([9, 0], categories=categories) + c = CategoricalIndex(categories[:2], categories=categories) assert c.is_monotonic_increasing assert not c.is_monotonic_decreasing - c = CategoricalIndex([0, 1], categories=categories) + c = CategoricalIndex(categories[1:3], categories=categories) assert c.is_monotonic_increasing assert not c.is_monotonic_decreasing diff --git a/pandas/tests/indexes/test_multi.py b/pandas/tests/indexes/test_multi.py index 37f70090c179f..182dbdf2cf4e4 100644 --- a/pandas/tests/indexes/test_multi.py +++ b/pandas/tests/indexes/test_multi.py @@ -164,6 +164,22 @@ def test_set_name_methods(self): assert res is None assert ind.names == new_names2 + @pytest.mark.parametrize('inplace', [True, False]) + def test_set_names_with_nlevel_1(self, inplace): + # GH 21149 + # Ensure that .set_names for MultiIndex with + # nlevels == 1 does not raise any errors + expected = pd.MultiIndex(levels=[[0, 1]], + labels=[[0, 1]], + names=['first']) + m = pd.MultiIndex.from_product([[0, 1]]) + result = m.set_names('first', level=0, inplace=inplace) + + if inplace: + result = m + + tm.assert_index_equal(result, expected) + def test_set_levels_labels_directly(self): # setting levels/labels directly raises AttributeError diff --git a/pandas/tests/io/parser/common.py b/pandas/tests/io/parser/common.py index 2423ddcd9a1a0..2b7ff1f5a9879 100644 --- a/pandas/tests/io/parser/common.py +++ b/pandas/tests/io/parser/common.py @@ -54,20 +54,21 @@ def test_bad_stream_exception(self): # and C engine will raise UnicodeDecodeError instead of # c engine raising ParserError and swallowing exception # that caused read to fail. - handle = open(self.csv_shiftjs, "rb") codec = codecs.lookup("utf-8") utf8 = codecs.lookup('utf-8') - # stream must be binary UTF8 - stream = codecs.StreamRecoder( - handle, utf8.encode, utf8.decode, codec.streamreader, - codec.streamwriter) + if compat.PY3: msg = "'utf-8' codec can't decode byte" else: msg = "'utf8' codec can't decode byte" - with tm.assert_raises_regex(UnicodeDecodeError, msg): - self.read_csv(stream) - stream.close() + + # stream must be binary UTF8 + with open(self.csv_shiftjs, "rb") as handle, codecs.StreamRecoder( + handle, utf8.encode, utf8.decode, codec.streamreader, + codec.streamwriter) as stream: + + with tm.assert_raises_regex(UnicodeDecodeError, msg): + self.read_csv(stream) def test_read_csv(self): if not compat.PY3: diff --git a/pandas/tests/io/parser/compression.py b/pandas/tests/io/parser/compression.py index 01c6620e50d37..e84db66561c49 100644 --- a/pandas/tests/io/parser/compression.py +++ b/pandas/tests/io/parser/compression.py @@ -110,16 +110,15 @@ def test_read_csv_infer_compression(self): # see gh-9770 expected = self.read_csv(self.csv1, index_col=0, parse_dates=True) - inputs = [self.csv1, self.csv1 + '.gz', - self.csv1 + '.bz2', open(self.csv1)] + with open(self.csv1) as f: + inputs = [self.csv1, self.csv1 + '.gz', + self.csv1 + '.bz2', f] - for f in inputs: - df = self.read_csv(f, index_col=0, parse_dates=True, - compression='infer') - - tm.assert_frame_equal(expected, df) + for inp in inputs: + df = self.read_csv(inp, index_col=0, parse_dates=True, + compression='infer') - inputs[3].close() + tm.assert_frame_equal(expected, df) def test_read_csv_compressed_utf16_example(self): # GH18071 diff --git a/pandas/tests/io/parser/test_textreader.py b/pandas/tests/io/parser/test_textreader.py index ab4c14034cd20..e8d9d8b52164b 100644 --- a/pandas/tests/io/parser/test_textreader.py +++ b/pandas/tests/io/parser/test_textreader.py @@ -35,24 +35,18 @@ def setup_method(self, method): self.xls1 = os.path.join(self.dirpath, 'test.xls') def test_file_handle(self): - try: - f = open(self.csv1, 'rb') + with open(self.csv1, 'rb') as f: reader = TextReader(f) - result = reader.read() # noqa - finally: - f.close() + reader.read() def test_string_filename(self): reader = TextReader(self.csv1, header=None) reader.read() def test_file_handle_mmap(self): - try: - f = open(self.csv1, 'rb') + with open(self.csv1, 'rb') as f: reader = TextReader(f, memory_map=True, header=None) reader.read() - finally: - f.close() def test_StringIO(self): with open(self.csv1, 'rb') as f: diff --git a/pandas/tests/io/sas/test_sas7bdat.py b/pandas/tests/io/sas/test_sas7bdat.py index 5da347e47957c..b80263021c269 100644 --- a/pandas/tests/io/sas/test_sas7bdat.py +++ b/pandas/tests/io/sas/test_sas7bdat.py @@ -182,6 +182,8 @@ def test_date_time(): fname = os.path.join(dirpath, "datetime.csv") df0 = pd.read_csv(fname, parse_dates=['Date1', 'Date2', 'DateTime', 'DateTimeHi', 'Taiw']) + # GH 19732: Timestamps imported from sas will incur floating point errors + df.iloc[:, 3] = df.iloc[:, 3].dt.round('us') tm.assert_frame_equal(df, df0) diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index 110b790a65037..f3a465da4e87f 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -2,6 +2,8 @@ # pylint: disable=E1101 import datetime as dt +import io +import gzip import os import struct import warnings @@ -1473,3 +1475,28 @@ def test_invalid_date_conversion(self): with pytest.raises(ValueError): original.to_stata(path, convert_dates={'wrong_name': 'tc'}) + + @pytest.mark.parametrize('version', [114, 117]) + def test_nonfile_writing(self, version): + # GH 21041 + bio = io.BytesIO() + df = tm.makeDataFrame() + df.index.name = 'index' + with tm.ensure_clean() as path: + df.to_stata(bio, version=version) + bio.seek(0) + with open(path, 'wb') as dta: + dta.write(bio.read()) + reread = pd.read_stata(path, index_col='index') + tm.assert_frame_equal(df, reread) + + def test_gzip_writing(self): + # writing version 117 requires seek and cannot be used with gzip + df = tm.makeDataFrame() + df.index.name = 'index' + with tm.ensure_clean() as path: + with gzip.GzipFile(path, 'wb') as gz: + df.to_stata(gz, version=114) + with gzip.GzipFile(path, 'rb') as gz: + reread = pd.read_stata(gz, index_col='index') + tm.assert_frame_equal(df, reread) diff --git a/pandas/tests/reshape/test_concat.py b/pandas/tests/reshape/test_concat.py index f5e58fa70e1c4..dea305d4b3fee 100644 --- a/pandas/tests/reshape/test_concat.py +++ b/pandas/tests/reshape/test_concat.py @@ -2487,3 +2487,14 @@ def test_concat_aligned_sort_does_not_raise(): 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 = pd.Series({'a': 1, 'b': 2}, name=s1name) + s2 = pd.Series({'c': 5, 'd': 6}, name=s2name) + result = pd.concat([s1, s2]) + expected = pd.Series({'a': 1, 'b': 2, 'c': 5, 'd': 6}) + tm.assert_series_equal(result, expected) diff --git a/pandas/tests/scalar/timedelta/test_timedelta.py b/pandas/tests/scalar/timedelta/test_timedelta.py index 3fdc2aa71bfc0..205fdf49d3e91 100644 --- a/pandas/tests/scalar/timedelta/test_timedelta.py +++ b/pandas/tests/scalar/timedelta/test_timedelta.py @@ -106,6 +106,16 @@ def test_compare_timedelta_ndarray(self): class TestTimedeltas(object): + @pytest.mark.parametrize("unit, value, expected", [ + ('us', 9.999, 9999), ('ms', 9.999999, 9999999), + ('s', 9.999999999, 9999999999)]) + def test_rounding_on_int_unit_construction(self, unit, value, expected): + # GH 12690 + result = Timedelta(value, unit=unit) + assert result.value == expected + result = Timedelta(str(value) + unit) + assert result.value == expected + def test_total_seconds_scalar(self): # see gh-10939 rng = Timedelta('1 days, 10:11:12.100123456') diff --git a/pandas/tests/scalar/timestamp/test_timestamp.py b/pandas/tests/scalar/timestamp/test_timestamp.py index b022b327de57c..ab87d98fca8eb 100644 --- a/pandas/tests/scalar/timestamp/test_timestamp.py +++ b/pandas/tests/scalar/timestamp/test_timestamp.py @@ -621,10 +621,51 @@ def test_basics_nanos(self): assert stamp.microsecond == 145224 assert stamp.nanosecond == 192 - def test_unit(self): - - def check(val, unit=None, h=1, s=1, us=0): - stamp = Timestamp(val, unit=unit) + @pytest.mark.parametrize('value, check_kwargs', [ + [946688461000000000, {}], + [946688461000000000 / long(1000), dict(unit='us')], + [946688461000000000 / long(1000000), dict(unit='ms')], + [946688461000000000 / long(1000000000), dict(unit='s')], + [10957, dict(unit='D', h=0)], + pytest.param((946688461000000000 + 500000) / long(1000000000), + dict(unit='s', us=499, ns=964), + marks=pytest.mark.skipif(not PY3, + reason='using truediv, so these' + ' are like floats')), + pytest.param((946688461000000000 + 500000000) / long(1000000000), + dict(unit='s', us=500000), + marks=pytest.mark.skipif(not PY3, + reason='using truediv, so these' + ' are like floats')), + pytest.param((946688461000000000 + 500000) / long(1000000), + dict(unit='ms', us=500), + marks=pytest.mark.skipif(not PY3, + reason='using truediv, so these' + ' are like floats')), + pytest.param((946688461000000000 + 500000) / long(1000000000), + dict(unit='s'), + marks=pytest.mark.skipif(PY3, + reason='get chopped in py2')), + pytest.param((946688461000000000 + 500000000) / long(1000000000), + dict(unit='s'), + marks=pytest.mark.skipif(PY3, + reason='get chopped in py2')), + pytest.param((946688461000000000 + 500000) / long(1000000), + dict(unit='ms'), + marks=pytest.mark.skipif(PY3, + reason='get chopped in py2')), + [(946688461000000000 + 500000) / long(1000), dict(unit='us', us=500)], + [(946688461000000000 + 500000000) / long(1000000), + dict(unit='ms', us=500000)], + [946688461000000000 / 1000.0 + 5, dict(unit='us', us=5)], + [946688461000000000 / 1000.0 + 5000, dict(unit='us', us=5000)], + [946688461000000000 / 1000000.0 + 0.5, dict(unit='ms', us=500)], + [946688461000000000 / 1000000.0 + 0.005, dict(unit='ms', us=5, ns=5)], + [946688461000000000 / 1000000000.0 + 0.5, dict(unit='s', us=500000)], + [10957 + 0.5, dict(unit='D', h=12)]]) + def test_unit(self, value, check_kwargs): + def check(value, unit=None, h=1, s=1, us=0, ns=0): + stamp = Timestamp(value, unit=unit) assert stamp.year == 2000 assert stamp.month == 1 assert stamp.day == 1 @@ -637,41 +678,9 @@ def check(val, unit=None, h=1, s=1, us=0): assert stamp.minute == 0 assert stamp.second == 0 assert stamp.microsecond == 0 - assert stamp.nanosecond == 0 - - ts = Timestamp('20000101 01:01:01') - val = ts.value - days = (ts - Timestamp('1970-01-01')).days - - check(val) - check(val / long(1000), unit='us') - check(val / long(1000000), unit='ms') - check(val / long(1000000000), unit='s') - check(days, unit='D', h=0) + assert stamp.nanosecond == ns - # using truediv, so these are like floats - if PY3: - check((val + 500000) / long(1000000000), unit='s', us=500) - check((val + 500000000) / long(1000000000), unit='s', us=500000) - check((val + 500000) / long(1000000), unit='ms', us=500) - - # get chopped in py2 - else: - check((val + 500000) / long(1000000000), unit='s') - check((val + 500000000) / long(1000000000), unit='s') - check((val + 500000) / long(1000000), unit='ms') - - # ok - check((val + 500000) / long(1000), unit='us', us=500) - check((val + 500000000) / long(1000000), unit='ms', us=500000) - - # floats - check(val / 1000.0 + 5, unit='us', us=5) - check(val / 1000.0 + 5000, unit='us', us=5000) - check(val / 1000000.0 + 0.5, unit='ms', us=500) - check(val / 1000000.0 + 0.005, unit='ms', us=5) - check(val / 1000000000.0 + 0.5, unit='s', us=500000) - check(days + 0.5, unit='D', h=12) + check(value, **check_kwargs) def test_roundtrip(self): diff --git a/pandas/tests/series/test_alter_axes.py b/pandas/tests/series/test_alter_axes.py index dce4e82cbdcf1..859082a7e722d 100644 --- a/pandas/tests/series/test_alter_axes.py +++ b/pandas/tests/series/test_alter_axes.py @@ -188,6 +188,11 @@ def test_reset_index_level(self): with tm.assert_raises_regex(IndexError, 'Too many levels'): s.reset_index(level=[0, 1, 2]) + # Check that .reset_index([],drop=True) doesn't fail + result = pd.Series(range(4)).reset_index([], drop=True) + expected = pd.Series(range(4)) + assert_series_equal(result, expected) + def test_reset_index_range(self): # GH 12071 s = pd.Series(range(2), name='A', dtype='int64') @@ -275,3 +280,18 @@ def test_set_axis_prior_to_deprecation_signature(self): with tm.assert_produces_warning(FutureWarning): result = s.set_axis(0, list('abcd'), inplace=False) tm.assert_series_equal(result, expected) + + def test_reset_index_drop_errors(self): + # GH 20925 + + # KeyError raised for series index when passed level name is missing + s = pd.Series(range(4)) + with tm.assert_raises_regex(KeyError, 'must be same as name'): + s.reset_index('wrong', drop=True) + with tm.assert_raises_regex(KeyError, 'must be same as name'): + s.reset_index('wrong') + + # KeyError raised for series when level to be dropped is missing + s = pd.Series(range(4), index=pd.MultiIndex.from_product([[1, 2]] * 2)) + with tm.assert_raises_regex(KeyError, 'not found'): + s.reset_index('wrong', drop=True) diff --git a/pandas/tests/series/test_sorting.py b/pandas/tests/series/test_sorting.py index 01b4ea6eaa238..13e0d1b12c372 100644 --- a/pandas/tests/series/test_sorting.py +++ b/pandas/tests/series/test_sorting.py @@ -141,19 +141,20 @@ def test_sort_index_inplace(self): assert result is None tm.assert_series_equal(random_order, self.ts) - def test_sort_index_multiindex(self): + @pytest.mark.parametrize("level", ['A', 0]) # GH 21052 + def test_sort_index_multiindex(self, level): mi = MultiIndex.from_tuples([[1, 1, 3], [1, 1, 1]], names=list('ABC')) s = Series([1, 2], mi) backwards = s.iloc[[1, 0]] # implicit sort_remaining=True - res = s.sort_index(level='A') + res = s.sort_index(level=level) assert_series_equal(backwards, res) # GH13496 - # rows share same level='A': sort has no effect without remaining lvls - res = s.sort_index(level='A', sort_remaining=False) + # sort has no effect without remaining lvls + res = s.sort_index(level=level, sort_remaining=False) assert_series_equal(s, res) def test_sort_index_kind(self): diff --git a/pandas/tests/sparse/test_array.py b/pandas/tests/sparse/test_array.py index 6c0c83cf65ff7..b3330f866ba1f 100644 --- a/pandas/tests/sparse/test_array.py +++ b/pandas/tests/sparse/test_array.py @@ -454,6 +454,17 @@ def test_values_asarray(self): assert_almost_equal(self.arr.to_dense(), self.arr_data) assert_almost_equal(self.arr.sp_values, np.asarray(self.arr)) + @pytest.mark.parametrize('data,shape,dtype', [ + ([0, 0, 0, 0, 0], (5,), None), + ([], (0,), None), + ([0], (1,), None), + (['A', 'A', np.nan, 'B'], (4,), np.object) + ]) + def test_shape(self, data, shape, dtype): + # GH 21126 + out = SparseArray(data, dtype=dtype) + assert out.shape == shape + def test_to_dense(self): vals = np.array([1, np.nan, np.nan, 3, np.nan]) res = SparseArray(vals).to_dense() diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 0b329f64dafa3..bb7ee1b911fee 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -1,12 +1,13 @@ # -*- coding: utf-8 -*- import pytest +import os import collections from functools import partial import numpy as np -from pandas import Series, Timestamp +from pandas import Series, DataFrame, Timestamp from pandas.compat import range, lmap import pandas.core.common as com from pandas.core import ops @@ -222,3 +223,21 @@ def test_standardize_mapping(): dd = collections.defaultdict(list) assert isinstance(com.standardize_mapping(dd), partial) + + +@pytest.mark.parametrize('obj', [ + DataFrame(100 * [[0.123456, 0.234567, 0.567567], + [12.32112, 123123.2, 321321.2]], + columns=['X', 'Y', 'Z']), + Series(100 * [0.123456, 0.234567, 0.567567], name='X')]) +@pytest.mark.parametrize('method', ['to_pickle', 'to_json', 'to_csv']) +def test_compression_size(obj, method, compression): + if not compression: + pytest.skip("only test compression case.") + + with tm.ensure_clean() as filename: + getattr(obj, method)(filename, compression=compression) + compressed = os.path.getsize(filename) + getattr(obj, method)(filename, compression=None) + uncompressed = os.path.getsize(filename) + assert uncompressed > compressed diff --git a/pandas/tests/test_compat.py b/pandas/tests/test_compat.py index ead9ba1e26e2d..79d3aad493182 100644 --- a/pandas/tests/test_compat.py +++ b/pandas/tests/test_compat.py @@ -4,9 +4,10 @@ """ import pytest +import re from pandas.compat import (range, zip, map, filter, lrange, lzip, lmap, lfilter, builtins, iterkeys, itervalues, iteritems, - next, get_range_parameters, PY2) + next, get_range_parameters, PY2, re_type) class TestBuiltinIterators(object): @@ -89,3 +90,7 @@ def test_get_range_parameters(self, start, stop, step): assert start_result == start_expected assert stop_result == stop_expected assert step_result == step_expected + + +def test_re_type(): + assert isinstance(re.compile(''), re_type) diff --git a/pandas/tests/test_downstream.py b/pandas/tests/test_downstream.py index a595d9f18d6b8..c2d09c6d49e86 100644 --- a/pandas/tests/test_downstream.py +++ b/pandas/tests/test_downstream.py @@ -2,6 +2,8 @@ """ Testing that we work in the downstream packages """ +import subprocess + import pytest import numpy as np # noqa from pandas import DataFrame @@ -53,6 +55,11 @@ def test_xarray(df): assert df.to_xarray() is not None +def test_oo_optimizable(): + # GH 21071 + subprocess.check_call(["python", "-OO", "-c", "import pandas"]) + + @tm.network def test_statsmodels(): @@ -87,6 +94,7 @@ def test_pandas_gbq(df): pandas_gbq = import_module('pandas_gbq') # noqa +@pytest.mark.xfail(reason="0.7.0 pending") @tm.network def test_pandas_datareader(): @@ -95,6 +103,7 @@ def test_pandas_datareader(): 'F', 'quandl', '2017-01-01', '2017-02-01') +@pytest.mark.xfail(reaason="downstream install issue") def test_geopandas(): geopandas = import_module('geopandas') # noqa diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index d8e90ae0e1b35..74f2c977e0db2 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -41,7 +41,7 @@ def win_types(request): return request.param -@pytest.fixture(params=['kaiser', 'gaussian', 'general_gaussian', 'slepian']) +@pytest.fixture(params=['kaiser', 'gaussian', 'general_gaussian']) def win_types_special(request): return request.param @@ -1079,8 +1079,7 @@ def test_cmov_window_special(self, win_types_special): kwds = { 'kaiser': {'beta': 1.}, 'gaussian': {'std': 1.}, - 'general_gaussian': {'power': 2., 'width': 2.}, - 'slepian': {'width': 0.5}} + 'general_gaussian': {'power': 2., 'width': 2.}} vals = np.array([6.95, 15.21, 4.72, 9.12, 13.81, 13.49, 16.68, 9.48, 10.63, 14.48]) @@ -1090,8 +1089,6 @@ def test_cmov_window_special(self, win_types_special): 13.65671, 12.01002, np.nan, np.nan], 'general_gaussian': [np.nan, np.nan, 9.85011, 10.71589, 11.73161, 13.08516, 12.95111, 12.74577, np.nan, np.nan], - 'slepian': [np.nan, np.nan, 9.81073, 10.89359, 11.70284, 12.88331, - 12.96079, 12.77008, np.nan, np.nan], 'kaiser': [np.nan, np.nan, 9.86851, 11.02969, 11.65161, 12.75129, 12.90702, 12.83757, np.nan, np.nan] } diff --git a/pandas/tests/util/test_testing.py b/pandas/tests/util/test_testing.py index d6f58d16bcf64..ab7c4fb528452 100644 --- a/pandas/tests/util/test_testing.py +++ b/pandas/tests/util/test_testing.py @@ -503,6 +503,25 @@ def test_index_equal_metadata_message(self): with tm.assert_raises_regex(AssertionError, expected): assert_index_equal(idx1, idx2) + def test_categorical_index_equality(self): + expected = """Index are different + +Attribute "dtype" are different +\\[left\\]: CategoricalDtype\\(categories=\\[u?'a', u?'b'\\], ordered=False\\) +\\[right\\]: CategoricalDtype\\(categories=\\[u?'a', u?'b', u?'c'\\], \ +ordered=False\\)""" + + with tm.assert_raises_regex(AssertionError, expected): + assert_index_equal(pd.Index(pd.Categorical(['a', 'b'])), + pd.Index(pd.Categorical(['a', 'b'], + categories=['a', 'b', 'c']))) + + def test_categorical_index_equality_relax_categories_check(self): + assert_index_equal(pd.Index(pd.Categorical(['a', 'b'])), + pd.Index(pd.Categorical(['a', 'b'], + categories=['a', 'b', 'c'])), + check_categorical=False) + class TestAssertSeriesEqual(object): @@ -600,6 +619,25 @@ def test_series_equal_message(self): assert_series_equal(pd.Series([1, 2, 3]), pd.Series([1, 2, 4]), check_less_precise=True) + def test_categorical_series_equality(self): + expected = """Attributes are different + +Attribute "dtype" are different +\\[left\\]: CategoricalDtype\\(categories=\\[u?'a', u?'b'\\], ordered=False\\) +\\[right\\]: CategoricalDtype\\(categories=\\[u?'a', u?'b', u?'c'\\], \ +ordered=False\\)""" + + with tm.assert_raises_regex(AssertionError, expected): + assert_series_equal(pd.Series(pd.Categorical(['a', 'b'])), + pd.Series(pd.Categorical(['a', 'b'], + categories=['a', 'b', 'c']))) + + def test_categorical_series_equality_relax_categories_check(self): + assert_series_equal(pd.Series(pd.Categorical(['a', 'b'])), + pd.Series(pd.Categorical(['a', 'b'], + categories=['a', 'b', 'c'])), + check_categorical=False) + class TestAssertFrameEqual(object): diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index 749165f894819..c294110d89ec5 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -1090,12 +1090,17 @@ def apply(self, other): class CustomBusinessMonthEnd(_CustomBusinessMonth): - __doc__ = _CustomBusinessMonth.__doc__.replace('[BEGIN/END]', 'end') + # TODO(py27): Replace condition with Subsitution after dropping Py27 + if _CustomBusinessMonth.__doc__: + __doc__ = _CustomBusinessMonth.__doc__.replace('[BEGIN/END]', 'end') _prefix = 'CBM' class CustomBusinessMonthBegin(_CustomBusinessMonth): - __doc__ = _CustomBusinessMonth.__doc__.replace('[BEGIN/END]', 'beginning') + # TODO(py27): Replace condition with Subsitution after dropping Py27 + if _CustomBusinessMonth.__doc__: + __doc__ = _CustomBusinessMonth.__doc__.replace('[BEGIN/END]', + 'beginning') _prefix = 'CBMS' diff --git a/pandas/util/_decorators.py b/pandas/util/_decorators.py index 624fbbbd4f05e..6b55554cdc941 100644 --- a/pandas/util/_decorators.py +++ b/pandas/util/_decorators.py @@ -4,7 +4,7 @@ import types import warnings from textwrap import dedent, wrap -from functools import wraps, update_wrapper +from functools import wraps, update_wrapper, WRAPPER_ASSIGNMENTS def deprecate(name, alternative, version, alt_name=None, @@ -20,18 +20,18 @@ def deprecate(name, alternative, version, alt_name=None, Parameters ---------- name : str - Name of function to deprecate - alternative : str - Name of function to use instead + Name of function to deprecate. + alternative : func + Function to use instead. version : str - Version of pandas in which the method has been deprecated + Version of pandas in which the method has been deprecated. alt_name : str, optional - Name to use in preference of alternative.__name__ + Name to use in preference of alternative.__name__. klass : Warning, default FutureWarning stacklevel : int, default 2 msg : str - The message to display in the warning. - Default is '{name} is deprecated. Use {alt_name} instead.' + The message to display in the warning. + Default is '{name} is deprecated. Use {alt_name} instead.' """ alt_name = alt_name or alternative.__name__ @@ -39,25 +39,26 @@ def deprecate(name, alternative, version, alt_name=None, warning_msg = msg or '{} is deprecated, use {} instead'.format(name, alt_name) - @wraps(alternative) + # adding deprecated directive to the docstring + msg = msg or 'Use `{alt_name}` instead.'.format(alt_name=alt_name) + msg = '\n '.join(wrap(msg, 70)) + + @Substitution(version=version, msg=msg) + @Appender(alternative.__doc__) def wrapper(*args, **kwargs): + """ + .. deprecated:: %(version)s + + %(msg)s + + """ warnings.warn(warning_msg, klass, stacklevel=stacklevel) return alternative(*args, **kwargs) - # adding deprecated directive to the docstring - msg = msg or 'Use `{alt_name}` instead.'.format(alt_name=alt_name) - tpl = dedent(""" - .. deprecated:: {version} - - {msg} - - {rest} - """) - rest = getattr(wrapper, '__doc__', '') - docstring = tpl.format(version=version, - msg='\n '.join(wrap(msg, 70)), - rest=dedent(rest)) - wrapper.__doc__ = docstring + # Since we are using Substitution to create the required docstring, + # remove that from the attributes that should be assigned to the wrapper + assignments = tuple(x for x in WRAPPER_ASSIGNMENTS if x != '__doc__') + update_wrapper(wrapper, alternative, assigned=assignments) return wrapper diff --git a/pandas/util/testing.py b/pandas/util/testing.py index e1484a9c1b390..233eba6490937 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -778,8 +778,12 @@ def assert_index_equal(left, right, exact='equiv', check_names=True, def _check_types(l, r, obj='Index'): if exact: - assert_class_equal(left, right, exact=exact, obj=obj) - assert_attr_equal('dtype', l, r, obj=obj) + assert_class_equal(l, r, exact=exact, obj=obj) + + # Skip exact dtype checking when `check_categorical` is False + if check_categorical: + assert_attr_equal('dtype', l, r, obj=obj) + # allow string-like to have different inferred_types if l.inferred_type in ('string', 'unicode'): assert r.inferred_type in ('string', 'unicode') @@ -829,7 +833,8 @@ def _get_ilevel_values(index, level): # get_level_values may change dtype _check_types(left.levels[level], right.levels[level], obj=obj) - if check_exact: + # skip exact index checking when `check_categorical` is False + if check_exact and check_categorical: if not left.equals(right): diff = np.sum((left.values != right.values) .astype(int)) * 100.0 / len(left) @@ -950,23 +955,23 @@ def is_sorted(seq): def assert_categorical_equal(left, right, check_dtype=True, - obj='Categorical', check_category_order=True): + check_category_order=True, obj='Categorical'): """Test that Categoricals are equivalent. Parameters ---------- - left, right : Categorical - Categoricals to compare + left : Categorical + right : Categorical check_dtype : bool, default True Check that integer dtype of the codes are the same - obj : str, default 'Categorical' - Specify object name being compared, internally used to show appropriate - assertion message check_category_order : bool, default True Whether the order of the categories should be compared, which implies identical integer codes. If False, only the resulting values are compared. The ordered attribute is checked regardless. + obj : str, default 'Categorical' + Specify object name being compared, internally used to show appropriate + assertion message """ _check_isinstance(left, right, Categorical) @@ -1020,7 +1025,7 @@ def raise_assert_detail(obj, message, left, right, diff=None): def assert_numpy_array_equal(left, right, strict_nan=False, check_dtype=True, err_msg=None, - obj='numpy array', check_same=None): + check_same=None, obj='numpy array'): """ Checks that 'np.ndarray' is equivalent Parameters @@ -1033,11 +1038,11 @@ def assert_numpy_array_equal(left, right, strict_nan=False, check dtype if both a and b are np.ndarray err_msg : str, default None If provided, used as assertion message + check_same : None|'copy'|'same', default None + Ensure left and right refer/do not refer to the same memory area obj : str, default 'numpy array' Specify object name being compared, internally used to show appropriate assertion message - check_same : None|'copy'|'same', default None - Ensure left and right refer/do not refer to the same memory area """ # instance validation
https://api.github.com/repos/pandas-dev/pandas/pulls/21389
2018-06-08T17:22:16Z
2018-06-09T15:32:44Z
2018-06-09T15:32:44Z
2018-06-09T15:32:52Z
DOC: update whatsnew 0.23.1
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index 5a1bcce9b5970..d0af3c6c9ca9c 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -47,27 +47,23 @@ Performance Improvements Bug Fixes ~~~~~~~~~ -Groupby/Resample/Rolling -~~~~~~~~~~~~~~~~~~~~~~~~ +**Groupby/Resample/Rolling** - Bug in :func:`DataFrame.agg` where applying multiple aggregation functions to a :class:`DataFrame` with duplicated column names would cause a stack overflow (:issue:`21063`) - Bug in :func:`pandas.core.groupby.GroupBy.ffill` and :func:`pandas.core.groupby.GroupBy.bfill` where the fill within a grouping would not always be applied as intended due to the implementations' use of a non-stable sort (:issue:`21207`) - Bug in :func:`pandas.core.groupby.GroupBy.rank` where results did not scale to 100% when specifying ``method='dense'`` and ``pct=True`` -Data-type specific -~~~~~~~~~~~~~~~~~~ +**Data-type specific** - Bug in :meth:`Series.str.replace()` where the method throws `TypeError` on Python 3.5.2 (:issue: `21078`) - Bug in :class:`Timedelta`: where passing a float with a unit would prematurely round the float precision (:issue: `14156`) - Bug in :func:`pandas.testing.assert_index_equal` which raised ``AssertionError`` incorrectly, when comparing two :class:`CategoricalIndex` objects with param ``check_categorical=False`` (:issue:`19776`) -Sparse -~~~~~~ +**Sparse** - Bug in :attr:`SparseArray.shape` which previously only returned the shape :attr:`SparseArray.sp_values` (:issue:`21126`) -Indexing -~~~~~~~~ +**Indexing** - Bug in :meth:`Series.reset_index` where appropriate error was not raised with an invalid level name (:issue:`20925`) - Bug in :func:`interval_range` when ``start``/``periods`` or ``end``/``periods`` are specified with float ``start`` or ``end`` (:issue:`21161`) @@ -75,26 +71,21 @@ Indexing - Bug in :class:`IntervalIndex` constructors where creating an ``IntervalIndex`` from categorical data was not fully supported (:issue:`21243`, issue:`21253`) - Bug in :meth:`MultiIndex.sort_index` which was not guaranteed to sort correctly with ``level=1``; this was also causing data misalignment in particular :meth:`DataFrame.stack` operations (:issue:`20994`, :issue:`20945`, :issue:`21052`) -Plotting -~~~~~~~~ +**Plotting** - New keywords (sharex, sharey) to turn on/off sharing of x/y-axis by subplots generated with pandas.DataFrame().groupby().boxplot() (:issue: `20968`) -I/O -~~~ +**I/O** - Bug in IO methods specifying ``compression='zip'`` which produced uncompressed zip archives (:issue:`17778`, :issue:`21144`) - Bug in :meth:`DataFrame.to_stata` which prevented exporting DataFrames to buffers and most file-like objects (:issue:`21041`) - Bug in :meth:`read_stata` and :class:`StataReader` which did not correctly decode utf-8 strings on Python 3 from Stata 14 files (dta version 118) (:issue:`21244`) - -Reshaping -~~~~~~~~~ +**Reshaping** - Bug in :func:`concat` where error was raised in concatenating :class:`Series` with numpy scalar and tuple names (:issue:`21015`) - Bug in :func:`concat` warning message providing the wrong guidance for future behavior (:issue:`21101`) -Other -~~~~~ +**Other** - Tab completion on :class:`Index` in IPython no longer outputs deprecation warnings (:issue:`21125`)
One of the last commits apparently added back the subsections
https://api.github.com/repos/pandas-dev/pandas/pulls/21387
2018-06-08T16:41:36Z
2018-06-08T16:41:50Z
2018-06-08T16:41:50Z
2018-06-08T17:42:01Z
DOC: update multi-index term with MultiIndex
diff --git a/doc/source/basics.rst b/doc/source/basics.rst index d4efa8a28f6c5..74f1d80c6fd3d 100644 --- a/doc/source/basics.rst +++ b/doc/source/basics.rst @@ -168,7 +168,7 @@ either match on the *index* or *columns* via the **axis** keyword: df_orig = df -Furthermore you can align a level of a multi-indexed DataFrame with a Series. +Furthermore you can align a level of a MultiIndexed DataFrame with a Series. .. ipython:: python @@ -1034,7 +1034,7 @@ Passing a single function to ``.transform()`` with a ``Series`` will yield a sin Transform with multiple functions +++++++++++++++++++++++++++++++++ -Passing multiple functions will yield a column multi-indexed DataFrame. +Passing multiple functions will yield a column MultiIndexed DataFrame. The first level will be the original frame column names; the second level will be the names of the transforming functions. @@ -1060,7 +1060,7 @@ Passing a dict of functions will allow selective transforming per column. tsdf.transform({'A': np.abs, 'B': lambda x: x+1}) -Passing a dict of lists will generate a multi-indexed DataFrame with these +Passing a dict of lists will generate a MultiIndexed DataFrame with these selective transforms. .. ipython:: python @@ -1889,12 +1889,12 @@ faster than sorting the entire Series and calling ``head(n)`` on the result. df.nsmallest(5, ['a', 'c']) -.. _basics.multi-index_sorting: +.. _basics.multiindex_sorting: -Sorting by a multi-index column -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Sorting by a MultiIndex column +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -You must be explicit about sorting when the column is a multi-index, and fully specify +You must be explicit about sorting when the column is a MultiIndex, and fully specify all levels to ``by``. .. ipython:: python diff --git a/doc/source/contributing_docstring.rst b/doc/source/contributing_docstring.rst index 6b2ecfe66d5e2..4dec2a23facca 100644 --- a/doc/source/contributing_docstring.rst +++ b/doc/source/contributing_docstring.rst @@ -243,7 +243,7 @@ their use cases, if it is not too generic. """ Pivot a row index to columns. - When using a multi-index, a level can be pivoted so each value in + When using a MultiIndex, a level can be pivoted so each value in the index becomes a column. This is especially useful when a subindex is repeated for the main index, and data is easier to visualize as a pivot table. diff --git a/doc/source/dsintro.rst b/doc/source/dsintro.rst index b5b56fc6815c9..4d8e7979060f4 100644 --- a/doc/source/dsintro.rst +++ b/doc/source/dsintro.rst @@ -353,7 +353,7 @@ From a list of dicts From a dict of tuples ~~~~~~~~~~~~~~~~~~~~~ -You can automatically create a multi-indexed frame by passing a tuples +You can automatically create a MultiIndexed frame by passing a tuples dictionary. .. ipython:: python diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst index d0af44cde1857..56fea1ccfd9dc 100644 --- a/doc/source/ecosystem.rst +++ b/doc/source/ecosystem.rst @@ -189,7 +189,7 @@ widely used by institutions such as statistics offices, central banks, and international organisations. pandaSDMX can expose datasets and related structural metadata including data flows, code-lists, and data structure definitions as pandas Series -or multi-indexed DataFrames. +or MultiIndexed DataFrames. `fredapi <https://github.com/mortada/fredapi>`__ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/doc/source/io.rst b/doc/source/io.rst index 32129147ee281..658b9ff15783d 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -2356,7 +2356,7 @@ Read a URL and match a table that contains specific text: Specify a header row (by default ``<th>`` or ``<td>`` elements located within a ``<thead>`` are used to form the column index, if multiple rows are contained within -``<thead>`` then a multi-index is created); if specified, the header row is taken +``<thead>`` then a MultiIndex is created); if specified, the header row is taken from the data minus the parsed header elements (``<th>`` elements). .. code-block:: python @@ -3615,10 +3615,10 @@ defaults to `nan`. # we have provided a minimum string column size store.root.df_mixed.table -Storing Multi-Index DataFrames -++++++++++++++++++++++++++++++ +Storing MultiIndex DataFrames ++++++++++++++++++++++++++++++ -Storing multi-index ``DataFrames`` as tables is very similar to +Storing MultiIndex ``DataFrames`` as tables is very similar to storing/selecting from homogeneous index ``DataFrames``. .. ipython:: python diff --git a/doc/source/merging.rst b/doc/source/merging.rst index 0de6b871712a3..45944ba56d4e7 100644 --- a/doc/source/merging.rst +++ b/doc/source/merging.rst @@ -1085,12 +1085,12 @@ As you can see, this drops any rows where there was no match. .. _merging.join_on_mi: -Joining a single Index to a Multi-index -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Joining a single Index to a MultiIndex +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -You can join a singly-indexed ``DataFrame`` with a level of a multi-indexed ``DataFrame``. +You can join a singly-indexed ``DataFrame`` with a level of a MultiIndexed ``DataFrame``. The level will match on the name of the index of the singly-indexed frame against -a level name of the multi-indexed frame. +a level name of the MultiIndexed frame. .. ipython:: python @@ -1130,8 +1130,8 @@ This is equivalent but less verbose and more memory efficient / faster than this labels=['left', 'right'], vertical=False); plt.close('all'); -Joining with two multi-indexes -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Joining with two MultiIndexes +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ This is not implemented via ``join`` at-the-moment, however it can be done using the following code. diff --git a/doc/source/release.rst b/doc/source/release.rst index 04c499ff6797b..fa03d614ed42c 100644 --- a/doc/source/release.rst +++ b/doc/source/release.rst @@ -2174,7 +2174,7 @@ Highlights include: - SQL interfaces updated to use ``sqlalchemy``, see :ref:`here<whatsnew_0140.sql>`. - Display interface changes, see :ref:`here<whatsnew_0140.display>` - MultiIndexing using Slicers, see :ref:`here<whatsnew_0140.slicers>`. -- Ability to join a singly-indexed DataFrame with a multi-indexed DataFrame, see :ref:`here <merging.join_on_mi>` +- Ability to join a singly-indexed DataFrame with a MultiIndexed DataFrame, see :ref:`here <merging.join_on_mi>` - More consistency in groupby results and more flexible groupby specifications, see :ref:`here<whatsnew_0140.groupby>` - Holiday calendars are now supported in ``CustomBusinessDay``, see :ref:`here <timeseries.holiday>` - Several improvements in plotting functions, including: hexbin, area and pie plots, see :ref:`here<whatsnew_0140.plotting>`. @@ -2384,8 +2384,8 @@ Bug Fixes - Bug in merging ``timedelta`` dtypes (:issue:`5695`) - Bug in plotting.scatter_matrix function. Wrong alignment among diagonal and off-diagonal plots, see (:issue:`5497`). -- Regression in Series with a multi-index via ix (:issue:`6018`) -- Bug in Series.xs with a multi-index (:issue:`6018`) +- Regression in Series with a MultiIndex via ix (:issue:`6018`) +- Bug in Series.xs with a MultiIndex (:issue:`6018`) - Bug in Series construction of mixed type with datelike and an integer (which should result in object type and not automatic conversion) (:issue:`6028`) - Possible segfault when chained indexing with an object array under NumPy 1.7.1 (:issue:`6026`, :issue:`6056`) @@ -2409,10 +2409,10 @@ Bug Fixes - Fixed a bug in ``query``/``eval`` during lexicographic string comparisons (:issue:`6155`). - Fixed a bug in ``query`` where the index of a single-element ``Series`` was being thrown away (:issue:`6148`). -- Bug in ``HDFStore`` on appending a dataframe with multi-indexed columns to +- Bug in ``HDFStore`` on appending a dataframe with MultiIndexed columns to an existing table (:issue:`6167`) - Consistency with dtypes in setting an empty DataFrame (:issue:`6171`) -- Bug in selecting on a multi-index ``HDFStore`` even in the presence of under +- Bug in selecting on a MultiIndex ``HDFStore`` even in the presence of under specified column spec (:issue:`6169`) - Bug in ``nanops.var`` with ``ddof=1`` and 1 elements would sometimes return ``inf`` rather than ``nan`` on some platforms (:issue:`6136`) @@ -2659,8 +2659,8 @@ API Changes - the ``format`` keyword now replaces the ``table`` keyword; allowed values are ``fixed(f)|table(t)`` the ``Storer`` format has been renamed to ``Fixed`` - - a column multi-index will be recreated properly (:issue:`4710`); raise on - trying to use a multi-index with data_columns on the same axis + - a column MultiIndex will be recreated properly (:issue:`4710`); raise on + trying to use a MultiIndex with data_columns on the same axis - ``select_as_coordinates`` will now return an ``Int64Index`` of the resultant selection set - support ``timedelta64[ns]`` as a serialization type (:issue:`3577`) @@ -2932,7 +2932,7 @@ Bug Fixes - A zero length series written in Fixed format not deserializing properly. (:issue:`4708`) - Fixed decoding perf issue on pyt3 (:issue:`5441`) - - Validate levels in a multi-index before storing (:issue:`5527`) + - Validate levels in a MultiIndex before storing (:issue:`5527`) - Correctly handle ``data_columns`` with a Panel (:issue:`5717`) - Fixed bug in tslib.tz_convert(vals, tz1, tz2): it could raise IndexError exception while trying to access trans[pos + 1] (:issue:`4496`) @@ -2995,7 +2995,7 @@ Bug Fixes alignment (:issue:`3777`) - frozenset objects now raise in the ``Series`` constructor (:issue:`4482`, :issue:`4480`) -- Fixed issue with sorting a duplicate multi-index that has multiple dtypes +- Fixed issue with sorting a duplicate MultiIndex that has multiple dtypes (:issue:`4516`) - Fixed bug in ``DataFrame.set_values`` which was causing name attributes to be lost when expanding the index. (:issue:`3742`, :issue:`4039`) @@ -3042,11 +3042,11 @@ Bug Fixes (:issue:`4328`) - Bug with Series indexing not raising an error when the right-hand-side has an incorrect length (:issue:`2702`) -- Bug in multi-indexing with a partial string selection as one part of a +- Bug in MultiIndexing with a partial string selection as one part of a MultIndex (:issue:`4758`) - Bug with reindexing on the index with a non-unique index will now raise ``ValueError`` (:issue:`4746`) -- Bug in setting with ``loc/ix`` a single indexer with a multi-index axis and +- Bug in setting with ``loc/ix`` a single indexer with a MultiIndex axis and a NumPy array, related to (:issue:`3777`) - Bug in concatenation with duplicate columns across dtypes not merging with axis=0 (:issue:`4771`, :issue:`4975`) @@ -3117,7 +3117,7 @@ Bug Fixes - Make sure series-series boolean comparisons are label based (:issue:`4947`) - Bug in multi-level indexing with a Timestamp partial indexer (:issue:`4294`) -- Tests/fix for multi-index construction of an all-nan frame (:issue:`4078`) +- Tests/fix for MultiIndex construction of an all-nan frame (:issue:`4078`) - Fixed a bug where :func:`~pandas.read_html` wasn't correctly inferring values of tables with commas (:issue:`5029`) - Fixed a bug where :func:`~pandas.read_html` wasn't providing a stable @@ -3174,7 +3174,7 @@ Bug Fixes - Fixed segfault in C parser caused by passing more names than columns in the file. (:issue:`5156`) - Fix ``Series.isin`` with date/time-like dtypes (:issue:`5021`) -- C and Python Parser can now handle the more common multi-index column +- C and Python Parser can now handle the more common MultiIndex column format which doesn't have a row for index names (:issue:`4702`) - Bug when trying to use an out-of-bounds date as an object dtype (:issue:`5312`) @@ -3199,7 +3199,7 @@ Bug Fixes - performance improvements in ``isnull`` on larger size pandas objects - Fixed various setitem with 1d ndarray that does not have a matching length to the indexer (:issue:`5508`) -- Bug in getitem with a multi-index and ``iloc`` (:issue:`5528`) +- Bug in getitem with a MultiIndex and ``iloc`` (:issue:`5528`) - Bug in delitem on a Series (:issue:`5542`) - Bug fix in apply when using custom function and objects are not mutated (:issue:`5545`) - Bug in selecting from a non-unique index with ``loc`` (:issue:`5553`) @@ -3208,7 +3208,7 @@ Bug Fixes - Bug in repeated indexing of object with resultant non-unique index (:issue:`5678`) - Bug in fillna with Series and a passed series/dict (:issue:`5703`) - Bug in groupby transform with a datetime-like grouper (:issue:`5712`) -- Bug in multi-index selection in PY3 when using certain keys (:issue:`5725`) +- Bug in MultiIndex selection in PY3 when using certain keys (:issue:`5725`) - Row-wise concat of differing dtypes failing in certain cases (:issue:`5754`) pandas 0.12.0 @@ -3229,14 +3229,14 @@ New Features - Added module for reading and writing Stata files: pandas.io.stata (:issue:`1512`) includes ``to_stata`` DataFrame method, and a ``read_stata`` top-level reader - Added support for writing in ``to_csv`` and reading in ``read_csv``, - multi-index columns. The ``header`` option in ``read_csv`` now accepts a + MultiIndex columns. The ``header`` option in ``read_csv`` now accepts a list of the rows from which to read the index. Added the option, ``tupleize_cols`` to provide compatibility for the pre 0.12 behavior of - writing and reading multi-index columns via a list of tuples. The default in + writing and reading MultiIndex columns via a list of tuples. The default in 0.12 is to write lists of tuples and *not* interpret list of tuples as a - multi-index column. + MultiIndex column. Note: The default value will change in 0.12 to make the default *to* write and - read multi-index columns in the new format. (:issue:`3571`, :issue:`1651`, :issue:`3141`) + read MultiIndex columns in the new format. (:issue:`3571`, :issue:`1651`, :issue:`3141`) - Add iterator to ``Series.str`` (:issue:`3638`) - ``pd.set_option()`` now allows N option, value pairs (:issue:`3667`). - Added keyword parameters for different types of scatter_matrix subplots @@ -3447,7 +3447,7 @@ Bug Fixes - Fixed bug with ``Panel.transpose`` argument aliases (:issue:`3556`) - Fixed platform bug in ``PeriodIndex.take`` (:issue:`3579`) - Fixed bud in incorrect conversion of datetime64[ns] in ``combine_first`` (:issue:`3593`) -- Fixed bug in reset_index with ``NaN`` in a multi-index (:issue:`3586`) +- Fixed bug in reset_index with ``NaN`` in a MultiIndex (:issue:`3586`) - ``fillna`` methods now raise a ``TypeError`` when the ``value`` parameter is a ``list`` or ``tuple``. - Fixed bug where a time-series was being selected in preference to an actual column name @@ -3480,7 +3480,7 @@ Bug Fixes their first argument (:issue:`3702`) - Fix file tokenization error with \r delimiter and quoted fields (:issue:`3453`) - Groupby transform with item-by-item not upcasting correctly (:issue:`3740`) -- Incorrectly read a HDFStore multi-index Frame with a column specification (:issue:`3748`) +- Incorrectly read a HDFStore MultiIndex Frame with a column specification (:issue:`3748`) - ``read_html`` now correctly skips tests (:issue:`3741`) - PandasObjects raise TypeError when trying to hash (:issue:`3882`) - Fix incorrect arguments passed to concat that are not list-like (e.g. concat(df1,df2)) (:issue:`3481`) @@ -3497,7 +3497,7 @@ Bug Fixes - csv parsers would loop infinitely if ``iterator=True`` but no ``chunksize`` was specified (:issue:`3967`), Python parser failing with ``chunksize=1`` - Fix index name not propagating when using ``shift`` -- Fixed dropna=False being ignored with multi-index stack (:issue:`3997`) +- Fixed dropna=False being ignored with MultiIndex stack (:issue:`3997`) - Fixed flattening of columns when renaming MultiIndex columns DataFrame (:issue:`4004`) - Fix ``Series.clip`` for datetime series. NA/NaN threshold values will now throw ValueError (:issue:`3996`) - Fixed insertion issue into DataFrame, after rename (:issue:`4032`) @@ -3521,7 +3521,7 @@ Bug Fixes iterated over when regex=False (:issue:`4115`) - Fixed bug in ``convert_objects(convert_numeric=True)`` where a mixed numeric and object Series/Frame was not converting properly (:issue:`4119`) -- Fixed bugs in multi-index selection with column multi-index and duplicates +- Fixed bugs in MultiIndex selection with column MultiIndex and duplicates (:issue:`4145`, :issue:`4146`) - Fixed bug in the parsing of microseconds when using the ``format`` argument in ``to_datetime`` (:issue:`4152`) @@ -3830,7 +3830,7 @@ Improvements to existing features - ``HDFStore`` - - enables storing of multi-index dataframes (closes :issue:`1277`) + - enables storing of MultiIndex dataframes (closes :issue:`1277`) - support data column indexing and selection, via ``data_columns`` keyword in append - support write chunking to reduce memory footprint, via ``chunksize`` diff --git a/doc/source/spelling_wordlist.txt b/doc/source/spelling_wordlist.txt index 4c355a1b9c435..be93cdad083e9 100644 --- a/doc/source/spelling_wordlist.txt +++ b/doc/source/spelling_wordlist.txt @@ -8,6 +8,10 @@ ga fe reindexed automagic +closedness +ae +arbitrarly +losslessly Histogramming histogramming concat diff --git a/doc/source/whatsnew/v0.10.0.txt b/doc/source/whatsnew/v0.10.0.txt index 3a269e53a2404..ec4ac17c80fd7 100644 --- a/doc/source/whatsnew/v0.10.0.txt +++ b/doc/source/whatsnew/v0.10.0.txt @@ -370,7 +370,7 @@ Updated PyTables Support df1.get_dtype_counts() - performance improvements on table writing -- support for arbitrary indexed dimensions +- support for arbitrarly indexed dimensions - ``SparseSeries`` now has a ``density`` property (:issue:`2384`) - enable ``Series.str.strip/lstrip/rstrip`` methods to take an input argument to strip arbitrary characters (:issue:`2411`) diff --git a/doc/source/whatsnew/v0.10.1.txt b/doc/source/whatsnew/v0.10.1.txt index bb405c283ba24..f1a32440c6950 100644 --- a/doc/source/whatsnew/v0.10.1.txt +++ b/doc/source/whatsnew/v0.10.1.txt @@ -93,7 +93,7 @@ columns, this is equivalent to passing a store.select('df',columns = ['A','B']) -``HDFStore`` now serializes multi-index dataframes when appending tables. +``HDFStore`` now serializes MultiIndex dataframes when appending tables. .. ipython:: python diff --git a/doc/source/whatsnew/v0.12.0.txt b/doc/source/whatsnew/v0.12.0.txt index 69483b18a5490..f66f6c0f72d5d 100644 --- a/doc/source/whatsnew/v0.12.0.txt +++ b/doc/source/whatsnew/v0.12.0.txt @@ -7,7 +7,7 @@ This is a major release from 0.11.0 and includes several new features and enhancements along with a large number of bug fixes. Highlights include a consistent I/O API naming scheme, routines to read html, -write multi-indexes to csv files, read & write STATA data files, read & write JSON format +write MultiIndexes to csv files, read & write STATA data files, read & write JSON format files, Python 3 support for ``HDFStore``, filtering of groupby expressions via ``filter``, and a revamped ``replace`` routine that accepts regular expressions. diff --git a/doc/source/whatsnew/v0.14.0.txt b/doc/source/whatsnew/v0.14.0.txt index 4408470c52feb..d4b7b09c054d6 100644 --- a/doc/source/whatsnew/v0.14.0.txt +++ b/doc/source/whatsnew/v0.14.0.txt @@ -13,7 +13,7 @@ users upgrade to this version. - SQL interfaces updated to use ``sqlalchemy``, See :ref:`Here<whatsnew_0140.sql>`. - Display interface changes, See :ref:`Here<whatsnew_0140.display>` - MultiIndexing Using Slicers, See :ref:`Here<whatsnew_0140.slicers>`. - - Ability to join a singly-indexed DataFrame with a multi-indexed DataFrame, see :ref:`Here <merging.join_on_mi>` + - Ability to join a singly-indexed DataFrame with a MultiIndexed DataFrame, see :ref:`Here <merging.join_on_mi>` - More consistency in groupby results and more flexible groupby specifications, See :ref:`Here<whatsnew_0140.groupby>` - Holiday calendars are now supported in ``CustomBusinessDay``, see :ref:`Here <timeseries.holiday>` - Several improvements in plotting functions, including: hexbin, area and pie plots, see :ref:`Here<whatsnew_0140.plotting>`. @@ -466,8 +466,8 @@ Some other enhancements to the sql functions include: MultiIndexing Using Slicers ~~~~~~~~~~~~~~~~~~~~~~~~~~~ -In 0.14.0 we added a new way to slice multi-indexed objects. -You can slice a multi-index by providing multiple indexers. +In 0.14.0 we added a new way to slice MultiIndexed objects. +You can slice a MultiIndex by providing multiple indexers. You can provide any of the selectors as if you are indexing by label, see :ref:`Selection by Label <indexing.label>`, including slices, lists of labels, labels, and boolean indexers. @@ -519,7 +519,7 @@ See also issues (:issue:`6134`, :issue:`4036`, :issue:`3057`, :issue:`2598`, :is columns=columns).sort_index().sort_index(axis=1) df -Basic multi-index slicing using slices, lists, and labels. +Basic MultiIndex slicing using slices, lists, and labels. .. ipython:: python @@ -748,9 +748,9 @@ Enhancements - Add option to turn off escaping in ``DataFrame.to_latex`` (:issue:`6472`) - ``pd.read_clipboard`` will, if the keyword ``sep`` is unspecified, try to detect data copied from a spreadsheet and parse accordingly. (:issue:`6223`) -- Joining a singly-indexed DataFrame with a multi-indexed DataFrame (:issue:`3662`) +- Joining a singly-indexed DataFrame with a MultiIndexed DataFrame (:issue:`3662`) - See :ref:`the docs<merging.join_on_mi>`. Joining multi-index DataFrames on both the left and right is not yet supported ATM. + See :ref:`the docs<merging.join_on_mi>`. Joining MultiIndex DataFrames on both the left and right is not yet supported ATM. .. ipython:: python @@ -781,7 +781,7 @@ Enhancements noon, January 1, 4713 BC. Because nanoseconds are used to define the time in pandas the actual range of dates that you can use is 1678 AD to 2262 AD. (:issue:`4041`) - ``DataFrame.to_stata`` will now check data for compatibility with Stata data types - and will upcast when needed. When it is not possible to lossless upcast, a warning + and will upcast when needed. When it is not possible to losslessly upcast, a warning is issued (:issue:`6327`) - ``DataFrame.to_stata`` and ``StataWriter`` will accept keyword arguments time_stamp and data_label which allow the time stamp and dataset label to be set when creating a @@ -852,7 +852,7 @@ Performance - Performance improvement when converting ``DatetimeIndex`` to floating ordinals using ``DatetimeConverter`` (:issue:`6636`) - Performance improvement for ``DataFrame.shift`` (:issue:`5609`) -- Performance improvement in indexing into a multi-indexed Series (:issue:`5567`) +- Performance improvement in indexing into a MultiIndexed Series (:issue:`5567`) - Performance improvements in single-dtyped indexing (:issue:`6484`) - Improve performance of DataFrame construction with certain offsets, by removing faulty caching (e.g. MonthEnd,BusinessMonthEnd), (:issue:`6479`) @@ -896,7 +896,7 @@ Bug Fixes - Issue with groupby ``agg`` with a single function and a a mixed-type frame (:issue:`6337`) - Bug in ``DataFrame.replace()`` when passing a non- ``bool`` ``to_replace`` argument (:issue:`6332`) -- Raise when trying to align on different levels of a multi-index assignment (:issue:`3738`) +- Raise when trying to align on different levels of a MultiIndex assignment (:issue:`3738`) - Bug in setting complex dtypes via boolean indexing (:issue:`6345`) - Bug in TimeGrouper/resample when presented with a non-monotonic DatetimeIndex that would return invalid results. (:issue:`4161`) - Bug in index name propagation in TimeGrouper/resample (:issue:`4161`) @@ -996,7 +996,7 @@ Bug Fixes - accept ``TextFileReader`` in ``concat``, which was affecting a common user idiom (:issue:`6583`) - Bug in C parser with leading white space (:issue:`3374`) - Bug in C parser with ``delim_whitespace=True`` and ``\r``-delimited lines -- Bug in python parser with explicit multi-index in row following column header (:issue:`6893`) +- Bug in python parser with explicit MultiIndex in row following column header (:issue:`6893`) - Bug in ``Series.rank`` and ``DataFrame.rank`` that caused small floats (<1e-13) to all receive the same rank (:issue:`6886`) - Bug in ``DataFrame.apply`` with functions that used ``*args`` or ``**kwargs`` and returned an empty result (:issue:`6952`) @@ -1043,7 +1043,7 @@ Bug Fixes - Bug in ``query``/``eval`` where global constants were not looked up correctly (:issue:`7178`) - Bug in recognizing out-of-bounds positional list indexers with ``iloc`` and a multi-axis tuple indexer (:issue:`7189`) -- Bug in setitem with a single value, multi-index and integer indices (:issue:`7190`, :issue:`7218`) +- Bug in setitem with a single value, MultiIndex and integer indices (:issue:`7190`, :issue:`7218`) - Bug in expressions evaluation with reversed ops, showing in series-dataframe ops (:issue:`7198`, :issue:`7192`) -- Bug in multi-axis indexing with > 2 ndim and a multi-index (:issue:`7199`) +- Bug in multi-axis indexing with > 2 ndim and a MultiIndex (:issue:`7199`) - Fix a bug where invalid eval/query operations would blow the stack (:issue:`5198`) diff --git a/doc/source/whatsnew/v0.14.1.txt b/doc/source/whatsnew/v0.14.1.txt index f7f69218e0ef5..5183dd24e9b34 100644 --- a/doc/source/whatsnew/v0.14.1.txt +++ b/doc/source/whatsnew/v0.14.1.txt @@ -156,7 +156,7 @@ Experimental ~~~~~~~~~~~~ - ``pandas.io.data.Options`` has a new method, ``get_all_data`` method, and now consistently returns a - multi-indexed ``DataFrame`` (:issue:`5602`) + MultiIndexed ``DataFrame`` (:issue:`5602`) - ``io.gbq.read_gbq`` and ``io.gbq.to_gbq`` were refactored to remove the dependency on the Google ``bq.py`` command line client. This submodule now uses ``httplib2`` and the Google ``apiclient`` and ``oauth2client`` API client @@ -169,7 +169,7 @@ Experimental Bug Fixes ~~~~~~~~~ - Bug in ``DataFrame.where`` with a symmetric shaped frame and a passed other of a DataFrame (:issue:`7506`) -- Bug in Panel indexing with a multi-index axis (:issue:`7516`) +- Bug in Panel indexing with a MultiIndex axis (:issue:`7516`) - Regression in datetimelike slice indexing with a duplicated index and non-exact end-points (:issue:`7523`) - Bug in setitem with list-of-lists and single vs mixed types (:issue:`7551`:) - Bug in time ops with non-aligned Series (:issue:`7500`) @@ -183,10 +183,10 @@ Bug Fixes - Bug in plotting subplots with ``DataFrame.plot``, ``hist`` clears passed ``ax`` even if the number of subplots is one (:issue:`7391`). - Bug in plotting subplots with ``DataFrame.boxplot`` with ``by`` kw raises ``ValueError`` if the number of subplots exceeds 1 (:issue:`7391`). - Bug in subplots displays ``ticklabels`` and ``labels`` in different rule (:issue:`5897`) -- Bug in ``Panel.apply`` with a multi-index as an axis (:issue:`7469`) +- Bug in ``Panel.apply`` with a MultiIndex as an axis (:issue:`7469`) - Bug in ``DatetimeIndex.insert`` doesn't preserve ``name`` and ``tz`` (:issue:`7299`) - Bug in ``DatetimeIndex.asobject`` doesn't preserve ``name`` (:issue:`7299`) -- Bug in multi-index slicing with datetimelike ranges (strings and Timestamps), (:issue:`7429`) +- Bug in MultiIndex slicing with datetimelike ranges (strings and Timestamps), (:issue:`7429`) - Bug in ``Index.min`` and ``max`` doesn't handle ``nan`` and ``NaT`` properly (:issue:`7261`) - Bug in ``PeriodIndex.min/max`` results in ``int`` (:issue:`7609`) - Bug in ``resample`` where ``fill_method`` was ignored if you passed ``how`` (:issue:`2073`) @@ -221,8 +221,8 @@ Bug Fixes - Bug where ``NDFrame.replace()`` didn't correctly replace objects with ``Period`` values (:issue:`7379`). - Bug in ``.ix`` getitem should always return a Series (:issue:`7150`) -- Bug in multi-index slicing with incomplete indexers (:issue:`7399`) -- Bug in multi-index slicing with a step in a sliced level (:issue:`7400`) +- Bug in MultiIndex slicing with incomplete indexers (:issue:`7399`) +- Bug in MultiIndex slicing with a step in a sliced level (:issue:`7400`) - Bug where negative indexers in ``DatetimeIndex`` were not correctly sliced (:issue:`7408`) - Bug where ``NaT`` wasn't repr'd correctly in a ``MultiIndex`` (:issue:`7406`, diff --git a/doc/source/whatsnew/v0.15.0.txt b/doc/source/whatsnew/v0.15.0.txt index 94093b2cfb16c..79003296ac165 100644 --- a/doc/source/whatsnew/v0.15.0.txt +++ b/doc/source/whatsnew/v0.15.0.txt @@ -711,7 +711,7 @@ Other notable API changes: 2 7 NaN 3 11 NaN - Furthermore, ``.loc`` will raise If no values are found in a multi-index with a list-like indexer: + Furthermore, ``.loc`` will raise If no values are found in a MultiIndex with a list-like indexer: .. ipython:: python :okexcept: @@ -1114,9 +1114,9 @@ Bug Fixes - Bug in ``DatetimeIndex`` and ``PeriodIndex`` in-place addition and subtraction cause different result from normal one (:issue:`6527`) - Bug in adding and subtracting ``PeriodIndex`` with ``PeriodIndex`` raise ``TypeError`` (:issue:`7741`) - Bug in ``combine_first`` with ``PeriodIndex`` data raises ``TypeError`` (:issue:`3367`) -- Bug in multi-index slicing with missing indexers (:issue:`7866`) -- Bug in multi-index slicing with various edge cases (:issue:`8132`) -- Regression in multi-index indexing with a non-scalar type object (:issue:`7914`) +- Bug in MultiIndex slicing with missing indexers (:issue:`7866`) +- Bug in MultiIndex slicing with various edge cases (:issue:`8132`) +- Regression in MultiIndex indexing with a non-scalar type object (:issue:`7914`) - Bug in ``Timestamp`` comparisons with ``==`` and ``int64`` dtype (:issue:`8058`) - Bug in pickles contains ``DateOffset`` may raise ``AttributeError`` when ``normalize`` attribute is referred internally (:issue:`7748`) - Bug in ``Panel`` when using ``major_xs`` and ``copy=False`` is passed (deprecation warning fails because of missing ``warnings``) (:issue:`8152`). @@ -1130,7 +1130,7 @@ Bug Fixes - Bug in ``get`` where an ``IndexError`` would not cause the default value to be returned (:issue:`7725`) - Bug in ``offsets.apply``, ``rollforward`` and ``rollback`` may reset nanosecond (:issue:`7697`) - Bug in ``offsets.apply``, ``rollforward`` and ``rollback`` may raise ``AttributeError`` if ``Timestamp`` has ``dateutil`` tzinfo (:issue:`7697`) -- Bug in sorting a multi-index frame with a ``Float64Index`` (:issue:`8017`) +- Bug in sorting a MultiIndex frame with a ``Float64Index`` (:issue:`8017`) - Bug in inconsistent panel setitem with a rhs of a ``DataFrame`` for alignment (:issue:`7763`) - Bug in ``is_superperiod`` and ``is_subperiod`` cannot handle higher frequencies than ``S`` (:issue:`7760`, :issue:`7772`, :issue:`7803`) - Bug in 32-bit platforms with ``Series.shift`` (:issue:`8129`) @@ -1212,7 +1212,7 @@ Bug Fixes - Bug in ``NDFrame.loc`` indexing when row/column names were lost when target was a list/ndarray (:issue:`6552`) - Regression in ``NDFrame.loc`` indexing when rows/columns were converted to Float64Index if target was an empty list/ndarray (:issue:`7774`) - Bug in ``Series`` that allows it to be indexed by a ``DataFrame`` which has unexpected results. Such indexing is no longer permitted (:issue:`8444`) -- Bug in item assignment of a ``DataFrame`` with multi-index columns where right-hand-side columns were not aligned (:issue:`7655`) +- Bug in item assignment of a ``DataFrame`` with MultiIndex columns where right-hand-side columns were not aligned (:issue:`7655`) - Suppress FutureWarning generated by NumPy when comparing object arrays containing NaN for equality (:issue:`7065`) - Bug in ``DataFrame.eval()`` where the dtype of the ``not`` operator (``~``) was not correctly inferred as ``bool``. diff --git a/doc/source/whatsnew/v0.15.1.txt b/doc/source/whatsnew/v0.15.1.txt index 918eab3a9763e..8cbf239ea20d0 100644 --- a/doc/source/whatsnew/v0.15.1.txt +++ b/doc/source/whatsnew/v0.15.1.txt @@ -288,7 +288,7 @@ Bug Fixes - Bug in Panel indexing with a list-like (:issue:`8710`) - Compat issue is ``DataFrame.dtypes`` when ``options.mode.use_inf_as_null`` is True (:issue:`8722`) - Bug in ``read_csv``, ``dialect`` parameter would not take a string (:issue:`8703`) -- Bug in slicing a multi-index level with an empty-list (:issue:`8737`) +- Bug in slicing a MultiIndex level with an empty-list (:issue:`8737`) - Bug in numeric index operations of add/sub with Float/Index Index with numpy arrays (:issue:`8608`) - Bug in setitem with empty indexer and unwanted coercion of dtypes (:issue:`8669`) - Bug in ix/loc block splitting on setitem (manifests with integer-like dtypes, e.g. datetime64) (:issue:`8607`) diff --git a/doc/source/whatsnew/v0.15.2.txt b/doc/source/whatsnew/v0.15.2.txt index 16a57676c89c0..ee72fab7d23f2 100644 --- a/doc/source/whatsnew/v0.15.2.txt +++ b/doc/source/whatsnew/v0.15.2.txt @@ -199,7 +199,7 @@ Bug Fixes - Bug in ``groupby`` signatures that didn't include \*args or \*\*kwargs (:issue:`8733`). - ``io.data.Options`` now raises ``RemoteDataError`` when no expiry dates are available from Yahoo and when it receives no data from Yahoo (:issue:`8761`), (:issue:`8783`). - Unclear error message in csv parsing when passing dtype and names and the parsed data is a different data type (:issue:`8833`) -- Bug in slicing a multi-index with an empty list and at least one boolean indexer (:issue:`8781`) +- Bug in slicing a MultiIndex with an empty list and at least one boolean indexer (:issue:`8781`) - ``io.data.Options`` now raises ``RemoteDataError`` when no expiry dates are available from Yahoo (:issue:`8761`). - ``Timedelta`` kwargs may now be numpy ints and floats (:issue:`8757`). - Fixed several outstanding bugs for ``Timedelta`` arithmetic and comparisons (:issue:`8813`, :issue:`5963`, :issue:`5436`). diff --git a/doc/source/whatsnew/v0.16.0.txt b/doc/source/whatsnew/v0.16.0.txt index 214a08ef0bbff..ce525bbb4c1d6 100644 --- a/doc/source/whatsnew/v0.16.0.txt +++ b/doc/source/whatsnew/v0.16.0.txt @@ -589,7 +589,7 @@ Bug Fixes - Fixed bug on big endian platforms which produced incorrect results in ``StataReader`` (:issue:`8688`). - Bug in ``MultiIndex.has_duplicates`` when having many levels causes an indexer overflow (:issue:`9075`, :issue:`5873`) - Bug in ``pivot`` and ``unstack`` where ``nan`` values would break index alignment (:issue:`4862`, :issue:`7401`, :issue:`7403`, :issue:`7405`, :issue:`7466`, :issue:`9497`) -- Bug in left ``join`` on multi-index with ``sort=True`` or null values (:issue:`9210`). +- Bug in left ``join`` on MultiIndex with ``sort=True`` or null values (:issue:`9210`). - Bug in ``MultiIndex`` where inserting new keys would fail (:issue:`9250`). - Bug in ``groupby`` when key space exceeds ``int64`` bounds (:issue:`9096`). - Bug in ``unstack`` with ``TimedeltaIndex`` or ``DatetimeIndex`` and nulls (:issue:`9491`). diff --git a/doc/source/whatsnew/v0.16.1.txt b/doc/source/whatsnew/v0.16.1.txt index e2da12fc94b58..d3a8064a0e786 100644 --- a/doc/source/whatsnew/v0.16.1.txt +++ b/doc/source/whatsnew/v0.16.1.txt @@ -133,7 +133,7 @@ groupby operations on the index will preserve the index nature as well reindexing operations, will return a resulting index based on the type of the passed indexer, meaning that passing a list will return a plain-old-``Index``; indexing with a ``Categorical`` will return a ``CategoricalIndex``, indexed according to the categories -of the PASSED ``Categorical`` dtype. This allows one to arbitrary index these even with +of the PASSED ``Categorical`` dtype. This allows one to arbitrarly index these even with values NOT in the categories, similarly to how you can reindex ANY pandas index. .. code-block:: ipython @@ -455,7 +455,7 @@ Bug Fixes - Bug where using DataFrames asfreq would remove the name of the index. (:issue:`9885`) - Bug causing extra index point when resample BM/BQ (:issue:`9756`) - Changed caching in ``AbstractHolidayCalendar`` to be at the instance level rather than at the class level as the latter can result in unexpected behaviour. (:issue:`9552`) -- Fixed latex output for multi-indexed dataframes (:issue:`9778`) +- Fixed latex output for MultiIndexed dataframes (:issue:`9778`) - Bug causing an exception when setting an empty range using ``DataFrame.loc`` (:issue:`9596`) - Bug in hiding ticklabels with subplots and shared axes when adding a new plot to an existing grid of axes (:issue:`9158`) - Bug in ``transform`` and ``filter`` when grouping on a categorical variable (:issue:`9921`) diff --git a/doc/source/whatsnew/v0.17.0.txt b/doc/source/whatsnew/v0.17.0.txt index 1b98ebd0e19c5..404f2bf06e861 100644 --- a/doc/source/whatsnew/v0.17.0.txt +++ b/doc/source/whatsnew/v0.17.0.txt @@ -1069,7 +1069,7 @@ Bug Fixes - Bug in ``offsets.generate_range`` where ``start`` and ``end`` have finer precision than ``offset`` (:issue:`9907`) - Bug in ``pd.rolling_*`` where ``Series.name`` would be lost in the output (:issue:`10565`) - Bug in ``stack`` when index or columns are not unique. (:issue:`10417`) -- Bug in setting a ``Panel`` when an axis has a multi-index (:issue:`10360`) +- Bug in setting a ``Panel`` when an axis has a MultiIndex (:issue:`10360`) - Bug in ``USFederalHolidayCalendar`` where ``USMemorialDay`` and ``USMartinLutherKingJr`` were incorrect (:issue:`10278` and :issue:`9760` ) - Bug in ``.sample()`` where returned object, if set, gives unnecessary ``SettingWithCopyWarning`` (:issue:`10738`) - Bug in ``.sample()`` where weights passed as ``Series`` were not aligned along axis before being treated positionally, potentially causing problems if weight indices were not aligned with sampled object. (:issue:`10738`) diff --git a/doc/source/whatsnew/v0.17.1.txt b/doc/source/whatsnew/v0.17.1.txt index 990f27950d982..c5ae0d147824c 100644 --- a/doc/source/whatsnew/v0.17.1.txt +++ b/doc/source/whatsnew/v0.17.1.txt @@ -160,7 +160,7 @@ Bug Fixes - Bug in ``HDFStore.append`` with strings whose encoded length exceeded the max unencoded length (:issue:`11234`) - Bug in merging ``datetime64[ns, tz]`` dtypes (:issue:`11405`) - Bug in ``HDFStore.select`` when comparing with a numpy scalar in a where clause (:issue:`11283`) -- Bug in using ``DataFrame.ix`` with a multi-index indexer (:issue:`11372`) +- Bug in using ``DataFrame.ix`` with a MultiIndex indexer (:issue:`11372`) - Bug in ``date_range`` with ambiguous endpoints (:issue:`11626`) - Prevent adding new attributes to the accessors ``.str``, ``.dt`` and ``.cat``. Retrieving such a value was not possible, so error out on setting it. (:issue:`10673`) @@ -189,7 +189,7 @@ Bug Fixes - Bug in ``pandas.json`` when file to load is big (:issue:`11344`) - Bugs in ``to_excel`` with duplicate columns (:issue:`11007`, :issue:`10982`, :issue:`10970`) - Fixed a bug that prevented the construction of an empty series of dtype ``datetime64[ns, tz]`` (:issue:`11245`). -- Bug in ``read_excel`` with multi-index containing integers (:issue:`11317`) +- Bug in ``read_excel`` with MultiIndex containing integers (:issue:`11317`) - Bug in ``to_excel`` with openpyxl 2.2+ and merging (:issue:`11408`) - Bug in ``DataFrame.to_dict()`` produces a ``np.datetime64`` object instead of ``Timestamp`` when only datetime is present in data (:issue:`11327`) - Bug in ``DataFrame.corr()`` raises exception when computes Kendall correlation for DataFrames with boolean and not boolean columns (:issue:`11560`) diff --git a/doc/source/whatsnew/v0.18.0.txt b/doc/source/whatsnew/v0.18.0.txt index 8dc49dbc319a6..a3213136d998a 100644 --- a/doc/source/whatsnew/v0.18.0.txt +++ b/doc/source/whatsnew/v0.18.0.txt @@ -1257,7 +1257,7 @@ Bug Fixes - Bug in ``read_sql`` with ``pymysql`` connections failing to return chunked data (:issue:`11522`) - Bug in ``.to_csv`` ignoring formatting parameters ``decimal``, ``na_rep``, ``float_format`` for float indexes (:issue:`11553`) - Bug in ``Int64Index`` and ``Float64Index`` preventing the use of the modulo operator (:issue:`9244`) -- Bug in ``MultiIndex.drop`` for not lexsorted multi-indexes (:issue:`12078`) +- Bug in ``MultiIndex.drop`` for not lexsorted MultiIndexes (:issue:`12078`) - Bug in ``DataFrame`` when masking an empty ``DataFrame`` (:issue:`11859`) @@ -1277,7 +1277,7 @@ Bug Fixes - Bug in ``Series`` constructor with read-only data (:issue:`11502`) - Removed ``pandas.util.testing.choice()``. Should use ``np.random.choice()``, instead. (:issue:`12386`) - Bug in ``.loc`` setitem indexer preventing the use of a TZ-aware DatetimeIndex (:issue:`12050`) -- Bug in ``.style`` indexes and multi-indexes not appearing (:issue:`11655`) +- Bug in ``.style`` indexes and MultiIndexes not appearing (:issue:`11655`) - Bug in ``to_msgpack`` and ``from_msgpack`` which did not correctly serialize or deserialize ``NaT`` (:issue:`12307`). - Bug in ``.skew`` and ``.kurt`` due to roundoff error for highly similar values (:issue:`11974`) - Bug in ``Timestamp`` constructor where microsecond resolution was lost if HHMMSS were not separated with ':' (:issue:`10041`) diff --git a/doc/source/whatsnew/v0.20.0.txt b/doc/source/whatsnew/v0.20.0.txt index bd90e371597dc..2146b7b99a5a7 100644 --- a/doc/source/whatsnew/v0.20.0.txt +++ b/doc/source/whatsnew/v0.20.0.txt @@ -462,7 +462,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 closed. 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 <stats.rolling_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`) diff --git a/doc/source/whatsnew/v0.21.0.txt b/doc/source/whatsnew/v0.21.0.txt index 3a257c1ff9648..77ae5b92d0e70 100644 --- a/doc/source/whatsnew/v0.21.0.txt +++ b/doc/source/whatsnew/v0.21.0.txt @@ -935,7 +935,7 @@ Deprecations - :func:`read_excel()` has deprecated ``sheetname`` in favor of ``sheet_name`` for consistency with ``.to_excel()`` (:issue:`10559`). - :func:`read_excel()` has deprecated ``parse_cols`` in favor of ``usecols`` for consistency with :func:`read_csv` (:issue:`4988`) - :func:`read_csv()` has deprecated the ``tupleize_cols`` argument. Column tuples will always be converted to a ``MultiIndex`` (:issue:`17060`) -- :meth:`DataFrame.to_csv` has deprecated the ``tupleize_cols`` argument. Multi-index columns will be always written as rows in the CSV file (:issue:`17060`) +- :meth:`DataFrame.to_csv` has deprecated the ``tupleize_cols`` argument. MultiIndex columns will be always written as rows in the CSV file (:issue:`17060`) - The ``convert`` parameter has been deprecated in the ``.take()`` method, as it was not being respected (:issue:`16948`) - ``pd.options.html.border`` has been deprecated in favor of ``pd.options.display.html.border`` (:issue:`15793`). - :func:`SeriesGroupBy.nth` has deprecated ``True`` in favor of ``'all'`` for its kwarg ``dropna`` (:issue:`11038`). diff --git a/doc/source/whatsnew/v0.21.1.txt b/doc/source/whatsnew/v0.21.1.txt index 2c147736d79a8..49e59c9ddf5a7 100644 --- a/doc/source/whatsnew/v0.21.1.txt +++ b/doc/source/whatsnew/v0.21.1.txt @@ -126,7 +126,7 @@ I/O - Bug in :meth:`DataFrame.to_msgpack` when serializing data of the ``numpy.bool_`` datatype (:issue:`18390`) - Bug in :func:`read_json` not decoding when reading line delimited JSON from S3 (:issue:`17200`) - Bug in :func:`pandas.io.json.json_normalize` to avoid modification of ``meta`` (:issue:`18610`) -- Bug in :func:`to_latex` where repeated multi-index values were not printed even though a higher level index differed from the previous row (:issue:`14484`) +- Bug in :func:`to_latex` where repeated MultiIndex values were not printed even though a higher level index differed from the previous row (:issue:`14484`) - Bug when reading NaN-only categorical columns in :class:`HDFStore` (:issue:`18413`) - Bug in :meth:`DataFrame.to_latex` with ``longtable=True`` where a latex multicolumn always spanned over three columns (:issue:`17959`)
Hello, before I start working on part 2 of the sphinx spelling extension I wanted to submit this PR in order to fix the double use of multi-index and MultiIndex. I have changed all `multi-index` mentions through the documentation to `MultiIndex`, this meant that some titles needed changing and new linking needed to be done. I have tested the documentation locally and everything seems to be working okay. I have also reverted the changes to some adverbs that got changed previously (which shouldn't have according to @h-vetinari) I hope that creating this PR before working on part 2 is okay. If you would rather me add this and the next one together let me know and I'll update the title and whatnot 😄 👍 - [ ] closes #xxxx - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21382
2018-06-08T11:26:36Z
2018-06-08T17:39:12Z
2018-06-08T17:39:12Z
2018-06-29T14:43:18Z
MAINT: More friendly error msg on Index overflow
diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index dff6b5421d5ab..bf1051332ee19 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -181,6 +181,9 @@ class Index(IndexOpsMixin, PandasObject): ---------- data : array-like (1-dimensional) dtype : NumPy dtype (default: object) + If dtype is None, we find the dtype that best fits the data. + If an actual dtype is provided, we coerce to that dtype if it's safe. + Otherwise, an error will be raised. copy : bool Make a copy of input ndarray name : object @@ -306,7 +309,14 @@ def __new__(cls, data=None, dtype=None, copy=False, name=None, if is_integer_dtype(dtype): inferred = lib.infer_dtype(data) if inferred == 'integer': - data = np.array(data, copy=copy, dtype=dtype) + try: + data = np.array(data, copy=copy, dtype=dtype) + except OverflowError: + # gh-15823: a more user-friendly error message + raise OverflowError( + "the elements provided in the data cannot " + "all be casted to the dtype {dtype}" + .format(dtype=dtype)) elif inferred in ['floating', 'mixed-integer-float']: if isna(data).any(): raise ValueError('cannot convert float ' diff --git a/pandas/tests/indexes/test_base.py b/pandas/tests/indexes/test_base.py index f9f16dc0ce8b7..c264f5f79e47e 100644 --- a/pandas/tests/indexes/test_base.py +++ b/pandas/tests/indexes/test_base.py @@ -474,6 +474,13 @@ def test_constructor_nonhashable_name(self, indices): tm.assert_raises_regex(TypeError, message, indices.set_names, names=renamed) + def test_constructor_overflow_int64(self): + # see gh-15832 + msg = ("the elements provided in the data cannot " + "all be casted to the dtype int64") + with tm.assert_raises_regex(OverflowError, msg): + Index([np.iinfo(np.uint64).max - 1], dtype="int64") + def test_view_with_args(self): restricted = ['unicodeIndex', 'strIndex', 'catIndex', 'boolIndex',
Display a more friendly error message when there is an `OverflowError` during `Index` construction. Partially addresses #15832.
https://api.github.com/repos/pandas-dev/pandas/pulls/21377
2018-06-08T05:34:52Z
2018-06-12T00:16:37Z
2018-06-12T00:16:37Z
2018-06-29T14:46:02Z
PERF: Add __contains__ to CategoricalIndex
diff --git a/asv_bench/benchmarks/categoricals.py b/asv_bench/benchmarks/categoricals.py index 5464e7cba22c3..48f42621d183d 100644 --- a/asv_bench/benchmarks/categoricals.py +++ b/asv_bench/benchmarks/categoricals.py @@ -193,3 +193,16 @@ def time_categorical_series_is_monotonic_increasing(self): def time_categorical_series_is_monotonic_decreasing(self): self.s.is_monotonic_decreasing + + +class Contains(object): + + goal_time = 0.2 + + def setup(self): + N = 10**5 + self.ci = tm.makeCategoricalIndex(N) + self.cat = self.ci.categories[0] + + def time_contains(self): + self.cat in self.ci diff --git a/doc/source/whatsnew/v0.23.2.txt b/doc/source/whatsnew/v0.23.2.txt index 3e4326dea2ecc..1ac6e21adc46d 100644 --- a/doc/source/whatsnew/v0.23.2.txt +++ b/doc/source/whatsnew/v0.23.2.txt @@ -24,7 +24,9 @@ Fixed Regressions Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ -- +- Improved performance of membership checks in :class:`CategoricalIndex` + (i.e. ``x in ci``-style checks are much faster). :meth:`CategoricalIndex.contains` + is likewise much faster (:issue:`21369`) - Documentation Changes diff --git a/pandas/core/indexes/category.py b/pandas/core/indexes/category.py index 587090fa72def..7f2860a963423 100644 --- a/pandas/core/indexes/category.py +++ b/pandas/core/indexes/category.py @@ -325,19 +325,31 @@ def _reverse_indexer(self): def __contains__(self, key): hash(key) - if self.categories._defer_to_indexing: - return key in self.categories + if isna(key): # if key is a NaN, check if any NaN is in self. + return self.isna().any() + + # is key in self.categories? Then get its location. + # If not (i.e. KeyError), it logically can't be in self either + try: + loc = self.categories.get_loc(key) + except KeyError: + return False - return key in self.values + # loc is the location of key in self.categories, but also the value + # for key in self.codes and in self._engine. key may be in categories, + # but still not in self, check this. Example: + # 'b' in CategoricalIndex(['a'], categories=['a', 'b']) # False + if is_scalar(loc): + return loc in self._engine + else: + # if self.categories is IntervalIndex, loc is an array + # check if any scalar of the array is in self._engine + return any(loc_ in self._engine for loc_ in loc) @Appender(_index_shared_docs['contains'] % _index_doc_kwargs) def contains(self, key): hash(key) - - if self.categories._defer_to_indexing: - return self.categories.contains(key) - - return key in self.values + return key in self def __array__(self, dtype=None): """ the array interface, return my values """
- [x] progress towards #20395 - [x] xref #21022 - [ ] tests added / passed - [x] benchmark added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Currently, membership checks in ``CategoricalIndex`` is very slow as explained in #21022. This PR fixes the issue for ``CategoricalIndex``, while #21022 contains the fix for ``Categorical``. The difference between the two cases is the use of ``_engine`` for ``CategoricalIndex``, which makes this even faster than the ``Catagorical`` solution in #21022. Tests exist already and can be found in ``tests/indexes/test_category.py::TestCategoricalIndex::test_contains``. ASV: ``` before after ratio [0c65c57a] [986779ab] - 2.49±0.2ms 3.26±0.2μs 0.00 categoricals.Contains.time_contains SOME BENCHMARKS HAVE CHANGED SIGNIFICANTLY. ```
https://api.github.com/repos/pandas-dev/pandas/pulls/21369
2018-06-07T21:38:54Z
2018-06-14T10:38:24Z
2018-06-14T10:38:24Z
2018-07-02T23:25:25Z
DOC: clean-up 0.23.1 whatsnew
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index 048a429136f0c..09b711c80910c 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -10,19 +10,22 @@ and bug fixes. We recommend that all users upgrade to this version. :local: :backlinks: none -.. _whatsnew_0231.enhancements: -New features -~~~~~~~~~~~~ +.. _whatsnew_0231.fixed_regressions: +Fixed Regressions +~~~~~~~~~~~~~~~~~ -.. _whatsnew_0231.deprecations: - -Deprecations -~~~~~~~~~~~~ +- Fixed regression in the :attr:`DatetimeIndex.date` and :attr:`DatetimeIndex.time` + attributes in case of timezone-aware data: :attr:`DatetimeIndex.time` returned + a tz-aware time instead of tz-naive (:issue:`21267`) and :attr:`DatetimeIndex.date` + returned incorrect date when the input date has a non-UTC timezone (:issue:`21230`). +- Fixed regression in :meth:`pandas.io.json.json_normalize` when called with ``None`` values + in nested levels in JSON (:issue:`21158`). +- Bug in :meth:`~DataFrame.to_csv` causes encoding error when compression and encoding are specified (:issue:`21241`, :issue:`21118`) +- Bug preventing pandas from being importable with -OO optimization (:issue:`21071`) +- Bug in :meth:`Categorical.fillna` incorrectly raising a ``TypeError`` when `value` the individual categories are iterable and `value` is an iterable (:issue:`21097`, :issue:`19788`) -- -- .. _whatsnew_0231.performance: @@ -31,14 +34,7 @@ Performance Improvements - Improved performance of :meth:`CategoricalIndex.is_monotonic_increasing`, :meth:`CategoricalIndex.is_monotonic_decreasing` and :meth:`CategoricalIndex.is_monotonic` (:issue:`21025`) - Improved performance of :meth:`CategoricalIndex.is_unique` (:issue:`21107`) -- -- - -Documentation Changes -~~~~~~~~~~~~~~~~~~~~~ -- -- .. _whatsnew_0231.bug_fixes: @@ -46,74 +42,39 @@ Bug Fixes ~~~~~~~~~ Groupby/Resample/Rolling -^^^^^^^^^^^^^^^^^^^^^^^^ - Bug in :func:`DataFrame.agg` where applying multiple aggregation functions to a :class:`DataFrame` with duplicated column names would cause a stack overflow (:issue:`21063`) - Bug in :func:`pandas.core.groupby.GroupBy.ffill` and :func:`pandas.core.groupby.GroupBy.bfill` where the fill within a grouping would not always be applied as intended due to the implementations' use of a non-stable sort (:issue:`21207`) - Bug in :func:`pandas.core.groupby.GroupBy.rank` where results did not scale to 100% when specifying ``method='dense'`` and ``pct=True`` -Strings -^^^^^^^ +Data-type specific - Bug in :meth:`Series.str.replace()` where the method throws `TypeError` on Python 3.5.2 (:issue: `21078`) - -Timedelta -^^^^^^^^^ - Bug in :class:`Timedelta`: where passing a float with a unit would prematurely round the float precision (:issue: `14156`) - -Categorical -^^^^^^^^^^^ - -- Bug in :func:`pandas.util.testing.assert_index_equal` which raised ``AssertionError`` incorrectly, when comparing two :class:`CategoricalIndex` objects with param ``check_categorical=False`` (:issue:`19776`) -- Bug in :meth:`Categorical.fillna` incorrectly raising a ``TypeError`` when `value` the individual categories are iterable and `value` is an iterable (:issue:`21097`, :issue:`19788`) +- Bug in :func:`pandas.testing.assert_index_equal` which raised ``AssertionError`` incorrectly, when comparing two :class:`CategoricalIndex` objects with param ``check_categorical=False`` (:issue:`19776`) Sparse -^^^^^^ - Bug in :attr:`SparseArray.shape` which previously only returned the shape :attr:`SparseArray.sp_values` (:issue:`21126`) -Conversion -^^^^^^^^^^ - -- -- - Indexing -^^^^^^^^ - Bug in :meth:`Series.reset_index` where appropriate error was not raised with an invalid level name (:issue:`20925`) - Bug in :func:`interval_range` when ``start``/``periods`` or ``end``/``periods`` are specified with float ``start`` or ``end`` (:issue:`21161`) - Bug in :meth:`MultiIndex.set_names` where error raised for a ``MultiIndex`` with ``nlevels == 1`` (:issue:`21149`) -- Bug in :attr:`DatetimeIndex.date` where an incorrect date is returned when the input date has a non-UTC timezone (:issue:`21230`) - Bug in :class:`IntervalIndex` constructors where creating an ``IntervalIndex`` from categorical data was not fully supported (:issue:`21243`, issue:`21253`) - Bug in :meth:`MultiIndex.sort_index` which was not guaranteed to sort correctly with ``level=1``; this was also causing data misalignment in particular :meth:`DataFrame.stack` operations (:issue:`20994`, :issue:`20945`, :issue:`21052`) -- Bug in :attr:`DatetimeIndex.time` where given a tz-aware Timestamp, a tz-aware Time is returned instead of tz-naive (:issue:`21267`) -- I/O -^^^ - Bug in IO methods specifying ``compression='zip'`` which produced uncompressed zip archives (:issue:`17778`, :issue:`21144`) - Bug in :meth:`DataFrame.to_stata` which prevented exporting DataFrames to buffers and most file-like objects (:issue:`21041`) -- Bug when :meth:`pandas.io.json.json_normalize` was called with ``None`` values in nested levels in JSON (:issue:`21158`) -- Bug in :meth:`DataFrame.to_csv` and :meth:`Series.to_csv` causes encoding error when compression and encoding are specified (:issue:`21241`, :issue:`21118`) - Bug in :meth:`read_stata` and :class:`StataReader` which did not correctly decode utf-8 strings on Python 3 from Stata 14 files (dta version 118) (:issue:`21244`) -- - -Plotting -^^^^^^^^ - -- -- Reshaping -^^^^^^^^^ - Bug in :func:`concat` where error was raised in concatenating :class:`Series` with numpy scalar and tuple names (:issue:`21015`) -- Other -^^^^^ - Tab completion on :class:`Index` in IPython no longer outputs deprecation warnings (:issue:`21125`) -- Bug preventing pandas from being importable with -OO optimization (:issue:`21071`)
I added a "Fixed regressions" section and moved some over there. @TomAugspurger does that look ok to you? (then I'll maybe merge to the other PRs can add it there) Also mad the bug fixes subsections into plain text to make it a bit less "heavy" (given the only few entries per section).
https://api.github.com/repos/pandas-dev/pandas/pulls/21368
2018-06-07T21:12:48Z
2018-06-07T21:20:17Z
2018-06-07T21:20:17Z
2018-06-12T16:30:40Z
DOC: move whatsnew file for #21116 (index droplevel)
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index f2bc81eea186b..b3c1dbc86525d 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -15,8 +15,6 @@ and bug fixes. We recommend that all users upgrade to this version. New features ~~~~~~~~~~~~ -- :meth:`Index.droplevel` is now implemented also for flat indexes, for compatibility with MultiIndex (:issue:`21115`) - .. _whatsnew_0231.deprecations: diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 6cbc19cca99e1..78974a955b570 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -15,7 +15,8 @@ Other Enhancements - :func:`to_datetime` now supports the ``%Z`` and ``%z`` directive when passed into ``format`` (:issue:`13486`) - :func:`Series.mode` and :func:`DataFrame.mode` now support the ``dropna`` parameter which can be used to specify whether NaN/NaT values should be considered (:issue:`17534`) - :func:`to_csv` now supports ``compression`` keyword when a file handle is passed. (:issue:`21227`) -- +- :meth:`Index.droplevel` is now implemented also for flat indexes, for compatibility with MultiIndex (:issue:`21115`) + .. _whatsnew_0240.api_breaking:
xref https://github.com/pandas-dev/pandas/pull/21116#issuecomment-395436923
https://api.github.com/repos/pandas-dev/pandas/pulls/21367
2018-06-07T20:41:51Z
2018-06-07T20:42:12Z
2018-06-07T20:42:12Z
2018-06-07T20:42:15Z
REGR: NA-values in ctors with string dtype
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index 5a1bcce9b5970..b766ee9f3dec1 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -10,7 +10,6 @@ and bug fixes. We recommend that all users upgrade to this version. :local: :backlinks: none - .. _whatsnew_0231.fixed_regressions: Fixed Regressions @@ -29,6 +28,7 @@ Fixed Regressions - Bug in :meth:`~DataFrame.to_csv` causes encoding error when compression and encoding are specified (:issue:`21241`, :issue:`21118`) - Bug preventing pandas from being importable with -OO optimization (:issue:`21071`) - Bug in :meth:`Categorical.fillna` incorrectly raising a ``TypeError`` when `value` the individual categories are iterable and `value` is an iterable (:issue:`21097`, :issue:`19788`) +- Fixed regression in constructors coercing NA values like ``None`` to strings when passing ``dtype=str`` (:issue:`21083`) - Regression in :func:`pivot_table` where an ordered ``Categorical`` with missing values for the pivot's ``index`` would give a mis-aligned result (:issue:`21133`) diff --git a/pandas/conftest.py b/pandas/conftest.py index a463f573c82e0..d5f399c7cd63d 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -159,3 +159,14 @@ def tz_aware_fixture(request): Fixture for trying explicit timezones: {0} """ return request.param + + +@pytest.fixture(params=[str, 'str', 'U']) +def string_dtype(request): + """Parametrized fixture for string dtypes. + + * str + * 'str' + * 'U' + """ + return request.param diff --git a/pandas/core/dtypes/cast.py b/pandas/core/dtypes/cast.py index e4ed6d544d42e..ebc7a13234a98 100644 --- a/pandas/core/dtypes/cast.py +++ b/pandas/core/dtypes/cast.py @@ -1227,3 +1227,45 @@ def construct_1d_object_array_from_listlike(values): result = np.empty(len(values), dtype='object') result[:] = values return result + + +def construct_1d_ndarray_preserving_na(values, dtype=None, copy=False): + """ + Construct a new ndarray, coercing `values` to `dtype`, preserving NA. + + Parameters + ---------- + values : Sequence + dtype : numpy.dtype, optional + copy : bool, default False + Note that copies may still be made with ``copy=False`` if casting + is required. + + Returns + ------- + arr : ndarray[dtype] + + Examples + -------- + >>> np.array([1.0, 2.0, None], dtype='str') + array(['1.0', '2.0', 'None'], dtype='<U4') + + >>> construct_1d_ndarray_preserving_na([1.0, 2.0, None], dtype='str') + + + """ + subarr = np.array(values, dtype=dtype, copy=copy) + + if dtype is not None and dtype.kind in ("U", "S"): + # GH-21083 + # We can't just return np.array(subarr, dtype='str') since + # NumPy will convert the non-string objects into strings + # Including NA values. Se we have to go + # string -> object -> update NA, which requires an + # additional pass over the data. + na_values = isna(values) + subarr2 = subarr.astype(object) + subarr2[na_values] = np.asarray(values, dtype=object)[na_values] + subarr = subarr2 + + return subarr diff --git a/pandas/core/series.py b/pandas/core/series.py index 2ba1f15044952..0450f28087f66 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -40,6 +40,7 @@ maybe_convert_platform, maybe_cast_to_datetime, maybe_castable, construct_1d_arraylike_from_scalar, + construct_1d_ndarray_preserving_na, construct_1d_object_array_from_listlike) from pandas.core.dtypes.missing import ( isna, @@ -4074,7 +4075,8 @@ def _try_cast(arr, take_fast_path): isinstance(subarr, np.ndarray))): subarr = construct_1d_object_array_from_listlike(subarr) elif not is_extension_type(subarr): - subarr = np.array(subarr, dtype=dtype, copy=copy) + subarr = construct_1d_ndarray_preserving_na(subarr, dtype, + copy=copy) except (ValueError, TypeError): if is_categorical_dtype(dtype): # We *do* allow casting to categorical, since we know diff --git a/pandas/tests/dtypes/test_cast.py b/pandas/tests/dtypes/test_cast.py index 20cd8b43478d2..4a19682e2c558 100644 --- a/pandas/tests/dtypes/test_cast.py +++ b/pandas/tests/dtypes/test_cast.py @@ -23,6 +23,7 @@ maybe_convert_scalar, find_common_type, construct_1d_object_array_from_listlike, + construct_1d_ndarray_preserving_na, construct_1d_arraylike_from_scalar) from pandas.core.dtypes.dtypes import ( CategoricalDtype, @@ -440,3 +441,15 @@ def test_cast_1d_arraylike_from_scalar_categorical(self): tm.assert_categorical_equal(result, expected, check_category_order=True, check_dtype=True) + + +@pytest.mark.parametrize('values, dtype, expected', [ + ([1, 2, 3], None, np.array([1, 2, 3])), + (np.array([1, 2, 3]), None, np.array([1, 2, 3])), + (['1', '2', None], None, np.array(['1', '2', None])), + (['1', '2', None], np.dtype('str'), np.array(['1', '2', None])), + ([1, 2, None], np.dtype('str'), np.array(['1', '2', None])), +]) +def test_construct_1d_ndarray_preserving_na(values, dtype, expected): + result = construct_1d_ndarray_preserving_na(values, dtype=dtype) + tm.assert_numpy_array_equal(result, expected) diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index 300e1acdea911..e7fb765128738 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -151,6 +151,17 @@ def test_constructor_complex_dtypes(self): assert a.dtype == df.a.dtype assert b.dtype == df.b.dtype + def test_constructor_dtype_str_na_values(self, string_dtype): + # https://github.com/pandas-dev/pandas/issues/21083 + df = DataFrame({'A': ['x', None]}, dtype=string_dtype) + result = df.isna() + expected = DataFrame({"A": [False, True]}) + tm.assert_frame_equal(result, expected) + assert df.iloc[1, 0] is None + + df = DataFrame({'A': ['x', np.nan]}, dtype=string_dtype) + assert np.isnan(df.iloc[1, 0]) + def test_constructor_rec(self): rec = self.frame.to_records(index=False) diff --git a/pandas/tests/frame/test_dtypes.py b/pandas/tests/frame/test_dtypes.py index 4c9f8c2ea0980..1eeeec0be3b8b 100644 --- a/pandas/tests/frame/test_dtypes.py +++ b/pandas/tests/frame/test_dtypes.py @@ -794,22 +794,26 @@ def test_arg_for_errors_in_astype(self): @pytest.mark.parametrize('input_vals', [ ([1, 2]), - ([1.0, 2.0, np.nan]), (['1', '2']), (list(pd.date_range('1/1/2011', periods=2, freq='H'))), (list(pd.date_range('1/1/2011', periods=2, freq='H', tz='US/Eastern'))), ([pd.Interval(left=0, right=5)]), ]) - def test_constructor_list_str(self, input_vals): + def test_constructor_list_str(self, input_vals, string_dtype): # GH 16605 # Ensure that data elements are converted to strings when # dtype is str, 'str', or 'U' - for dtype in ['str', str, 'U']: - result = DataFrame({'A': input_vals}, dtype=dtype) - expected = DataFrame({'A': input_vals}).astype({'A': dtype}) - assert_frame_equal(result, expected) + result = DataFrame({'A': input_vals}, dtype=string_dtype) + expected = DataFrame({'A': input_vals}).astype({'A': string_dtype}) + assert_frame_equal(result, expected) + + def test_constructor_list_str_na(self, string_dtype): + + result = DataFrame({"A": [1.0, 2.0, None]}, dtype=string_dtype) + expected = DataFrame({"A": ['1.0', '2.0', None]}, dtype=object) + assert_frame_equal(result, expected) class TestDataFrameDatetimeWithTZ(TestData): diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index 14ae1ef42865a..aba472f2ce8f9 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -1829,7 +1829,7 @@ def test_mode_str_obj(self, dropna, expected1, expected2, expected3): data = ['foo', 'bar', 'bar', np.nan, np.nan, np.nan] - s = Series(data, dtype=str) + s = Series(data, dtype=object).astype(str) result = s.mode(dropna) expected3 = Series(expected3, dtype=str) tm.assert_series_equal(result, expected3) diff --git a/pandas/tests/series/test_constructors.py b/pandas/tests/series/test_constructors.py index 7e59325c32ddc..906d2aacd5586 100644 --- a/pandas/tests/series/test_constructors.py +++ b/pandas/tests/series/test_constructors.py @@ -137,6 +137,17 @@ def test_constructor_no_data_index_order(self): result = pd.Series(index=['b', 'a', 'c']) assert result.index.tolist() == ['b', 'a', 'c'] + def test_constructor_dtype_str_na_values(self, string_dtype): + # https://github.com/pandas-dev/pandas/issues/21083 + ser = Series(['x', None], dtype=string_dtype) + result = ser.isna() + expected = Series([False, True]) + tm.assert_series_equal(result, expected) + assert ser.iloc[1] is None + + ser = Series(['x', np.nan], dtype=string_dtype) + assert np.isnan(ser.iloc[1]) + def test_constructor_series(self): index1 = ['d', 'b', 'a', 'c'] index2 = sorted(index1) @@ -164,22 +175,25 @@ def test_constructor_list_like(self): @pytest.mark.parametrize('input_vals', [ ([1, 2]), - ([1.0, 2.0, np.nan]), (['1', '2']), (list(pd.date_range('1/1/2011', periods=2, freq='H'))), (list(pd.date_range('1/1/2011', periods=2, freq='H', tz='US/Eastern'))), ([pd.Interval(left=0, right=5)]), ]) - def test_constructor_list_str(self, input_vals): + def test_constructor_list_str(self, input_vals, string_dtype): # GH 16605 # Ensure that data elements from a list are converted to strings # when dtype is str, 'str', or 'U' + result = Series(input_vals, dtype=string_dtype) + expected = Series(input_vals).astype(string_dtype) + assert_series_equal(result, expected) - for dtype in ['str', str, 'U']: - result = Series(input_vals, dtype=dtype) - expected = Series(input_vals).astype(dtype) - assert_series_equal(result, expected) + def test_constructor_list_str_na(self, string_dtype): + result = Series([1.0, 2.0, np.nan], dtype=string_dtype) + expected = Series(['1.0', '2.0', np.nan], dtype=object) + assert_series_equal(result, expected) + assert np.isnan(result[2]) def test_constructor_generator(self): gen = (i for i in range(10))
```python In [1]: import pandas as pd In [2]: pd.Series([1, 2, None], dtype='str')[2] # None ``` Closes #21083
https://api.github.com/repos/pandas-dev/pandas/pulls/21366
2018-06-07T18:59:58Z
2018-06-08T16:27:14Z
2018-06-08T16:27:14Z
2018-06-12T16:30:40Z
Fix #21356: JSON nested_to_record Silently Drops Top-Level None Values
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index 807b83fa2cf69..8ce2824d779f4 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -31,6 +31,7 @@ Fixed Regressions - Fixed regression in constructors coercing NA values like ``None`` to strings when passing ``dtype=str`` (:issue:`21083`) - Regression in :func:`pivot_table` where an ordered ``Categorical`` with missing values for the pivot's ``index`` would give a mis-aligned result (:issue:`21133`) +- Fixed Regression in :func:`nested_to_record` which now flattens list of dictionaries and doesnot drop keys with value as `None` (:issue:`21356`) .. _whatsnew_0231.performance: diff --git a/pandas/io/json/normalize.py b/pandas/io/json/normalize.py index 17393d458e746..b845a43b9ca9e 100644 --- a/pandas/io/json/normalize.py +++ b/pandas/io/json/normalize.py @@ -80,8 +80,6 @@ def nested_to_record(ds, prefix="", sep=".", level=0): if level != 0: # so we skip copying for top level, common case v = new_d.pop(k) new_d[newkey] = v - elif v is None: # pop the key if the value is None - new_d.pop(k) continue else: v = new_d.pop(k) diff --git a/pandas/tests/io/json/test_normalize.py b/pandas/tests/io/json/test_normalize.py index dc34ba81f679d..395c2c90767d3 100644 --- a/pandas/tests/io/json/test_normalize.py +++ b/pandas/tests/io/json/test_normalize.py @@ -238,15 +238,16 @@ def test_non_ascii_key(self): tm.assert_frame_equal(result, expected) def test_missing_field(self, author_missing_data): - # GH20030: Checks for robustness of json_normalize - should - # unnest records where only the first record has a None value + # GH20030: result = json_normalize(author_missing_data) ex_data = [ - {'author_name.first': np.nan, + {'info': np.nan, + 'author_name.first': np.nan, 'author_name.last_name': np.nan, 'info.created_at': np.nan, 'info.last_updated': np.nan}, - {'author_name.first': 'Jane', + {'info': None, + 'author_name.first': 'Jane', 'author_name.last_name': 'Doe', 'info.created_at': '11/08/1993', 'info.last_updated': '26/05/2012'} @@ -351,9 +352,8 @@ def test_json_normalize_errors(self): errors='raise' ) - def test_nonetype_dropping(self): - # GH20030: Checks that None values are dropped in nested_to_record - # to prevent additional columns of nans when passed to DataFrame + def test_donot_drop_nonevalues(self): + # GH21356 data = [ {'info': None, 'author_name': @@ -367,7 +367,8 @@ def test_nonetype_dropping(self): ] result = nested_to_record(data) expected = [ - {'author_name.first': 'Smith', + {'info': None, + 'author_name.first': 'Smith', 'author_name.last_name': 'Appleseed'}, {'author_name.first': 'Jane', 'author_name.last_name': 'Doe', @@ -395,6 +396,7 @@ def test_nonetype_top_level_bottom_level(self): } result = nested_to_record(data) expected = { + 'id': None, 'location.country.state.id': None, 'location.country.state.town.info.id': None, 'location.country.state.town.info.region': None, @@ -423,6 +425,7 @@ def test_nonetype_multiple_levels(self): } result = nested_to_record(data) expected = { + 'id': None, 'location.id': None, 'location.country.id': None, 'location.country.state.id': None,
- [x] closes #21356 - [x] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21363
2018-06-07T18:25:30Z
2018-06-08T16:50:21Z
2018-06-08T16:50:20Z
2018-06-12T16:30:39Z
BUG: Fixed concat warning message
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index 09b711c80910c..ead4fac14182d 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -74,6 +74,7 @@ I/O Reshaping - Bug in :func:`concat` where error was raised in concatenating :class:`Series` with numpy scalar and tuple names (:issue:`21015`) +- Bug in :func:`concat` warning message providing the wrong guidance for future behavior (:issue:`21101`) Other diff --git a/pandas/core/indexes/api.py b/pandas/core/indexes/api.py index f9501cd2f9ddf..6f4fdfe5bf5cd 100644 --- a/pandas/core/indexes/api.py +++ b/pandas/core/indexes/api.py @@ -24,9 +24,9 @@ Sorting because non-concatenation axis is not aligned. A future version of pandas will change to not sort by default. -To accept the future behavior, pass 'sort=True'. +To accept the future behavior, pass 'sort=False'. -To retain the current behavior and silence the warning, pass sort=False +To retain the current behavior and silence the warning, pass 'sort=True'. """)
- [x] closes #21101 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21362
2018-06-07T18:08:48Z
2018-06-07T21:21:09Z
2018-06-07T21:21:08Z
2018-06-12T16:30:39Z
Revert change to comparison op with datetime.date objects
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index 5a1bcce9b5970..3cebcc56e9083 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -10,12 +10,52 @@ and bug fixes. We recommend that all users upgrade to this version. :local: :backlinks: none - .. _whatsnew_0231.fixed_regressions: Fixed Regressions ~~~~~~~~~~~~~~~~~ +**Comparing Series with datetime.date** + +We've reverted a 0.23.0 change to comparing a :class:`Series` holding datetimes and a ``datetime.date`` object (:issue:`21152`). +In pandas 0.22 and earlier, comparing a Series holding datetimes and ``datetime.date`` objects would coerce the ``datetime.date`` to a datetime before comapring. +This was inconsistent with Python, NumPy, and :class:`DatetimeIndex`, which never consider a datetime and ``datetime.date`` equal. + +In 0.23.0, we unified operations between DatetimeIndex and Series, and in the process changed comparisons between a Series of datetimes and ``datetime.date`` without warning. + +We've temporarily restored the 0.22.0 behavior, so datetimes and dates may again compare equal, but restore the 0.23.0 behavior in a future release. + +To summarize, here's the behavior in 0.22.0, 0.23.0, 0.23.1: + +.. code-block:: python + + # 0.22.0... Silently coerce the datetime.date + >>> Series(pd.date_range('2017', periods=2)) == datetime.date(2017, 1, 1) + 0 True + 1 False + dtype: bool + + # 0.23.0... Do not coerce the datetime.date + >>> Series(pd.date_range('2017', periods=2)) == datetime.date(2017, 1, 1) + 0 False + 1 False + dtype: bool + + # 0.23.1... Coerce the datetime.date with a warning + >>> Series(pd.date_range('2017', periods=2)) == datetime.date(2017, 1, 1) + /bin/python:1: FutureWarning: Comparing Series of datetimes with 'datetime.date'. Currently, the + 'datetime.date' is coerced to a datetime. In the future pandas will + not coerce, and the values not compare equal to the 'datetime.date'. + To retain the current behavior, convert the 'datetime.date' to a + datetime with 'pd.Timestamp'. + #!/bin/python3 + 0 True + 1 False + dtype: bool + +In addition, ordering comparisons will raise a ``TypeError`` in the future. + +**Other Fixes** - Reverted the ability of :func:`~DataFrame.to_sql` to perform multivalue inserts as this caused regression in certain cases (:issue:`21103`). diff --git a/pandas/core/ops.py b/pandas/core/ops.py index e14f82906cd06..540ebeee438f6 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -5,7 +5,10 @@ """ # necessary to enforce truediv in Python 2.X from __future__ import division +import datetime import operator +import textwrap +import warnings import numpy as np import pandas as pd @@ -1197,8 +1200,35 @@ def wrapper(self, other, axis=None): if is_datetime64_dtype(self) or is_datetime64tz_dtype(self): # Dispatch to DatetimeIndex to ensure identical # Series/Index behavior + if (isinstance(other, datetime.date) and + not isinstance(other, datetime.datetime)): + # https://github.com/pandas-dev/pandas/issues/21152 + # Compatibility for difference between Series comparison w/ + # datetime and date + msg = ( + "Comparing Series of datetimes with 'datetime.date'. " + "Currently, the 'datetime.date' is coerced to a " + "datetime. In the future pandas will not coerce, " + "and {future}. " + "To retain the current behavior, " + "convert the 'datetime.date' to a datetime with " + "'pd.Timestamp'." + ) + + if op in {operator.lt, operator.le, operator.gt, operator.ge}: + future = "a TypeError will be raised" + else: + future = ( + "'the values will not compare equal to the " + "'datetime.date'" + ) + msg = '\n'.join(textwrap.wrap(msg.format(future=future))) + warnings.warn(msg, FutureWarning, stacklevel=2) + other = pd.Timestamp(other) + res_values = dispatch_to_index_op(op, self, other, pd.DatetimeIndex) + return self._constructor(res_values, index=self.index, name=res_name) diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index ec0d7296e540e..95836f046195a 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -88,6 +88,46 @@ def test_ser_cmp_result_names(self, names, op): class TestTimestampSeriesComparison(object): + def test_dt64_ser_cmp_date_warning(self): + # https://github.com/pandas-dev/pandas/issues/21359 + # Remove this test and enble invalid test below + ser = pd.Series(pd.date_range('20010101', periods=10), name='dates') + date = ser.iloc[0].to_pydatetime().date() + + with tm.assert_produces_warning(FutureWarning) as m: + result = ser == date + expected = pd.Series([True] + [False] * 9, name='dates') + tm.assert_series_equal(result, expected) + assert "Comparing Series of datetimes " in str(m[0].message) + assert "will not compare equal" in str(m[0].message) + + with tm.assert_produces_warning(FutureWarning) as m: + result = ser != date + tm.assert_series_equal(result, ~expected) + assert "will not compare equal" in str(m[0].message) + + with tm.assert_produces_warning(FutureWarning) as m: + result = ser <= date + tm.assert_series_equal(result, expected) + assert "a TypeError will be raised" in str(m[0].message) + + with tm.assert_produces_warning(FutureWarning) as m: + result = ser < date + tm.assert_series_equal(result, pd.Series([False] * 10, name='dates')) + assert "a TypeError will be raised" in str(m[0].message) + + with tm.assert_produces_warning(FutureWarning) as m: + result = ser >= date + tm.assert_series_equal(result, pd.Series([True] * 10, name='dates')) + assert "a TypeError will be raised" in str(m[0].message) + + with tm.assert_produces_warning(FutureWarning) as m: + result = ser > date + tm.assert_series_equal(result, pd.Series([False] + [True] * 9, + name='dates')) + assert "a TypeError will be raised" in str(m[0].message) + + @pytest.mark.skip(reason="GH-21359") def test_dt64ser_cmp_date_invalid(self): # GH#19800 datetime.date comparison raises to # match DatetimeIndex/Timestamp. This also matches the behavior
- [x] closes #21152 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry cc @jbrockmendel, @innominate227 FYI, @jorisvandenbossche the whatsnew will conflict with your other PR
https://api.github.com/repos/pandas-dev/pandas/pulls/21361
2018-06-07T18:01:46Z
2018-06-08T16:54:37Z
2018-06-08T16:54:37Z
2018-06-12T16:30:39Z
Revert "enable multivalues insert (#19664)"
diff --git a/doc/source/io.rst b/doc/source/io.rst index 7bd56d52b3492..32129147ee281 100644 --- a/doc/source/io.rst +++ b/doc/source/io.rst @@ -4719,12 +4719,6 @@ writes ``data`` to the database in batches of 1000 rows at a time: data.to_sql('data_chunked', engine, chunksize=1000) -.. note:: - - The function :func:`~pandas.DataFrame.to_sql` will perform a multi-value - insert if the engine dialect ``supports_multivalues_insert``. This will - greatly speed up the insert in some cases. - SQL data types ++++++++++++++ diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index ead4fac14182d..2b64ef32c1eb6 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -16,6 +16,10 @@ and bug fixes. We recommend that all users upgrade to this version. Fixed Regressions ~~~~~~~~~~~~~~~~~ + +- Reverted the ability of :func:`~DataFrame.to_sql` to perform multivalue + inserts as this caused regression in certain cases (:issue:`21103`). + In the future this will be made configurable. - Fixed regression in the :attr:`DatetimeIndex.date` and :attr:`DatetimeIndex.time` attributes in case of timezone-aware data: :attr:`DatetimeIndex.time` returned a tz-aware time instead of tz-naive (:issue:`21267`) and :attr:`DatetimeIndex.date` diff --git a/pandas/io/sql.py b/pandas/io/sql.py index ccb8d2d99d734..a582d32741ae9 100644 --- a/pandas/io/sql.py +++ b/pandas/io/sql.py @@ -572,29 +572,8 @@ def create(self): else: self._execute_create() - def insert_statement(self, data, conn): - """ - Generate tuple of SQLAlchemy insert statement and any arguments - to be executed by connection (via `_execute_insert`). - - Parameters - ---------- - conn : SQLAlchemy connectable(engine/connection) - Connection to recieve the data - data : list of dict - The data to be inserted - - Returns - ------- - SQLAlchemy statement - insert statement - *, optional - Additional parameters to be passed when executing insert statement - """ - dialect = getattr(conn, 'dialect', None) - if dialect and getattr(dialect, 'supports_multivalues_insert', False): - return self.table.insert(data), - return self.table.insert(), data + def insert_statement(self): + return self.table.insert() def insert_data(self): if self.index is not None: @@ -633,9 +612,8 @@ def insert_data(self): return column_names, data_list def _execute_insert(self, conn, keys, data_iter): - """Insert data into this table with database connection""" data = [{k: v for k, v in zip(keys, row)} for row in data_iter] - conn.execute(*self.insert_statement(data, conn)) + conn.execute(self.insert_statement(), data) def insert(self, chunksize=None): keys, data_list = self.insert_data() diff --git a/pandas/tests/io/test_sql.py b/pandas/tests/io/test_sql.py index 4530cc9d2fba9..f3ab74d37a2bc 100644 --- a/pandas/tests/io/test_sql.py +++ b/pandas/tests/io/test_sql.py @@ -1665,29 +1665,6 @@ class Temporary(Base): tm.assert_frame_equal(df, expected) - def test_insert_multivalues(self): - # issues addressed - # https://github.com/pandas-dev/pandas/issues/14315 - # https://github.com/pandas-dev/pandas/issues/8953 - - db = sql.SQLDatabase(self.conn) - df = DataFrame({'A': [1, 0, 0], 'B': [1.1, 0.2, 4.3]}) - table = sql.SQLTable("test_table", db, frame=df) - data = [ - {'A': 1, 'B': 0.46}, - {'A': 0, 'B': -2.06} - ] - statement = table.insert_statement(data, conn=self.conn)[0] - - if self.supports_multivalues_insert: - assert statement.parameters == data, ( - 'insert statement should be multivalues' - ) - else: - assert statement.parameters is None, ( - 'insert statement should not be multivalues' - ) - class _TestSQLAlchemyConn(_EngineToConnMixin, _TestSQLAlchemy): @@ -1702,7 +1679,6 @@ class _TestSQLiteAlchemy(object): """ flavor = 'sqlite' - supports_multivalues_insert = True @classmethod def connect(cls): @@ -1751,7 +1727,6 @@ class _TestMySQLAlchemy(object): """ flavor = 'mysql' - supports_multivalues_insert = True @classmethod def connect(cls): @@ -1821,7 +1796,6 @@ class _TestPostgreSQLAlchemy(object): """ flavor = 'postgresql' - supports_multivalues_insert = True @classmethod def connect(cls):
This reverts commit 7c7bd569ce8e0f117c618d068e3d2798134dbc73. Reverts https://github.com/pandas-dev/pandas/pull/19664 Closes https://github.com/pandas-dev/pandas/issues/21103
https://api.github.com/repos/pandas-dev/pandas/pulls/21355
2018-06-07T14:13:38Z
2018-06-07T21:25:38Z
2018-06-07T21:25:38Z
2018-06-12T16:30:38Z
Fix typo in error message in the PlanePlot class
diff --git a/pandas/plotting/_core.py b/pandas/plotting/_core.py index 87b7d13251f28..d1a2121597dd6 100644 --- a/pandas/plotting/_core.py +++ b/pandas/plotting/_core.py @@ -811,7 +811,7 @@ class PlanePlot(MPLPlot): def __init__(self, data, x, y, **kwargs): MPLPlot.__init__(self, data, **kwargs) if x is None or y is None: - raise ValueError(self._kind + ' requires and x and y column') + raise ValueError(self._kind + ' requires an x and y column') if is_integer(x) and not self.data.columns.holds_integer(): x = self.data.columns[x] if is_integer(y) and not self.data.columns.holds_integer():
- [x] closes #21347 - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry Very simple fix, just a typo in an error message.
https://api.github.com/repos/pandas-dev/pandas/pulls/21350
2018-06-07T07:41:06Z
2018-06-07T11:23:33Z
2018-06-07T11:23:33Z
2018-06-12T16:30:38Z
make DateOffset immutable
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index a9c49b7476fa6..fd34424dedc52 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -67,6 +67,7 @@ Datetimelike API Changes ^^^^^^^^^^^^^^^^^^^^^^^^ - For :class:`DatetimeIndex` and :class:`TimedeltaIndex` with non-``None`` ``freq`` attribute, addition or subtraction of integer-dtyped array or ``Index`` will return an object of the same class (:issue:`19959`) +- :class:`DateOffset` objects are now immutable. Attempting to alter one of these will now raise ``AttributeError`` (:issue:`21341`) .. _whatsnew_0240.api.other: @@ -176,7 +177,6 @@ Timezones Offsets ^^^^^^^ -- - - diff --git a/pandas/_libs/tslibs/offsets.pyx b/pandas/_libs/tslibs/offsets.pyx index 3ca9bb307da9c..a9ef9166e4d33 100644 --- a/pandas/_libs/tslibs/offsets.pyx +++ b/pandas/_libs/tslibs/offsets.pyx @@ -304,6 +304,15 @@ class _BaseOffset(object): _day_opt = None _attributes = frozenset(['n', 'normalize']) + def __init__(self, n=1, normalize=False): + n = self._validate_n(n) + object.__setattr__(self, "n", n) + object.__setattr__(self, "normalize", normalize) + object.__setattr__(self, "_cache", {}) + + def __setattr__(self, name, value): + raise AttributeError("DateOffset objects are immutable.") + @property def kwds(self): # for backwards-compatibility @@ -395,13 +404,14 @@ class _BaseOffset(object): kwds = {key: odict[key] for key in odict if odict[key]} state.update(kwds) - self.__dict__ = state + self.__dict__.update(state) + if 'weekmask' in state and 'holidays' in state: calendar, holidays = _get_calendar(weekmask=self.weekmask, holidays=self.holidays, calendar=None) - self.calendar = calendar - self.holidays = holidays + object.__setattr__(self, "calendar", calendar) + object.__setattr__(self, "holidays", holidays) def __getstate__(self): """Return a pickleable state""" diff --git a/pandas/tests/tseries/offsets/test_offsets.py b/pandas/tests/tseries/offsets/test_offsets.py index 5dd2a199405bf..66cb9baeb9357 100644 --- a/pandas/tests/tseries/offsets/test_offsets.py +++ b/pandas/tests/tseries/offsets/test_offsets.py @@ -234,6 +234,14 @@ class TestCommon(Base): 'Nano': Timestamp(np_datetime64_compat( '2011-01-01T09:00:00.000000001Z'))} + def test_immutable(self, offset_types): + # GH#21341 check that __setattr__ raises + offset = self._get_offset(offset_types) + with pytest.raises(AttributeError): + offset.normalize = True + with pytest.raises(AttributeError): + offset.n = 91 + def test_return_type(self, offset_types): offset = self._get_offset(offset_types) diff --git a/pandas/tseries/offsets.py b/pandas/tseries/offsets.py index ffa2c0a5e3211..da8fdb4d79e34 100644 --- a/pandas/tseries/offsets.py +++ b/pandas/tseries/offsets.py @@ -23,7 +23,6 @@ ApplyTypeError, as_datetime, _is_normalized, _get_calendar, _to_dt64, - _determine_offset, apply_index_wraps, roll_yearday, shift_month, @@ -192,11 +191,14 @@ def __add__(date): normalize = False def __init__(self, n=1, normalize=False, **kwds): - self.n = self._validate_n(n) - self.normalize = normalize + BaseOffset.__init__(self, n, normalize) - self._offset, self._use_relativedelta = _determine_offset(kwds) - self.__dict__.update(kwds) + off, use_rd = liboffsets._determine_offset(kwds) + object.__setattr__(self, "_offset", off) + object.__setattr__(self, "_use_relativedelta", use_rd) + for key in kwds: + val = kwds[key] + object.__setattr__(self, key, val) @apply_wraps def apply(self, other): @@ -446,9 +448,9 @@ def __init__(self, weekmask, holidays, calendar): # following two attributes. See DateOffset._params() # holidays, weekmask - self.weekmask = weekmask - self.holidays = holidays - self.calendar = calendar + object.__setattr__(self, "weekmask", weekmask) + object.__setattr__(self, "holidays", holidays) + object.__setattr__(self, "calendar", calendar) class BusinessMixin(object): @@ -480,9 +482,8 @@ class BusinessDay(BusinessMixin, SingleConstructorOffset): _attributes = frozenset(['n', 'normalize', 'offset']) def __init__(self, n=1, normalize=False, offset=timedelta(0)): - self.n = self._validate_n(n) - self.normalize = normalize - self._offset = offset + BaseOffset.__init__(self, n, normalize) + object.__setattr__(self, "_offset", offset) def _offset_str(self): def get_str(td): @@ -578,9 +579,11 @@ class BusinessHourMixin(BusinessMixin): def __init__(self, start='09:00', end='17:00', offset=timedelta(0)): # must be validated here to equality check - self.start = liboffsets._validate_business_time(start) - self.end = liboffsets._validate_business_time(end) - self._offset = offset + start = liboffsets._validate_business_time(start) + object.__setattr__(self, "start", start) + end = liboffsets._validate_business_time(end) + object.__setattr__(self, "end", end) + object.__setattr__(self, "_offset", offset) @cache_readonly def next_bday(self): @@ -807,8 +810,7 @@ class BusinessHour(BusinessHourMixin, SingleConstructorOffset): def __init__(self, n=1, normalize=False, start='09:00', end='17:00', offset=timedelta(0)): - self.n = self._validate_n(n) - self.normalize = normalize + BaseOffset.__init__(self, n, normalize) super(BusinessHour, self).__init__(start=start, end=end, offset=offset) @@ -837,9 +839,8 @@ class CustomBusinessDay(_CustomMixin, BusinessDay): def __init__(self, n=1, normalize=False, weekmask='Mon Tue Wed Thu Fri', holidays=None, calendar=None, offset=timedelta(0)): - self.n = self._validate_n(n) - self.normalize = normalize - self._offset = offset + BaseOffset.__init__(self, n, normalize) + object.__setattr__(self, "_offset", offset) _CustomMixin.__init__(self, weekmask, holidays, calendar) @@ -898,9 +899,8 @@ class CustomBusinessHour(_CustomMixin, BusinessHourMixin, def __init__(self, n=1, normalize=False, weekmask='Mon Tue Wed Thu Fri', holidays=None, calendar=None, start='09:00', end='17:00', offset=timedelta(0)): - self.n = self._validate_n(n) - self.normalize = normalize - self._offset = offset + BaseOffset.__init__(self, n, normalize) + object.__setattr__(self, "_offset", offset) _CustomMixin.__init__(self, weekmask, holidays, calendar) BusinessHourMixin.__init__(self, start=start, end=end, offset=offset) @@ -914,9 +914,7 @@ class MonthOffset(SingleConstructorOffset): _adjust_dst = True _attributes = frozenset(['n', 'normalize']) - def __init__(self, n=1, normalize=False): - self.n = self._validate_n(n) - self.normalize = normalize + __init__ = BaseOffset.__init__ @property def name(self): @@ -995,9 +993,8 @@ class _CustomBusinessMonth(_CustomMixin, BusinessMixin, MonthOffset): def __init__(self, n=1, normalize=False, weekmask='Mon Tue Wed Thu Fri', holidays=None, calendar=None, offset=timedelta(0)): - self.n = self._validate_n(n) - self.normalize = normalize - self._offset = offset + BaseOffset.__init__(self, n, normalize) + object.__setattr__(self, "_offset", offset) _CustomMixin.__init__(self, weekmask, holidays, calendar) @@ -1074,18 +1071,18 @@ class SemiMonthOffset(DateOffset): _attributes = frozenset(['n', 'normalize', 'day_of_month']) def __init__(self, n=1, normalize=False, day_of_month=None): + BaseOffset.__init__(self, n, normalize) + if day_of_month is None: - self.day_of_month = self._default_day_of_month + object.__setattr__(self, "day_of_month", + self._default_day_of_month) else: - self.day_of_month = int(day_of_month) + object.__setattr__(self, "day_of_month", int(day_of_month)) if not self._min_day_of_month <= self.day_of_month <= 27: msg = 'day_of_month must be {min}<=day_of_month<=27, got {day}' raise ValueError(msg.format(min=self._min_day_of_month, day=self.day_of_month)) - self.n = self._validate_n(n) - self.normalize = normalize - @classmethod def _from_name(cls, suffix=None): return cls(day_of_month=suffix) @@ -1291,9 +1288,8 @@ class Week(DateOffset): _attributes = frozenset(['n', 'normalize', 'weekday']) def __init__(self, n=1, normalize=False, weekday=None): - self.n = self._validate_n(n) - self.normalize = normalize - self.weekday = weekday + BaseOffset.__init__(self, n, normalize) + object.__setattr__(self, "weekday", weekday) if self.weekday is not None: if self.weekday < 0 or self.weekday > 6: @@ -1421,10 +1417,9 @@ class WeekOfMonth(_WeekOfMonthMixin, DateOffset): _attributes = frozenset(['n', 'normalize', 'week', 'weekday']) def __init__(self, n=1, normalize=False, week=0, weekday=0): - self.n = self._validate_n(n) - self.normalize = normalize - self.weekday = weekday - self.week = week + BaseOffset.__init__(self, n, normalize) + object.__setattr__(self, "weekday", weekday) + object.__setattr__(self, "week", week) if self.weekday < 0 or self.weekday > 6: raise ValueError('Day must be 0<=day<=6, got {day}' @@ -1493,9 +1488,8 @@ class LastWeekOfMonth(_WeekOfMonthMixin, DateOffset): _attributes = frozenset(['n', 'normalize', 'weekday']) def __init__(self, n=1, normalize=False, weekday=0): - self.n = self._validate_n(n) - self.normalize = normalize - self.weekday = weekday + BaseOffset.__init__(self, n, normalize) + object.__setattr__(self, "weekday", weekday) if self.n == 0: raise ValueError('N cannot be 0') @@ -1553,11 +1547,11 @@ class QuarterOffset(DateOffset): # startingMonth vs month attr names are resolved def __init__(self, n=1, normalize=False, startingMonth=None): - self.n = self._validate_n(n) - self.normalize = normalize + BaseOffset.__init__(self, n, normalize) + if startingMonth is None: startingMonth = self._default_startingMonth - self.startingMonth = startingMonth + object.__setattr__(self, "startingMonth", startingMonth) def isAnchored(self): return (self.n == 1 and self.startingMonth is not None) @@ -1679,11 +1673,10 @@ def onOffset(self, dt): return dt.month == self.month and dt.day == self._get_offset_day(dt) def __init__(self, n=1, normalize=False, month=None): - self.n = self._validate_n(n) - self.normalize = normalize + BaseOffset.__init__(self, n, normalize) month = month if month is not None else self._default_month - self.month = month + object.__setattr__(self, "month", month) if self.month < 1 or self.month > 12: raise ValueError('Month must go from 1 to 12') @@ -1776,12 +1769,11 @@ class FY5253(DateOffset): def __init__(self, n=1, normalize=False, weekday=0, startingMonth=1, variation="nearest"): - self.n = self._validate_n(n) - self.normalize = normalize - self.startingMonth = startingMonth - self.weekday = weekday + BaseOffset.__init__(self, n, normalize) + object.__setattr__(self, "startingMonth", startingMonth) + object.__setattr__(self, "weekday", weekday) - self.variation = variation + object.__setattr__(self, "variation", variation) if self.n == 0: raise ValueError('N cannot be 0') @@ -1976,13 +1968,12 @@ class FY5253Quarter(DateOffset): def __init__(self, n=1, normalize=False, weekday=0, startingMonth=1, qtr_with_extra_week=1, variation="nearest"): - self.n = self._validate_n(n) - self.normalize = normalize + BaseOffset.__init__(self, n, normalize) - self.weekday = weekday - self.startingMonth = startingMonth - self.qtr_with_extra_week = qtr_with_extra_week - self.variation = variation + object.__setattr__(self, "startingMonth", startingMonth) + object.__setattr__(self, "weekday", weekday) + object.__setattr__(self, "qtr_with_extra_week", qtr_with_extra_week) + object.__setattr__(self, "variation", variation) if self.n == 0: raise ValueError('N cannot be 0') @@ -2129,9 +2120,7 @@ class Easter(DateOffset): _adjust_dst = True _attributes = frozenset(['n', 'normalize']) - def __init__(self, n=1, normalize=False): - self.n = self._validate_n(n) - self.normalize = normalize + __init__ = BaseOffset.__init__ @apply_wraps def apply(self, other): @@ -2177,11 +2166,10 @@ class Tick(SingleConstructorOffset): _attributes = frozenset(['n', 'normalize']) def __init__(self, n=1, normalize=False): - self.n = self._validate_n(n) + BaseOffset.__init__(self, n, normalize) if normalize: raise ValueError("Tick offset with `normalize=True` are not " "allowed.") # GH#21427 - self.normalize = normalize __gt__ = _tick_comp(operator.gt) __ge__ = _tick_comp(operator.ge)
Returning to the long-standing goal of making `DateOffset`s immutable (recall: `DateOffset.__eq__` calls `DateOffset._params` which is _very_ slow. `_params` can't be cached ATM because `DateOffset` is mutable`) Earlier attempts in this direction tried to make the base class a `cdef class`, but that has run into `pickle` problems that I haven't been able to sort out so far. This PR goes the patch-`__setattr__` route instead. Note: this PR does _not_ implement the caching that is the underlying goal. I'm likely to make some other PRs in this area, will try to keep them orthogonal.
https://api.github.com/repos/pandas-dev/pandas/pulls/21341
2018-06-06T16:10:10Z
2018-06-21T10:24:21Z
2018-06-21T10:24:21Z
2018-06-22T03:27:26Z
Series.describe returns first and last for tz-aware datetimes
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 691345ad26e58..c609cb04db028 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -316,6 +316,7 @@ Timezones - Bug in :class:`Series` constructor which would coerce tz-aware and tz-naive :class:`Timestamp`s to tz-aware (:issue:`13051`) - Bug in :class:`Index` with ``datetime64[ns, tz]`` dtype that did not localize integer data correctly (:issue:`20964`) - Bug in :class:`DatetimeIndex` where constructing with an integer and tz would not localize correctly (:issue:`12619`) +- Fixed bug where :meth:`DataFrame.describe` and :meth:`Series.describe` on tz-aware datetimes did not show `first` and `last` result (:issue:`21328`) Offsets ^^^^^^^ diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 818dd1b408518..65ca467a05840 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -20,7 +20,7 @@ is_bool_dtype, is_categorical_dtype, is_numeric_dtype, - is_datetime64_dtype, + is_datetime64_any_dtype, is_timedelta64_dtype, is_datetime64tz_dtype, is_list_like, @@ -8531,12 +8531,13 @@ def describe_categorical_1d(data): if result[1] > 0: top, freq = objcounts.index[0], objcounts.iloc[0] - if is_datetime64_dtype(data): + if is_datetime64_any_dtype(data): + tz = data.dt.tz asint = data.dropna().values.view('i8') names += ['top', 'freq', 'first', 'last'] - result += [tslib.Timestamp(top), freq, - tslib.Timestamp(asint.min()), - tslib.Timestamp(asint.max())] + result += [tslib.Timestamp(top, tz=tz), freq, + tslib.Timestamp(asint.min(), tz=tz), + tslib.Timestamp(asint.max(), tz=tz)] else: names += ['top', 'freq'] result += [top, freq] diff --git a/pandas/tests/frame/test_analytics.py b/pandas/tests/frame/test_analytics.py index d357208813dd8..c0e9b89c1877f 100644 --- a/pandas/tests/frame/test_analytics.py +++ b/pandas/tests/frame/test_analytics.py @@ -417,6 +417,28 @@ def test_describe_timedelta_values(self): "max 5 days 00:00:00 0 days 05:00:00") assert repr(res) == exp_repr + def test_describe_tz_values(self, tz_naive_fixture): + # GH 21332 + tz = tz_naive_fixture + s1 = Series(range(5)) + start = Timestamp(2018, 1, 1) + end = Timestamp(2018, 1, 5) + s2 = Series(date_range(start, end, tz=tz)) + df = pd.DataFrame({'s1': s1, 's2': s2}) + + expected = DataFrame({'s1': [5, np.nan, np.nan, np.nan, np.nan, np.nan, + 2, 1.581139, 0, 1, 2, 3, 4], + 's2': [5, 5, s2.value_counts().index[0], 1, + start.tz_localize(tz), + end.tz_localize(tz), np.nan, np.nan, + np.nan, np.nan, np.nan, np.nan, np.nan]}, + index=['count', 'unique', 'top', 'freq', 'first', + 'last', 'mean', 'std', 'min', '25%', '50%', + '75%', 'max'] + ) + res = df.describe(include='all') + tm.assert_frame_equal(res, expected) + def test_reduce_mixed_frame(self): # GH 6806 df = DataFrame({ diff --git a/pandas/tests/series/test_analytics.py b/pandas/tests/series/test_analytics.py index fcfaff9b11002..b574b6dce930c 100644 --- a/pandas/tests/series/test_analytics.py +++ b/pandas/tests/series/test_analytics.py @@ -336,6 +336,23 @@ def test_describe(self): index=['count', 'unique', 'top', 'freq']) tm.assert_series_equal(result, expected) + def test_describe_with_tz(self, tz_naive_fixture): + # GH 21332 + tz = tz_naive_fixture + name = tz_naive_fixture + start = Timestamp(2018, 1, 1) + end = Timestamp(2018, 1, 5) + s = Series(date_range(start, end, tz=tz), name=name) + result = s.describe() + expected = Series( + [5, 5, s.value_counts().index[0], 1, start.tz_localize(tz), + end.tz_localize(tz) + ], + name=name, + index=['count', 'unique', 'top', 'freq', 'first', 'last'] + ) + tm.assert_series_equal(result, expected) + def test_argsort(self): self._check_accum_op('argsort', check_dtype=False) argsorted = self.ts.argsort()
GH issue 21328 - [x] closes #21328 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21332
2018-06-05T21:43:25Z
2018-07-06T22:57:52Z
2018-07-06T22:57:52Z
2018-07-07T01:42:11Z
DOC: fix mistake in Series.str.cat
diff --git a/pandas/core/strings.py b/pandas/core/strings.py index 5d50c45fe7eca..44811781837bc 100644 --- a/pandas/core/strings.py +++ b/pandas/core/strings.py @@ -2172,9 +2172,9 @@ def cat(self, others=None, sep=None, na_rep=None, join=None): Returns ------- - concat : str if `other is None`, Series/Index of objects if `others is - not None`. In the latter case, the result will remain categorical - if the calling Series/Index is categorical. + concat : str or Series/Index of objects + If `others` is None, `str` is returned, otherwise a `Series/Index` + (same type as caller) of objects is returned. See Also --------
Fix error in API-docstring that was introduced at the end of #20347 due to timepressure for the v.0.23-cutoff: removed functionality that categorical callers get categorical output, but forgot to adapt doc-string. Unfortunately, this survived both #20347 and the follow-up, but since v.0.23.1 is coming soon, I didn't wanna let this opportunity pass.
https://api.github.com/repos/pandas-dev/pandas/pulls/21330
2018-06-05T20:08:21Z
2018-06-06T15:08:23Z
2018-06-06T15:08:23Z
2018-06-12T16:30:38Z
Fixed Issue Preventing Agg on RollingGroupBy Objects
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 3b61fde77cb9f..a0eeb4c6288c8 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -783,6 +783,7 @@ Groupby/Resample/Rolling - Bug in :meth:`Series.resample` when passing ``numpy.timedelta64`` to ``loffset`` kwarg (:issue:`7687`). - Bug in :meth:`Resampler.asfreq` when frequency of ``TimedeltaIndex`` is a subperiod of a new frequency (:issue:`13022`). - Bug in :meth:`SeriesGroupBy.mean` when values were integral but could not fit inside of int64, overflowing instead. (:issue:`22487`) +- :func:`RollingGroupby.agg` and :func:`ExpandingGroupby.agg` now support multiple aggregation functions as parameters (:issue:`15072`) Sparse ^^^^^^ diff --git a/pandas/core/base.py b/pandas/core/base.py index 26fea89b45ae1..7f14a68503973 100644 --- a/pandas/core/base.py +++ b/pandas/core/base.py @@ -245,8 +245,8 @@ def _obj_with_exclusions(self): def __getitem__(self, key): if self._selection is not None: - raise Exception('Column(s) {selection} already selected' - .format(selection=self._selection)) + raise IndexError('Column(s) {selection} already selected' + .format(selection=self._selection)) if isinstance(key, (list, tuple, ABCSeries, ABCIndexClass, np.ndarray)): diff --git a/pandas/core/groupby/base.py b/pandas/core/groupby/base.py index 96c74f7fd4d75..ac84971de08d8 100644 --- a/pandas/core/groupby/base.py +++ b/pandas/core/groupby/base.py @@ -44,8 +44,15 @@ def _gotitem(self, key, ndim, subset=None): # we need to make a shallow copy of ourselves # with the same groupby kwargs = {attr: getattr(self, attr) for attr in self._attributes} + + # Try to select from a DataFrame, falling back to a Series + try: + groupby = self._groupby[key] + except IndexError: + groupby = self._groupby + self = self.__class__(subset, - groupby=self._groupby[key], + groupby=groupby, parent=self, **kwargs) self._reset_cache() diff --git a/pandas/tests/groupby/test_groupby.py b/pandas/tests/groupby/test_groupby.py index 483f814bc8383..3cdd0965ccfd0 100644 --- a/pandas/tests/groupby/test_groupby.py +++ b/pandas/tests/groupby/test_groupby.py @@ -623,8 +623,14 @@ def test_as_index_series_return_frame(df): assert isinstance(result2, DataFrame) assert_frame_equal(result2, expected2) - # corner case - pytest.raises(Exception, grouped['C'].__getitem__, 'D') + +def test_as_index_series_column_slice_raises(df): + # GH15072 + grouped = df.groupby('A', as_index=False) + msg = r"Column\(s\) C already selected" + + with tm.assert_raises_regex(IndexError, msg): + grouped['C'].__getitem__('D') def test_groupby_as_index_cython(df): diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index 052bfd2b858fb..cc663fc59cbf1 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -1,3 +1,4 @@ +from collections import OrderedDict from itertools import product import pytest import warnings @@ -314,6 +315,53 @@ def test_preserve_metadata(self): assert s2.name == 'foo' assert s3.name == 'foo' + @pytest.mark.parametrize("func,window_size,expected_vals", [ + ('rolling', 2, [[np.nan, np.nan, np.nan, np.nan], + [15., 20., 25., 20.], + [25., 30., 35., 30.], + [np.nan, np.nan, np.nan, np.nan], + [20., 30., 35., 30.], + [35., 40., 60., 40.], + [60., 80., 85., 80]]), + ('expanding', None, [[10., 10., 20., 20.], + [15., 20., 25., 20.], + [20., 30., 30., 20.], + [10., 10., 30., 30.], + [20., 30., 35., 30.], + [26.666667, 40., 50., 30.], + [40., 80., 60., 30.]])]) + def test_multiple_agg_funcs(self, func, window_size, expected_vals): + # GH 15072 + df = pd.DataFrame([ + ['A', 10, 20], + ['A', 20, 30], + ['A', 30, 40], + ['B', 10, 30], + ['B', 30, 40], + ['B', 40, 80], + ['B', 80, 90]], columns=['stock', 'low', 'high']) + + f = getattr(df.groupby('stock'), func) + if window_size: + window = f(window_size) + else: + window = f() + + index = pd.MultiIndex.from_tuples([ + ('A', 0), ('A', 1), ('A', 2), + ('B', 3), ('B', 4), ('B', 5), ('B', 6)], names=['stock', None]) + columns = pd.MultiIndex.from_tuples([ + ('low', 'mean'), ('low', 'max'), ('high', 'mean'), + ('high', 'min')]) + expected = pd.DataFrame(expected_vals, index=index, columns=columns) + + result = window.agg(OrderedDict(( + ('low', ['mean', 'max']), + ('high', ['mean', 'min']), + ))) + + tm.assert_frame_equal(result, expected) + @pytest.mark.filterwarnings("ignore:can't resolve package:ImportWarning") class TestWindow(Base):
- [X] closes #15072 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry AFAICT the fact that RollingGroupBy could not use `agg` with a list of functions is simply due to the fact that the GroupByMixing it inherits from could not handle the reduction in dimensions that occurs via the normal aggregation functions.
https://api.github.com/repos/pandas-dev/pandas/pulls/21323
2018-06-05T04:47:09Z
2018-09-26T10:35:55Z
2018-09-26T10:35:54Z
2020-01-16T00:34:29Z
BLD: include dll in package_data on Windows
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index 1a8b1603daaaa..18004be2b6b5f 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -132,3 +132,4 @@ Bug Fixes **Other** - Tab completion on :class:`Index` in IPython no longer outputs deprecation warnings (:issue:`21125`) +- Bug preventing pandas being used on Windows without C++ redistributable installed (:issue:`21106`) diff --git a/setup.py b/setup.py index 6febe674fb2a1..90ec8e91a0700 100755 --- a/setup.py +++ b/setup.py @@ -453,10 +453,10 @@ def pxd(name): return pjoin('pandas', name + '.pxd') -# args to ignore warnings if is_platform_windows(): extra_compile_args = [] else: + # args to ignore warnings extra_compile_args = ['-Wno-unused-function'] lib_depends = lib_depends + ['pandas/_libs/src/numpy_helper.h', @@ -733,7 +733,7 @@ def pxd(name): maintainer=AUTHOR, version=versioneer.get_version(), packages=find_packages(include=['pandas', 'pandas.*']), - package_data={'': ['data/*', 'templates/*'], + package_data={'': ['data/*', 'templates/*', '_libs/*.dll'], 'pandas.tests.io': ['data/legacy_hdf/*.h5', 'data/legacy_pickle/*/*.pickle', 'data/legacy_msgpack/*/*.msgpack',
- [x] closes #21106 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Not sure how to test this, but I believe should remove the runtime dependency by static linking against the MSVC++ runtime. @cgohlke any thoughts?
https://api.github.com/repos/pandas-dev/pandas/pulls/21321
2018-06-05T01:03:57Z
2018-06-08T23:32:21Z
2018-06-08T23:32:21Z
2018-06-12T16:30:38Z
BUG: Fix empty Data frames to JSON round-trippable back to data frames
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index 07120e26b4ecd..6118732768cb0 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -122,6 +122,7 @@ Bug Fixes - Bug in IO methods specifying ``compression='zip'`` which produced uncompressed zip archives (:issue:`17778`, :issue:`21144`) - Bug in :meth:`DataFrame.to_stata` which prevented exporting DataFrames to buffers and most file-like objects (:issue:`21041`) - Bug in :meth:`read_stata` and :class:`StataReader` which did not correctly decode utf-8 strings on Python 3 from Stata 14 files (dta version 118) (:issue:`21244`) +- Bug in IO JSON :func:`read_json` reading empty JSON schema with ``orient='table'`` back to :class:`DataFrame` caused an error (:issue:`21287`) **Reshaping** diff --git a/pandas/io/json/table_schema.py b/pandas/io/json/table_schema.py index 6f663f8ff8433..2dc176648fb31 100644 --- a/pandas/io/json/table_schema.py +++ b/pandas/io/json/table_schema.py @@ -296,7 +296,7 @@ def parse_table_schema(json, precise_float): """ table = loads(json, precise_float=precise_float) col_order = [field['name'] for field in table['schema']['fields']] - df = DataFrame(table['data'])[col_order] + df = DataFrame(table['data'], columns=col_order)[col_order] dtypes = {field['name']: convert_json_field_to_pandas_type(field) for field in table['schema']['fields']} diff --git a/pandas/tests/io/json/test_json_table_schema.py b/pandas/tests/io/json/test_json_table_schema.py index 49b39c17238ae..b6483d0e978ba 100644 --- a/pandas/tests/io/json/test_json_table_schema.py +++ b/pandas/tests/io/json/test_json_table_schema.py @@ -560,3 +560,16 @@ def test_multiindex(self, index_names): out = df.to_json(orient="table") result = pd.read_json(out, orient="table") tm.assert_frame_equal(df, result) + + @pytest.mark.parametrize("strict_check", [ + pytest.param(True, marks=pytest.mark.xfail), False]) + def test_empty_frame_roundtrip(self, strict_check): + # GH 21287 + df = pd.DataFrame([], columns=['a', 'b', 'c']) + expected = df.copy() + out = df.to_json(orient='table') + result = pd.read_json(out, orient='table') + # TODO: When DF coercion issue (#21345) is resolved tighten type checks + tm.assert_frame_equal(expected, result, + check_dtype=strict_check, + check_index_type=strict_check)
[x] closes #21287 [x] tests added / passed [x]passes git diff upstream/master -u -- "*.py" | flake8 --diff [x]whatsnew entry Fixes the bug occurring when empty DF, previously saved to JSON-file, is read from JSON back to DF.
https://api.github.com/repos/pandas-dev/pandas/pulls/21318
2018-06-04T19:23:28Z
2018-06-08T23:40:04Z
2018-06-08T23:40:03Z
2018-06-12T16:30:37Z
DOC: whatsnew note for MultiIndex Sorting Fix
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index 69b07d12c1e98..4f7f720c9004a 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -87,6 +87,7 @@ Indexing - Bug in :func:`interval_range` when ``start``/``periods`` or ``end``/``periods`` are specified with float ``start`` or ``end`` (:issue:`21161`) - Bug in :meth:`MultiIndex.set_names` where error raised for a ``MultiIndex`` with ``nlevels == 1`` (:issue:`21149`) - Bug in :class:`IntervalIndex` constructors where creating an ``IntervalIndex`` from categorical data was not fully supported (:issue:`21243`, issue:`21253`) +- Bug in :meth:`MultiIndex.sort_index` which was not guaranteed to sort correctly with ``level=1``; this was also causing data misalignment in particular :meth:`DataFrame.stack` operations (:issue:`20994`, :issue:`20945`, :issue:`21052`) - I/O
xref https://github.com/pandas-dev/pandas/pull/21043#issuecomment-394342149
https://api.github.com/repos/pandas-dev/pandas/pulls/21316
2018-06-04T16:32:58Z
2018-06-05T09:04:03Z
2018-06-05T09:04:02Z
2018-12-25T06:12:51Z
Make Period - Period return DateOffset instead of int
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index abf574ae109fd..41be4cb0053ff 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -69,6 +69,49 @@ Current Behavior: .. _whatsnew_0240.api.datetimelike: + +.. _whatsnew_0240.api.period_subtraction: + +Period Subtraction +^^^^^^^^^^^^^^^^^^ + +Subtraction of a ``Period`` from another ``Period`` will give a ``DateOffset``. +instead of an integer (:issue:`21314`) + +.. ipython:: python + + june = pd.Period('June 2018') + april = pd.Period('April 2018') + june - april + +Previous Behavior: + +.. code-block:: ipython + + In [2]: june = pd.Period('June 2018') + + In [3]: april = pd.Period('April 2018') + + In [4]: june - april + Out [4]: 2 + +Similarly, subtraction of a ``Period`` from a ``PeriodIndex`` will now return +an ``Index`` of ``DateOffset`` objects instead of an ``Int64Index`` + +.. ipython:: python + + pi = pd.period_range('June 2018', freq='M', periods=3) + pi - pi[0] + +Previous Behavior: + +.. code-block:: ipython + + In [2]: pi = pd.period_range('June 2018', freq='M', periods=3) + + In [3]: pi - pi[0] + Out[3]: Int64Index([0, 1, 2], dtype='int64') + Datetimelike API Changes ^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/pandas/_libs/tslibs/period.pyx b/pandas/_libs/tslibs/period.pyx index 49208056f88fe..6985d3b8df363 100644 --- a/pandas/_libs/tslibs/period.pyx +++ b/pandas/_libs/tslibs/period.pyx @@ -1123,9 +1123,12 @@ cdef class _Period(object): if other.freq != self.freq: msg = _DIFFERENT_FREQ.format(self.freqstr, other.freqstr) raise IncompatibleFrequency(msg) - return self.ordinal - other.ordinal + return (self.ordinal - other.ordinal) * self.freq elif getattr(other, '_typ', None) == 'periodindex': - return -other.__sub__(self) + # GH#21314 PeriodIndex - Period returns an object-index + # of DateOffset objects, for which we cannot use __neg__ + # directly, so we have to apply it pointwise + return other.__sub__(self).map(lambda x: -x) else: # pragma: no cover return NotImplemented elif is_period_object(other): diff --git a/pandas/core/indexes/datetimelike.py b/pandas/core/indexes/datetimelike.py index c7cb245263df8..a47dfe03445f5 100644 --- a/pandas/core/indexes/datetimelike.py +++ b/pandas/core/indexes/datetimelike.py @@ -899,7 +899,9 @@ def __add__(self, other): raise TypeError("cannot add {dtype}-dtype to {cls}" .format(dtype=other.dtype, cls=type(self).__name__)) - + elif is_categorical_dtype(other): + # Categorical op will raise; defer explicitly + return NotImplemented else: # pragma: no cover return NotImplemented @@ -964,6 +966,9 @@ def __sub__(self, other): raise TypeError("cannot subtract {dtype}-dtype from {cls}" .format(dtype=other.dtype, cls=type(self).__name__)) + elif is_categorical_dtype(other): + # Categorical op will raise; defer explicitly + return NotImplemented else: # pragma: no cover return NotImplemented diff --git a/pandas/core/indexes/period.py b/pandas/core/indexes/period.py index c163e3d53e634..d4d35d48743bd 100644 --- a/pandas/core/indexes/period.py +++ b/pandas/core/indexes/period.py @@ -551,13 +551,14 @@ def is_all_dates(self): @property def is_full(self): """ - Returns True if there are any missing periods from start to end + Returns True if this PeriodIndex is range-like in that all Periods + between start and end are present, in order. """ if len(self) == 0: return True if not self.is_monotonic: raise ValueError('Index is not monotonic') - values = self.values + values = self.asi8 return ((values[1:] - values[:-1]) < 2).all() @property @@ -761,17 +762,19 @@ def _sub_datelike(self, other): return NotImplemented def _sub_period(self, other): + # If the operation is well-defined, we return an object-Index + # of DateOffsets. Null entries are filled with pd.NaT if self.freq != other.freq: msg = _DIFFERENT_FREQ_INDEX.format(self.freqstr, other.freqstr) raise IncompatibleFrequency(msg) asi8 = self.asi8 new_data = asi8 - other.ordinal + new_data = np.array([self.freq * x for x in new_data]) if self.hasnans: - new_data = new_data.astype(np.float64) - new_data[self._isnan] = np.nan - # result must be Int64Index or Float64Index + new_data[self._isnan] = tslib.NaT + return Index(new_data) def shift(self, n): diff --git a/pandas/tests/frame/test_arithmetic.py b/pandas/tests/frame/test_arithmetic.py index 65afe85628f8e..fb381a5640519 100644 --- a/pandas/tests/frame/test_arithmetic.py +++ b/pandas/tests/frame/test_arithmetic.py @@ -258,9 +258,10 @@ def test_ops_frame_period(self): assert df['B'].dtype == object p = pd.Period('2015-03', freq='M') + off = p.freq # dtype will be object because of original dtype - exp = pd.DataFrame({'A': np.array([2, 1], dtype=object), - 'B': np.array([14, 13], dtype=object)}) + exp = pd.DataFrame({'A': np.array([2 * off, 1 * off], dtype=object), + 'B': np.array([14 * off, 13 * off], dtype=object)}) tm.assert_frame_equal(p - df, exp) tm.assert_frame_equal(df - p, -1 * exp) @@ -271,7 +272,7 @@ def test_ops_frame_period(self): assert df2['A'].dtype == object assert df2['B'].dtype == object - exp = pd.DataFrame({'A': np.array([4, 4], dtype=object), - 'B': np.array([16, 16], dtype=object)}) + exp = pd.DataFrame({'A': np.array([4 * off, 4 * off], dtype=object), + 'B': np.array([16 * off, 16 * off], dtype=object)}) tm.assert_frame_equal(df2 - df, exp) tm.assert_frame_equal(df - df2, -1 * exp) diff --git a/pandas/tests/indexes/period/test_arithmetic.py b/pandas/tests/indexes/period/test_arithmetic.py index aea019d910fe0..3a6ca14400dff 100644 --- a/pandas/tests/indexes/period/test_arithmetic.py +++ b/pandas/tests/indexes/period/test_arithmetic.py @@ -730,11 +730,12 @@ def test_pi_ops(self): self._check(idx + 2, lambda x: x - 2, idx) result = idx - Period('2011-01', freq='M') - exp = pd.Index([0, 1, 2, 3], name='idx') + off = idx.freq + exp = pd.Index([0 * off, 1 * off, 2 * off, 3 * off], name='idx') tm.assert_index_equal(result, exp) result = Period('2011-01', freq='M') - idx - exp = pd.Index([0, -1, -2, -3], name='idx') + exp = pd.Index([0 * off, -1 * off, -2 * off, -3 * off], name='idx') tm.assert_index_equal(result, exp) @pytest.mark.parametrize('ng', ["str", 1.5]) @@ -864,14 +865,15 @@ def test_pi_sub_period(self): freq='M', name='idx') result = idx - pd.Period('2012-01', freq='M') - exp = pd.Index([-12, -11, -10, -9], name='idx') + off = idx.freq + exp = pd.Index([-12 * off, -11 * off, -10 * off, -9 * off], name='idx') tm.assert_index_equal(result, exp) result = np.subtract(idx, pd.Period('2012-01', freq='M')) tm.assert_index_equal(result, exp) result = pd.Period('2012-01', freq='M') - idx - exp = pd.Index([12, 11, 10, 9], name='idx') + exp = pd.Index([12 * off, 11 * off, 10 * off, 9 * off], name='idx') tm.assert_index_equal(result, exp) result = np.subtract(pd.Period('2012-01', freq='M'), idx) @@ -898,11 +900,12 @@ def test_pi_sub_period_nat(self): freq='M', name='idx') result = idx - pd.Period('2012-01', freq='M') - exp = pd.Index([-12, np.nan, -10, -9], name='idx') + off = idx.freq + exp = pd.Index([-12 * off, pd.NaT, -10 * off, -9 * off], name='idx') tm.assert_index_equal(result, exp) result = pd.Period('2012-01', freq='M') - idx - exp = pd.Index([12, np.nan, 10, 9], name='idx') + 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') diff --git a/pandas/tests/scalar/period/test_period.py b/pandas/tests/scalar/period/test_period.py index f43ab0704f0f4..ffc375ba12e34 100644 --- a/pandas/tests/scalar/period/test_period.py +++ b/pandas/tests/scalar/period/test_period.py @@ -572,7 +572,7 @@ def test_strftime(self): def test_sub_delta(self): left, right = Period('2011', freq='A'), Period('2007', freq='A') result = left - right - assert result == 4 + assert result == 4 * right.freq with pytest.raises(period.IncompatibleFrequency): left - Period('2007-01', freq='M') @@ -1064,8 +1064,9 @@ def test_sub(self): dt1 = Period('2011-01-01', freq='D') dt2 = Period('2011-01-15', freq='D') - assert dt1 - dt2 == -14 - assert dt2 - dt1 == 14 + off = dt1.freq + assert dt1 - dt2 == -14 * off + assert dt2 - dt1 == 14 * off msg = r"Input has different freq=M from Period\(freq=D\)" with tm.assert_raises_regex(period.IncompatibleFrequency, msg): diff --git a/pandas/tests/series/test_arithmetic.py b/pandas/tests/series/test_arithmetic.py index 95836f046195a..f4bdb7ba86aaf 100644 --- a/pandas/tests/series/test_arithmetic.py +++ b/pandas/tests/series/test_arithmetic.py @@ -517,8 +517,9 @@ def test_ops_series_period(self): assert ser.dtype == object per = pd.Period('2015-01-10', freq='D') + off = per.freq # dtype will be object because of original dtype - expected = pd.Series([9, 8], name='xxx', dtype=object) + expected = pd.Series([9 * off, 8 * off], name='xxx', dtype=object) tm.assert_series_equal(per - ser, expected) tm.assert_series_equal(ser - per, -1 * expected) @@ -526,7 +527,7 @@ def test_ops_series_period(self): pd.Period('2015-01-04', freq='D')], name='xxx') assert s2.dtype == object - expected = pd.Series([4, 2], name='xxx', dtype=object) + expected = pd.Series([4 * off, 2 * off], name='xxx', dtype=object) tm.assert_series_equal(s2 - ser, expected) tm.assert_series_equal(ser - s2, -1 * expected)
Discussed briefly in #20049. - [ ] closes #xxxx - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21314
2018-06-04T14:42:47Z
2018-06-29T00:41:00Z
2018-06-29T00:41:00Z
2020-04-05T17:41:50Z
BUG: fix DataFrame.__getitem__ and .loc with non-list listlikes
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 3a8c81b5e9281..ccd14b7abe611 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -310,6 +310,8 @@ Indexing - When ``.ix`` is asked for a missing integer label in a :class:`MultiIndex` with a first level of integer type, it now raises a ``KeyError``, consistently with the case of a flat :class:`Int64Index, rather than falling back to positional indexing (:issue:`21593`) - Bug in :meth:`DatetimeIndex.reindex` when reindexing a tz-naive and tz-aware :class:`DatetimeIndex` (:issue:`8306`) - Bug in :class:`DataFrame` when setting values with ``.loc`` and a timezone aware :class:`DatetimeIndex` (:issue:`11365`) +- ``DataFrame.__getitem__`` now accepts dictionaries and dictionary keys as list-likes of labels, consistently with ``Series.__getitem__`` (:issue:`21294`) +- Fixed ``DataFrame[np.nan]`` when columns are non-unique (:issue:`21428`) - Bug when indexing :class:`DatetimeIndex` with nanosecond resolution dates and timezones (:issue:`11679`) - diff --git a/pandas/core/frame.py b/pandas/core/frame.py index a420266561c5a..7659d01c045d5 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -2670,68 +2670,80 @@ def _ixs(self, i, axis=0): def __getitem__(self, key): key = com._apply_if_callable(key, self) - # shortcut if we are an actual column - is_mi_columns = isinstance(self.columns, MultiIndex) + # shortcut if the key is in columns try: - if key in self.columns and not is_mi_columns: - return self._getitem_column(key) - except: + if self.columns.is_unique and key in self.columns: + if self.columns.nlevels > 1: + return self._getitem_multilevel(key) + return self._get_item_cache(key) + except (TypeError, ValueError): + # The TypeError correctly catches non hashable "key" (e.g. list) + # The ValueError can be removed once GH #21729 is fixed pass - # see if we can slice the rows + # Do we have a slicer (on rows)? indexer = convert_to_index_sliceable(self, key) if indexer is not None: - return self._getitem_slice(indexer) + return self._slice(indexer, axis=0) - if isinstance(key, (Series, np.ndarray, Index, list)): - # either boolean or fancy integer index - return self._getitem_array(key) - elif isinstance(key, DataFrame): + # Do we have a (boolean) DataFrame? + if isinstance(key, DataFrame): return self._getitem_frame(key) - elif is_mi_columns: - return self._getitem_multilevel(key) + + # Do we have a (boolean) 1d indexer? + if com.is_bool_indexer(key): + return self._getitem_bool_array(key) + + # We are left with two options: a single key, and a collection of keys, + # We interpret tuples as collections only for non-MultiIndex + is_single_key = isinstance(key, tuple) or not is_list_like(key) + + if is_single_key: + if self.columns.nlevels > 1: + return self._getitem_multilevel(key) + indexer = self.columns.get_loc(key) + if is_integer(indexer): + indexer = [indexer] else: - return self._getitem_column(key) + if is_iterator(key): + key = list(key) + indexer = self.loc._convert_to_indexer(key, axis=1, + raise_missing=True) - def _getitem_column(self, key): - """ return the actual column """ + # take() does not accept boolean indexers + if getattr(indexer, "dtype", None) == bool: + indexer = np.where(indexer)[0] - # get column - if self.columns.is_unique: - return self._get_item_cache(key) + data = self._take(indexer, axis=1) - # duplicate columns & possible reduce dimensionality - result = self._constructor(self._data.get(key)) - if result.columns.is_unique: - result = result[key] + if is_single_key: + # What does looking for a single key in a non-unique index return? + # The behavior is inconsistent. It returns a Series, except when + # - the key itself is repeated (test on data.shape, #9519), or + # - we have a MultiIndex on columns (test on self.columns, #21309) + if data.shape[1] == 1 and not isinstance(self.columns, MultiIndex): + data = data[key] - return result - - def _getitem_slice(self, key): - return self._slice(key, axis=0) + return data - def _getitem_array(self, key): + def _getitem_bool_array(self, key): # also raises Exception if object array with NA values - if com.is_bool_indexer(key): - # warning here just in case -- previously __setitem__ was - # reindexing but __getitem__ was not; it seems more reasonable to - # go with the __setitem__ behavior since that is more consistent - # with all other indexing behavior - if isinstance(key, Series) and not key.index.equals(self.index): - warnings.warn("Boolean Series key will be reindexed to match " - "DataFrame index.", UserWarning, stacklevel=3) - elif len(key) != len(self.index): - raise ValueError('Item wrong length %d instead of %d.' % - (len(key), len(self.index))) - # check_bool_indexer will throw exception if Series key cannot - # be reindexed to match DataFrame rows - key = check_bool_indexer(self.index, key) - indexer = key.nonzero()[0] - return self._take(indexer, axis=0) - else: - indexer = self.loc._convert_to_indexer(key, axis=1, - raise_missing=True) - return self._take(indexer, axis=1) + # warning here just in case -- previously __setitem__ was + # reindexing but __getitem__ was not; it seems more reasonable to + # go with the __setitem__ behavior since that is more consistent + # with all other indexing behavior + if isinstance(key, Series) and not key.index.equals(self.index): + warnings.warn("Boolean Series key will be reindexed to match " + "DataFrame index.", UserWarning, stacklevel=3) + elif len(key) != len(self.index): + raise ValueError('Item wrong length %d instead of %d.' % + (len(key), len(self.index))) + + # check_bool_indexer will throw exception if Series key cannot + # be reindexed to match DataFrame rows + key = check_bool_indexer(self.index, key) + indexer = key.nonzero()[0] + return self._take(indexer, axis=0) def _getitem_multilevel(self, key): loc = self.columns.get_loc(key) diff --git a/pandas/core/sparse/frame.py b/pandas/core/sparse/frame.py index 28299fbe61daf..1feddf004058a 100644 --- a/pandas/core/sparse/frame.py +++ b/pandas/core/sparse/frame.py @@ -148,9 +148,10 @@ def _init_dict(self, data, index, columns, dtype=None): if index is None: index = extract_index(list(data.values())) - sp_maker = lambda x: SparseArray(x, kind=self._default_kind, - fill_value=self._default_fill_value, - copy=True, dtype=dtype) + def sp_maker(x): + return SparseArray(x, kind=self._default_kind, + fill_value=self._default_fill_value, + copy=True, dtype=dtype) sdict = {} for k, v in compat.iteritems(data): if isinstance(v, Series): @@ -397,9 +398,10 @@ def _sanitize_column(self, key, value, **kwargs): sanitized_column : SparseArray """ - sp_maker = lambda x, index=None: SparseArray( - x, index=index, fill_value=self._default_fill_value, - kind=self._default_kind) + def sp_maker(x, index=None): + return SparseArray(x, index=index, + fill_value=self._default_fill_value, + kind=self._default_kind) if isinstance(value, SparseSeries): clean = value.reindex(self.index).as_sparse_array( fill_value=self._default_fill_value, kind=self._default_kind) @@ -428,18 +430,6 @@ def _sanitize_column(self, key, value, **kwargs): # always return a SparseArray! return clean - def __getitem__(self, key): - """ - Retrieve column or slice from DataFrame - """ - if isinstance(key, slice): - date_rng = self.index[key] - return self.reindex(date_rng) - elif isinstance(key, (np.ndarray, list, Series)): - return self._getitem_array(key) - else: - return self._get_item_cache(key) - def get_value(self, index, col, takeable=False): """ Quickly retrieve single value at passed column and index diff --git a/pandas/tests/frame/test_constructors.py b/pandas/tests/frame/test_constructors.py index e7fb765128738..bef38288ff3a5 100644 --- a/pandas/tests/frame/test_constructors.py +++ b/pandas/tests/frame/test_constructors.py @@ -501,9 +501,11 @@ def test_constructor_dict_of_tuples(self): tm.assert_frame_equal(result, expected, check_dtype=False) def test_constructor_dict_multiindex(self): - check = lambda result, expected: tm.assert_frame_equal( - result, expected, check_dtype=True, check_index_type=True, - check_column_type=True, check_names=True) + def check(result, expected): + return tm.assert_frame_equal(result, expected, check_dtype=True, + check_index_type=True, + check_column_type=True, + check_names=True) d = {('a', 'a'): {('i', 'i'): 0, ('i', 'j'): 1, ('j', 'i'): 2}, ('b', 'a'): {('i', 'i'): 6, ('i', 'j'): 5, ('j', 'i'): 4}, ('b', 'c'): {('i', 'i'): 7, ('i', 'j'): 8, ('j', 'i'): 9}} @@ -1655,19 +1657,21 @@ def check(df): for i in range(len(df.columns)): df.iloc[:, i] - # allow single nans to succeed indexer = np.arange(len(df.columns))[isna(df.columns)] - if len(indexer) == 1: - tm.assert_series_equal(df.iloc[:, indexer[0]], - df.loc[:, np.nan]) - - # multiple nans should fail - else: - + # No NaN found -> error + if len(indexer) == 0: def f(): df.loc[:, np.nan] pytest.raises(TypeError, f) + # single nan should result in Series + elif len(indexer) == 1: + tm.assert_series_equal(df.iloc[:, indexer[0]], + df.loc[:, np.nan]) + # multiple nans should result in DataFrame + else: + tm.assert_frame_equal(df.iloc[:, indexer], + df.loc[:, np.nan]) df = DataFrame([[1, 2, 3], [4, 5, 6]], index=[1, np.nan]) check(df) @@ -1683,6 +1687,11 @@ def f(): columns=[np.nan, 1.1, 2.2, np.nan]) check(df) + # GH 21428 (non-unique columns) + df = DataFrame([[0.0, 1, 2, 3.0], [4, 5, 6, 7]], + columns=[np.nan, 1, 2, 2]) + check(df) + def test_constructor_lists_to_object_dtype(self): # from #1074 d = DataFrame({'a': [np.nan, False]}) diff --git a/pandas/tests/frame/test_indexing.py b/pandas/tests/frame/test_indexing.py index 90f3bede482c6..9ca2b7e3c8a6a 100644 --- a/pandas/tests/frame/test_indexing.py +++ b/pandas/tests/frame/test_indexing.py @@ -92,45 +92,46 @@ def test_get(self): result = df.get(None) assert result is None - def test_getitem_iterator(self): + def test_loc_iterable(self): idx = iter(['A', 'B', 'C']) result = self.frame.loc[:, idx] expected = self.frame.loc[:, ['A', 'B', 'C']] assert_frame_equal(result, expected) - idx = iter(['A', 'B', 'C']) - result = self.frame.loc[:, idx] - expected = self.frame.loc[:, ['A', 'B', 'C']] - assert_frame_equal(result, expected) + @pytest.mark.parametrize( + "idx_type", + [list, iter, Index, set, + lambda l: dict(zip(l, range(len(l)))), + lambda l: dict(zip(l, range(len(l)))).keys()], + ids=["list", "iter", "Index", "set", "dict", "dict_keys"]) + @pytest.mark.parametrize("levels", [1, 2]) + def test_getitem_listlike(self, idx_type, levels): + # GH 21294 + + if levels == 1: + frame, missing = self.frame, 'food' + else: + # MultiIndex columns + frame = DataFrame(randn(8, 3), + columns=Index([('foo', 'bar'), ('baz', 'qux'), + ('peek', 'aboo')], + name=('sth', 'sth2'))) + missing = ('good', 'food') - def test_getitem_list(self): - self.frame.columns.name = 'foo' + keys = [frame.columns[1], frame.columns[0]] + idx = idx_type(keys) + idx_check = list(idx_type(keys)) - result = self.frame[['B', 'A']] - result2 = self.frame[Index(['B', 'A'])] + result = frame[idx] - expected = self.frame.loc[:, ['B', 'A']] - expected.columns.name = 'foo' + expected = frame.loc[:, idx_check] + expected.columns.names = frame.columns.names assert_frame_equal(result, expected) - assert_frame_equal(result2, expected) - assert result.columns.name == 'foo' - - with tm.assert_raises_regex(KeyError, 'not in index'): - self.frame[['B', 'A', 'food']] + idx = idx_type(keys + [missing]) with tm.assert_raises_regex(KeyError, 'not in index'): - self.frame[Index(['B', 'A', 'foo'])] - - # tuples - df = DataFrame(randn(8, 3), - columns=Index([('foo', 'bar'), ('baz', 'qux'), - ('peek', 'aboo')], name=('sth', 'sth2'))) - - result = df[[('foo', 'bar'), ('baz', 'qux')]] - expected = df.iloc[:, :2] - assert_frame_equal(result, expected) - assert result.columns.names == ('sth', 'sth2') + frame[idx] def test_getitem_callable(self): # GH 12533 @@ -223,7 +224,8 @@ def test_setitem_callable(self): def test_setitem_other_callable(self): # GH 13299 - inc = lambda x: x + 1 + def inc(x): + return x + 1 df = pd.DataFrame([[-1, 1], [1, -1]]) df[df > 0] = inc @@ -2082,7 +2084,8 @@ def test_reindex_level(self): icol = ['jim', 'joe', 'jolie'] def verify_first_level(df, level, idx, check_index_type=True): - f = lambda val: np.nonzero(df[level] == val)[0] + def f(val): + return np.nonzero(df[level] == val)[0] i = np.concatenate(list(map(f, idx))) left = df.set_index(icol).reindex(idx, level=level) right = df.iloc[i].set_index(icol)
- [x] closes #21294 - [x] closes #21428 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry xref #21309 , but worth fixing separately
https://api.github.com/repos/pandas-dev/pandas/pulls/21313
2018-06-04T13:49:12Z
2018-07-07T14:24:57Z
2018-07-07T14:24:56Z
2018-07-08T08:24:12Z
REGR: allow merging on object boolean columns
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index 1a8b1603daaaa..07120e26b4ecd 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -65,15 +65,14 @@ In addition, ordering comparisons will raise a ``TypeError`` in the future. a tz-aware time instead of tz-naive (:issue:`21267`) and :attr:`DatetimeIndex.date` returned incorrect date when the input date has a non-UTC timezone (:issue:`21230`). - Fixed regression in :meth:`pandas.io.json.json_normalize` when called with ``None`` values - in nested levels in JSON (:issue:`21158`). + in nested levels in JSON, and to not drop keys with value as `None` (:issue:`21158`, :issue:`21356`). - Bug in :meth:`~DataFrame.to_csv` causes encoding error when compression and encoding are specified (:issue:`21241`, :issue:`21118`) - Bug preventing pandas from being importable with -OO optimization (:issue:`21071`) - Bug in :meth:`Categorical.fillna` incorrectly raising a ``TypeError`` when `value` the individual categories are iterable and `value` is an iterable (:issue:`21097`, :issue:`19788`) - Fixed regression in constructors coercing NA values like ``None`` to strings when passing ``dtype=str`` (:issue:`21083`) - Regression in :func:`pivot_table` where an ordered ``Categorical`` with missing values for the pivot's ``index`` would give a mis-aligned result (:issue:`21133`) -- Fixed Regression in :func:`nested_to_record` which now flattens list of dictionaries and doesnot drop keys with value as `None` (:issue:`21356`) - +- Fixed regression in merging on boolean index/columns (:issue:`21119`). .. _whatsnew_0231.performance: diff --git a/pandas/core/reshape/merge.py b/pandas/core/reshape/merge.py index 73aba4d4e044b..e38c069b3c3fb 100644 --- a/pandas/core/reshape/merge.py +++ b/pandas/core/reshape/merge.py @@ -28,6 +28,7 @@ is_int_or_datetime_dtype, is_dtype_equal, is_bool, + is_bool_dtype, is_list_like, is_datetimelike, _ensure_int64, @@ -974,9 +975,14 @@ def _maybe_coerce_merge_keys(self): # Check if we are trying to merge on obviously # incompatible dtypes GH 9780, GH 15800 - elif is_numeric_dtype(lk) and not is_numeric_dtype(rk): + + # boolean values are considered as numeric, but are still allowed + # to be merged on object boolean values + elif ((is_numeric_dtype(lk) and not is_bool_dtype(lk)) + and not is_numeric_dtype(rk)): raise ValueError(msg) - elif not is_numeric_dtype(lk) and is_numeric_dtype(rk): + elif (not is_numeric_dtype(lk) + and (is_numeric_dtype(rk) and not is_bool_dtype(rk))): raise ValueError(msg) elif is_datetimelike(lk) and not is_datetimelike(rk): raise ValueError(msg) diff --git a/pandas/tests/reshape/merge/test_merge.py b/pandas/tests/reshape/merge/test_merge.py index 8e639edd34b18..037bd9cc7cd18 100644 --- a/pandas/tests/reshape/merge/test_merge.py +++ b/pandas/tests/reshape/merge/test_merge.py @@ -1526,6 +1526,27 @@ def test_merge_on_ints_floats_warning(self): result = B.merge(A, left_on='Y', right_on='X') assert_frame_equal(result, expected[['Y', 'X']]) + def test_merge_incompat_infer_boolean_object(self): + # GH21119: bool + object bool merge OK + df1 = DataFrame({'key': Series([True, False], dtype=object)}) + df2 = DataFrame({'key': [True, False]}) + + expected = DataFrame({'key': [True, False]}, dtype=object) + result = pd.merge(df1, df2, on='key') + assert_frame_equal(result, expected) + result = pd.merge(df2, df1, on='key') + assert_frame_equal(result, expected) + + # with missing value + df1 = DataFrame({'key': Series([True, False, np.nan], dtype=object)}) + df2 = DataFrame({'key': [True, False]}) + + expected = DataFrame({'key': [True, False]}, dtype=object) + result = pd.merge(df1, df2, on='key') + assert_frame_equal(result, expected) + result = pd.merge(df2, df1, on='key') + assert_frame_equal(result, expected) + @pytest.mark.parametrize('df1_vals, df2_vals', [ ([0, 1, 2], ["0", "1", "2"]), ([0.0, 1.0, 2.0], ["0", "1", "2"]), @@ -1538,6 +1559,8 @@ def test_merge_on_ints_floats_warning(self): pd.date_range('20130101', periods=3, tz='US/Eastern')), ([0, 1, 2], Series(['a', 'b', 'a']).astype('category')), ([0.0, 1.0, 2.0], Series(['a', 'b', 'a']).astype('category')), + # TODO ([0, 1], pd.Series([False, True], dtype=bool)), + ([0, 1], pd.Series([False, True], dtype=object)) ]) def test_merge_incompat_dtypes(self, df1_vals, df2_vals): # GH 9780, GH 15800
Fixes https://github.com/pandas-dev/pandas/issues/21119 This is a quick/hacky fix for the specific case in that issue, i.e. merging boolean / object boolean columns. However, I have the feeling we should do a more general solution for cases where object dtyped columns might be actually mergeable. The problem is that inferring the type can be costly? (and eg when having actual strings object columns, this inferring was also unnecessary and thus will unneeded slow down `merge`?)
https://api.github.com/repos/pandas-dev/pandas/pulls/21310
2018-06-04T08:41:20Z
2018-06-08T17:44:18Z
2018-06-08T17:44:18Z
2018-06-12T16:30:37Z
TST: fix shebang typo
diff --git a/pandas/tests/io/generate_legacy_storage_files.py b/pandas/tests/io/generate_legacy_storage_files.py index 9f1ac8b1e677b..eb40e5521f7f1 100755 --- a/pandas/tests/io/generate_legacy_storage_files.py +++ b/pandas/tests/io/generate_legacy_storage_files.py @@ -1,4 +1,4 @@ -#!/usr/env/bin python +#!/usr/bin/env python """ self-contained to write legacy storage (pickle/msgpack) files
Fix shebang typo in generate_legacy_storage_files.py - [x] closes #21306
https://api.github.com/repos/pandas-dev/pandas/pulls/21307
2018-06-04T05:06:39Z
2018-06-04T11:21:23Z
2018-06-04T11:21:22Z
2018-06-05T06:24:05Z
BUG: encoding error in to_csv compression
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index f2bc81eea186b..db4f4acc7ee16 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -92,6 +92,7 @@ I/O - Bug in IO methods specifying ``compression='zip'`` which produced uncompressed zip archives (:issue:`17778`, :issue:`21144`) - Bug in :meth:`DataFrame.to_stata` which prevented exporting DataFrames to buffers and most file-like objects (:issue:`21041`) +- Bug in :meth:`DataFrame.to_csv` and :meth:`Series.to_csv` causes encoding error when compression and encoding are specified (:issue:`21241`, :issue:`21118`) - Plotting diff --git a/pandas/io/formats/csvs.py b/pandas/io/formats/csvs.py index 0be2a180fbfa2..7f660e2644fa4 100644 --- a/pandas/io/formats/csvs.py +++ b/pandas/io/formats/csvs.py @@ -9,6 +9,7 @@ import numpy as np from pandas.core.dtypes.missing import notna +from pandas.core.dtypes.inference import is_file_like from pandas.core.index import Index, MultiIndex from pandas import compat from pandas.compat import (StringIO, range, zip) @@ -127,14 +128,19 @@ def save(self): else: encoding = self.encoding - if hasattr(self.path_or_buf, 'write'): - f = self.path_or_buf - close = False + # PR 21300 uses string buffer to receive csv writing and dump into + # file-like output with compression as option. GH 21241, 21118 + f = StringIO() + if not is_file_like(self.path_or_buf): + # path_or_buf is path + path_or_buf = self.path_or_buf + elif hasattr(self.path_or_buf, 'name'): + # path_or_buf is file handle + path_or_buf = self.path_or_buf.name else: - f, handles = _get_handle(self.path_or_buf, self.mode, - encoding=encoding, - compression=None) - close = True if self.compression is None else False + # path_or_buf is file-like IO objects. + f = self.path_or_buf + path_or_buf = None try: writer_kwargs = dict(lineterminator=self.line_terminator, @@ -151,18 +157,16 @@ def save(self): self._save() finally: - # GH 17778 handles compression for byte strings. - if not close and self.compression: - f.close() - with open(f.name, 'r') as f: - data = f.read() - f, handles = _get_handle(f.name, self.mode, + # GH 17778 handles zip compression for byte strings separately. + buf = f.getvalue() + if path_or_buf: + f, handles = _get_handle(path_or_buf, self.mode, encoding=encoding, compression=self.compression) - f.write(data) - close = True - if close: + f.write(buf) f.close() + for _fh in handles: + _fh.close() def _save_header(self): diff --git a/pandas/tests/frame/test_to_csv.py b/pandas/tests/frame/test_to_csv.py index e4829ebf48561..60dc336a85388 100644 --- a/pandas/tests/frame/test_to_csv.py +++ b/pandas/tests/frame/test_to_csv.py @@ -919,29 +919,45 @@ def test_to_csv_path_is_none(self): recons = pd.read_csv(StringIO(csv_str), index_col=0) assert_frame_equal(self.frame, recons) - def test_to_csv_compression(self, compression): - - df = DataFrame([[0.123456, 0.234567, 0.567567], - [12.32112, 123123.2, 321321.2]], - index=['A', 'B'], columns=['X', 'Y', 'Z']) + @pytest.mark.parametrize('df,encoding', [ + (DataFrame([[0.123456, 0.234567, 0.567567], + [12.32112, 123123.2, 321321.2]], + index=['A', 'B'], columns=['X', 'Y', 'Z']), None), + # GH 21241, 21118 + (DataFrame([['abc', 'def', 'ghi']], columns=['X', 'Y', 'Z']), 'ascii'), + (DataFrame(5 * [[123, u"你好", u"世界"]], + columns=['X', 'Y', 'Z']), 'gb2312'), + (DataFrame(5 * [[123, u"Γειά σου", u"Κόσμε"]], + columns=['X', 'Y', 'Z']), 'cp737') + ]) + def test_to_csv_compression(self, df, encoding, compression): with ensure_clean() as filename: - df.to_csv(filename, compression=compression) + df.to_csv(filename, compression=compression, encoding=encoding) # test the round trip - to_csv -> read_csv - rs = read_csv(filename, compression=compression, - index_col=0) - assert_frame_equal(df, rs) + result = read_csv(filename, compression=compression, + index_col=0, encoding=encoding) + + with open(filename, 'w') as fh: + df.to_csv(fh, compression=compression, encoding=encoding) + + result_fh = read_csv(filename, compression=compression, + index_col=0, encoding=encoding) + assert_frame_equal(df, result) + assert_frame_equal(df, result_fh) # explicitly make sure file is compressed with tm.decompress_file(filename, compression) as fh: - text = fh.read().decode('utf8') + text = fh.read().decode(encoding or 'utf8') for col in df.columns: assert col in text with tm.decompress_file(filename, compression) as fh: - assert_frame_equal(df, read_csv(fh, index_col=0)) + assert_frame_equal(df, read_csv(fh, + index_col=0, + encoding=encoding)) def test_to_csv_date_format(self): with ensure_clean('__tmp_to_csv_date_format__') as path: diff --git a/pandas/tests/series/test_io.py b/pandas/tests/series/test_io.py index e369dfda6deac..f98962685ad9a 100644 --- a/pandas/tests/series/test_io.py +++ b/pandas/tests/series/test_io.py @@ -137,29 +137,45 @@ def test_to_csv_path_is_none(self): csv_str = s.to_csv(path=None) assert isinstance(csv_str, str) - def test_to_csv_compression(self, compression): - - s = Series([0.123456, 0.234567, 0.567567], index=['A', 'B', 'C'], - name='X') + @pytest.mark.parametrize('s,encoding', [ + (Series([0.123456, 0.234567, 0.567567], index=['A', 'B', 'C'], + name='X'), None), + # GH 21241, 21118 + (Series(['abc', 'def', 'ghi'], name='X'), 'ascii'), + (Series(["123", u"你好", u"世界"], name=u"中文"), 'gb2312'), + (Series(["123", u"Γειά σου", u"Κόσμε"], name=u"Ελληνικά"), 'cp737') + ]) + def test_to_csv_compression(self, s, encoding, compression): with ensure_clean() as filename: - s.to_csv(filename, compression=compression, header=True) + s.to_csv(filename, compression=compression, encoding=encoding, + header=True) # test the round trip - to_csv -> read_csv - rs = pd.read_csv(filename, compression=compression, - index_col=0, squeeze=True) - assert_series_equal(s, rs) + result = pd.read_csv(filename, compression=compression, + encoding=encoding, index_col=0, squeeze=True) + + with open(filename, 'w') as fh: + s.to_csv(fh, compression=compression, encoding=encoding, + header=True) + + result_fh = pd.read_csv(filename, compression=compression, + encoding=encoding, index_col=0, + squeeze=True) + assert_series_equal(s, result) + assert_series_equal(s, result_fh) # explicitly ensure file was compressed with tm.decompress_file(filename, compression) as fh: - text = fh.read().decode('utf8') + text = fh.read().decode(encoding or 'utf8') assert s.name in text with tm.decompress_file(filename, compression) as fh: assert_series_equal(s, pd.read_csv(fh, index_col=0, - squeeze=True)) + squeeze=True, + encoding=encoding)) class TestSeriesIO(TestData): diff --git a/pandas/tests/test_common.py b/pandas/tests/test_common.py index 88e469731060d..7034e9ac2e0c8 100644 --- a/pandas/tests/test_common.py +++ b/pandas/tests/test_common.py @@ -252,12 +252,13 @@ def test_compression_size_fh(obj, method, compression_only): with tm.ensure_clean() as filename: with open(filename, 'w') as fh: getattr(obj, method)(fh, compression=compression_only) - # GH 17778 - assert fh.closed + assert not fh.closed + assert fh.closed compressed = os.path.getsize(filename) with tm.ensure_clean() as filename: with open(filename, 'w') as fh: getattr(obj, method)(fh, compression=None) assert not fh.closed + assert fh.closed uncompressed = os.path.getsize(filename) assert uncompressed > compressed
- [x] closes #21241 closes #21118 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Fix a problem where encoding wasn't handled properly in to_csv compression in Python 3. It was caused by dumping uncompressed csv on disk and reading it back to memory without passing specified encoding. Then platform tried to decode using default locale encoding which may or may not succeed. This PR added tests for non-ascii data with csv compression. Also, by using string buffer, this PR removed repeated disk roundtrip and redundant encoding/decoding which caused UnicodeDecodeError. There is performance improvement compared to 0.22 and 0.23. It also supports file-like object as input path_or_buf. Before this PR: ``` >>> df = DataFrame(100 * [[123, "abc", u"样本1", u"样本2"]], columns=['A', 'B', 'C', 'D']) >>> >>> def test_to_csv(df): ... df.to_csv( ... path_or_buf='test', ... encoding='utf8', ... compression='zip', ... quoting=1, ... sep='\t', ... index=False) ... >>> timeit(lambda: test_to_csv(df), number=5000) 11.856349980007508 ``` After this PR: ``` >>> df = DataFrame(100 * [[123, "abc", u"样本1", u"样本2"]], columns=['A', 'B', 'C', 'D']) >>> >>> def test_to_csv(df): ... df.to_csv( ... path_or_buf='test', ... encoding='utf8', ... compression='zip', ... quoting=1, ... sep='\t', ... index=False) ... >>> timeit(lambda: test_to_csv(df), number=5000) 5.459916951993364 ```
https://api.github.com/repos/pandas-dev/pandas/pulls/21300
2018-06-03T10:03:06Z
2018-06-05T04:54:31Z
2018-06-05T04:54:31Z
2018-06-20T18:11:54Z
Add Featuretools to Pandas Ecosystem Page
diff --git a/doc/source/ecosystem.rst b/doc/source/ecosystem.rst index 30cdb06b28487..6714398084186 100644 --- a/doc/source/ecosystem.rst +++ b/doc/source/ecosystem.rst @@ -38,7 +38,10 @@ Statsmodels leverages pandas objects as the underlying data container for comput Use pandas DataFrames in your `scikit-learn <http://scikit-learn.org/>`__ ML pipeline. +`Featuretools <https://github.com/featuretools/featuretools/>`__ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Featuretools is a Python library for automated feature engineering built on top of pandas. It excels at transforming temporal and relational datasets into feature matrices for machine learning using reusable feature engineering "primitives". Users can contribute their own primitives in Python and share them with the rest of the community. .. _ecosystem.visualization:
Adding a library for automated feature engineering that is built on top of Pandas that I think would be very relevant to users of pandas. More info on our website (https://www.featuretools.com/) and GitHub (https://github.com/featuretools/featuretools/).
https://api.github.com/repos/pandas-dev/pandas/pulls/21297
2018-06-02T17:52:57Z
2018-06-05T11:08:30Z
2018-06-05T11:08:30Z
2018-06-12T16:30:36Z
DOC: Fixing 'a la' confusion in series.quantile documentation
diff --git a/pandas/core/series.py b/pandas/core/series.py index 4cf29319f703e..d8bdd9ac9ed22 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -1837,7 +1837,7 @@ def round(self, decimals=0, *args, **kwargs): def quantile(self, q=0.5, interpolation='linear'): """ - Return value at the given quantile, a la numpy.percentile. + Return value at the given quantile. Parameters ---------- @@ -1876,6 +1876,7 @@ def quantile(self, q=0.5, interpolation='linear'): See Also -------- pandas.core.window.Rolling.quantile + numpy.percentile """ self._check_percentile(q)
Just stating that numpy.percentile also offers something similar to this - [x] closes #21292 - [ ] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] Just clarified quantile doc a bit
https://api.github.com/repos/pandas-dev/pandas/pulls/21293
2018-06-02T05:23:51Z
2018-06-06T07:31:12Z
2018-06-06T07:31:11Z
2018-06-06T07:31:20Z
BUG: invalid rolling window on empty input
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index f2bc81eea186b..733633c38c281 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -52,6 +52,7 @@ Groupby/Resample/Rolling - Bug in :func:`DataFrame.agg` where applying multiple aggregation functions to a :class:`DataFrame` with duplicated column names would cause a stack overflow (:issue:`21063`) - Bug in :func:`pandas.core.groupby.GroupBy.ffill` and :func:`pandas.core.groupby.GroupBy.bfill` where the fill within a grouping would not always be applied as intended due to the implementations' use of a non-stable sort (:issue:`21207`) - Bug in :func:`pandas.core.groupby.GroupBy.rank` where results did not scale to 100% when specifying ``method='dense'`` and ``pct=True`` +- Bug in :func:`pandas.DataFrame.rolling` and :func:`pandas.Series.rolling` which incorrectly accepted a 0 window size rather than raising (:issue:`21286`) Strings ^^^^^^^ diff --git a/pandas/core/window.py b/pandas/core/window.py index 015e7f7913ed0..9d0f9dc4f75f9 100644 --- a/pandas/core/window.py +++ b/pandas/core/window.py @@ -602,8 +602,8 @@ def validate(self): if isinstance(window, (list, tuple, np.ndarray)): pass elif is_integer(window): - if window < 0: - raise ValueError("window must be non-negative") + if window <= 0: + raise ValueError("window must be > 0 ") try: import scipy.signal as sig except ImportError: diff --git a/pandas/tests/test_window.py b/pandas/tests/test_window.py index 74f2c977e0db2..cfd88f41f855e 100644 --- a/pandas/tests/test_window.py +++ b/pandas/tests/test_window.py @@ -389,8 +389,8 @@ def test_constructor(self, which): c(window=2, min_periods=1, center=False) # GH 13383 - c(0) with pytest.raises(ValueError): + c(0) c(-1) # not valid @@ -409,7 +409,6 @@ def test_constructor_with_win_type(self, which): # GH 13383 o = getattr(self, which) c = o.rolling - c(0, win_type='boxcar') with pytest.raises(ValueError): c(-1, win_type='boxcar')
Added a raise Value Error for the case when window==0, Kindly refer to issue #21286 for the same - [x] closes #21286 - [x] tests added / passed - [ ] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] A simple except cases added
https://api.github.com/repos/pandas-dev/pandas/pulls/21291
2018-06-02T05:05:04Z
2018-06-08T16:25:52Z
2018-06-08T16:25:52Z
2018-06-12T16:30:36Z
PERF: improve performance of groupby rank (#21237)
diff --git a/asv_bench/benchmarks/groupby.py b/asv_bench/benchmarks/groupby.py index 7777322071957..0725bbeb6c36d 100644 --- a/asv_bench/benchmarks/groupby.py +++ b/asv_bench/benchmarks/groupby.py @@ -5,7 +5,7 @@ import numpy as np from pandas import (DataFrame, Series, MultiIndex, date_range, period_range, - TimeGrouper, Categorical) + TimeGrouper, Categorical, Timestamp) import pandas.util.testing as tm from .pandas_vb_common import setup # noqa @@ -385,6 +385,25 @@ def time_dtype_as_field(self, dtype, method, application): self.as_field_method() +class RankWithTies(object): + # GH 21237 + goal_time = 0.2 + param_names = ['dtype', 'tie_method'] + params = [['float64', 'float32', 'int64', 'datetime64'], + ['first', 'average', 'dense', 'min', 'max']] + + def setup(self, dtype, tie_method): + N = 10**4 + if dtype == 'datetime64': + data = np.array([Timestamp("2011/01/01")] * N, dtype=dtype) + else: + data = np.array([1] * N, dtype=dtype) + self.df = DataFrame({'values': data, 'key': ['foo'] * N}) + + def time_rank_ties(self, dtype, tie_method): + self.df.groupby('key').rank(method=tie_method) + + class Float32(object): # GH 13335 goal_time = 0.2 diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 68c1839221508..eaeda8bf190da 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -65,6 +65,7 @@ Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ - Improved performance of :func:`Series.describe` in case of numeric dtpyes (:issue:`21274`) +- Improved performance of :func:`pandas.core.groupby.GroupBy.rank` when dealing with tied rankings (:issue:`21237`) - .. _whatsnew_0240.docs: diff --git a/pandas/_libs/groupby_helper.pxi.in b/pandas/_libs/groupby_helper.pxi.in index b3e9b7c9e69ee..0062a6c8d31ab 100644 --- a/pandas/_libs/groupby_helper.pxi.in +++ b/pandas/_libs/groupby_helper.pxi.in @@ -429,7 +429,8 @@ def group_rank_{{name}}(ndarray[float64_t, ndim=2] out, is_datetimelike : bool, default False unused in this method but provided for call compatibility with other Cython transformations - ties_method : {'average', 'min', 'max', 'first', 'dense'}, default 'average' + ties_method : {'average', 'min', 'max', 'first', 'dense'}, default + 'average' * average: average rank of group * min: lowest rank in group * max: highest rank in group @@ -514,26 +515,22 @@ def group_rank_{{name}}(ndarray[float64_t, ndim=2] out, dups += 1 sum_ranks += i - grp_start + 1 - # if keep_na, check for missing values and assign back - # to the result where appropriate - - if keep_na and mask[_as[i]]: - grp_na_count += 1 - out[_as[i], 0] = nan - else: - # this implementation is inefficient because it will - # continue overwriting previously encountered dups - # i.e. if 5 duplicated values are encountered it will - # write to the result as follows (assumes avg tiebreaker): - # 1 - # .5 .5 - # .33 .33 .33 - # .25 .25 .25 .25 - # .2 .2 .2 .2 .2 - # - # could potentially be optimized to only write to the - # result once the last duplicate value is encountered - if tiebreak == TIEBREAK_AVERAGE: + # Update out only when there is a transition of values or labels. + # When a new value or group is encountered, go back #dups steps( + # the number of occurrence of current value) and assign the ranks + # based on the the starting index of the current group (grp_start) + # and the current index + if (i == N - 1 or + (masked_vals[_as[i]] != masked_vals[_as[i+1]]) or + (mask[_as[i]] ^ mask[_as[i+1]]) or + (labels[_as[i]] != labels[_as[i+1]])): + # if keep_na, check for missing values and assign back + # to the result where appropriate + if keep_na and mask[_as[i]]: + for j in range(i - dups + 1, i + 1): + out[_as[j], 0] = nan + grp_na_count = dups + elif tiebreak == TIEBREAK_AVERAGE: for j in range(i - dups + 1, i + 1): out[_as[j], 0] = sum_ranks / <float64_t>dups elif tiebreak == TIEBREAK_MIN: @@ -552,38 +549,38 @@ def group_rank_{{name}}(ndarray[float64_t, ndim=2] out, for j in range(i - dups + 1, i + 1): out[_as[j], 0] = grp_vals_seen - # look forward to the next value (using the sorting in _as) - # if the value does not equal the current value then we need to - # reset the dups and sum_ranks, knowing that a new value is coming - # up. the conditional also needs to handle nan equality and the - # end of iteration - if (i == N - 1 or - (masked_vals[_as[i]] != masked_vals[_as[i+1]]) or - (mask[_as[i]] ^ mask[_as[i+1]])): - dups = sum_ranks = 0 - val_start = i - grp_vals_seen += 1 - grp_tie_count +=1 - - # Similar to the previous conditional, check now if we are moving - # to a new group. If so, keep track of the index where the new - # group occurs, so the tiebreaker calculations can decrement that - # from their position. fill in the size of each group encountered - # (used by pct calculations later). also be sure to reset any of - # the items helping to calculate dups - if i == N - 1 or labels[_as[i]] != labels[_as[i+1]]: - if tiebreak != TIEBREAK_DENSE: - for j in range(grp_start, i + 1): - grp_sizes[_as[j], 0] = i - grp_start + 1 - grp_na_count - else: - for j in range(grp_start, i + 1): - grp_sizes[_as[j], 0] = (grp_tie_count - - (grp_na_count > 0)) - dups = sum_ranks = 0 - grp_na_count = 0 - grp_tie_count = 0 - grp_start = i + 1 - grp_vals_seen = 1 + # look forward to the next value (using the sorting in _as) + # if the value does not equal the current value then we need to + # reset the dups and sum_ranks, knowing that a new value is + # coming up. the conditional also needs to handle nan equality + # and the end of iteration + if (i == N - 1 or + (masked_vals[_as[i]] != masked_vals[_as[i+1]]) or + (mask[_as[i]] ^ mask[_as[i+1]])): + dups = sum_ranks = 0 + grp_vals_seen += 1 + grp_tie_count += 1 + + # Similar to the previous conditional, check now if we are + # moving to a new group. If so, keep track of the index where + # the new group occurs, so the tiebreaker calculations can + # decrement that from their position. fill in the size of each + # group encountered (used by pct calculations later). also be + # sure to reset any of the items helping to calculate dups + if i == N - 1 or labels[_as[i]] != labels[_as[i+1]]: + if tiebreak != TIEBREAK_DENSE: + for j in range(grp_start, i + 1): + grp_sizes[_as[j], 0] = (i - grp_start + 1 - + grp_na_count) + else: + for j in range(grp_start, i + 1): + grp_sizes[_as[j], 0] = (grp_tie_count - + (grp_na_count > 0)) + dups = sum_ranks = 0 + grp_na_count = 0 + grp_tie_count = 0 + grp_start = i + 1 + grp_vals_seen = 1 if pct: for i in range(N):
- [x] closes #21237 - [ ] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21285
2018-06-01T13:39:35Z
2018-06-14T10:08:58Z
2018-06-14T10:08:58Z
2018-06-14T10:09:02Z
BUG: Using DatetimeIndex.date with timezone returns incorrect date #2…
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index 9c29c34adb7dd..974527624a312 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -86,8 +86,10 @@ Indexing - Bug in :meth:`Series.reset_index` where appropriate error was not raised with an invalid level name (:issue:`20925`) - Bug in :func:`interval_range` when ``start``/``periods`` or ``end``/``periods`` are specified with float ``start`` or ``end`` (:issue:`21161`) - Bug in :meth:`MultiIndex.set_names` where error raised for a ``MultiIndex`` with ``nlevels == 1`` (:issue:`21149`) +- Bug in :attr:`DatetimeIndex.date` where an incorrect date is returned when the input date has a non-UTC timezone (:issue:`21230`) - Bug in :class:`IntervalIndex` constructors where creating an ``IntervalIndex`` from categorical data was not fully supported (:issue:`21243`, issue:`21253`) - Bug in :meth:`MultiIndex.sort_index` which was not guaranteed to sort correctly with ``level=1``; this was also causing data misalignment in particular :meth:`DataFrame.stack` operations (:issue:`20994`, :issue:`20945`, :issue:`21052`) +- Bug in :attr:`DatetimeIndex.time` where given a tz-aware Timestamp, a tz-aware Time is returned instead of tz-naive (:issue:`21267`) - I/O diff --git a/pandas/_libs/tslib.pyx b/pandas/_libs/tslib.pyx index 17453d8af1297..0f58cfa761f21 100644 --- a/pandas/_libs/tslib.pyx +++ b/pandas/_libs/tslib.pyx @@ -77,7 +77,7 @@ cdef inline object create_time_from_ts( int64_t value, pandas_datetimestruct dts, object tz, object freq): """ convenience routine to construct a datetime.time from its parts """ - return time(dts.hour, dts.min, dts.sec, dts.us, tz) + return time(dts.hour, dts.min, dts.sec, dts.us) def ints_to_pydatetime(ndarray[int64_t] arr, tz=None, freq=None, diff --git a/pandas/core/indexes/datetimes.py b/pandas/core/indexes/datetimes.py index 83950f1d71633..0ddf33cdcae73 100644 --- a/pandas/core/indexes/datetimes.py +++ b/pandas/core/indexes/datetimes.py @@ -2032,7 +2032,16 @@ def time(self): """ Returns numpy array of datetime.time. The time part of the Timestamps. """ - return libts.ints_to_pydatetime(self.asi8, self.tz, box="time") + + # If the Timestamps have a timezone that is not UTC, + # convert them into their i8 representation while + # keeping their timezone and not using UTC + if (self.tz is not None and self.tz is not utc): + timestamps = self._local_timestamps() + else: + timestamps = self.asi8 + + return libts.ints_to_pydatetime(timestamps, box="time") @property def date(self): @@ -2040,7 +2049,16 @@ def date(self): Returns numpy array of python datetime.date objects (namely, the date part of Timestamps without timezone information). """ - return libts.ints_to_pydatetime(self.normalize().asi8, box="date") + + # If the Timestamps have a timezone that is not UTC, + # convert them into their i8 representation while + # keeping their timezone and not using UTC + if (self.tz is not None and self.tz is not utc): + timestamps = self._local_timestamps() + else: + timestamps = self.asi8 + + return libts.ints_to_pydatetime(timestamps, box="date") def normalize(self): """ diff --git a/pandas/tests/indexes/datetimes/test_timezones.py b/pandas/tests/indexes/datetimes/test_timezones.py index 09210d8b64d1b..573940edaa08f 100644 --- a/pandas/tests/indexes/datetimes/test_timezones.py +++ b/pandas/tests/indexes/datetimes/test_timezones.py @@ -2,7 +2,7 @@ """ Tests for DatetimeIndex timezone-related methods """ -from datetime import datetime, timedelta, tzinfo +from datetime import datetime, timedelta, tzinfo, date, time from distutils.version import LooseVersion import pytest @@ -706,6 +706,32 @@ def test_join_utc_convert(self, join_type): assert isinstance(result, DatetimeIndex) assert result.tz.zone == 'UTC' + @pytest.mark.parametrize("dtype", [ + None, 'datetime64[ns, CET]', + 'datetime64[ns, EST]', 'datetime64[ns, UTC]' + ]) + def test_date_accessor(self, dtype): + # Regression test for GH#21230 + expected = np.array([date(2018, 6, 4), pd.NaT]) + + index = DatetimeIndex(['2018-06-04 10:00:00', pd.NaT], dtype=dtype) + result = index.date + + tm.assert_numpy_array_equal(result, expected) + + @pytest.mark.parametrize("dtype", [ + None, 'datetime64[ns, CET]', + 'datetime64[ns, EST]', 'datetime64[ns, UTC]' + ]) + def test_time_accessor(self, dtype): + # Regression test for GH#21267 + expected = np.array([time(10, 20, 30), pd.NaT]) + + index = DatetimeIndex(['2018-06-04 10:20:30', pd.NaT], dtype=dtype) + result = index.time + + tm.assert_numpy_array_equal(result, expected) + def test_dti_drop_dont_lose_tz(self): # GH#2621 ind = date_range("2012-12-01", periods=10, tz="utc")
- [ ] closes #21230, closes https://github.com/pandas-dev/pandas/issues/21267 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry Added 2 tests for DatetimeIndex.date in tests/indexes/datetimes/test_datetime.py. Please let me know if I should move them somewhere else.
https://api.github.com/repos/pandas-dev/pandas/pulls/21281
2018-06-01T01:51:48Z
2018-06-07T09:39:25Z
2018-06-07T09:39:24Z
2018-06-12T16:30:35Z
BUG: Fix encoding for Stata format 118 files
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index 69b07d12c1e98..bddb9d3b8e2a7 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -95,6 +95,7 @@ I/O - Bug in IO methods specifying ``compression='zip'`` which produced uncompressed zip archives (:issue:`17778`, :issue:`21144`) - Bug in :meth:`DataFrame.to_stata` which prevented exporting DataFrames to buffers and most file-like objects (:issue:`21041`) - Bug in :meth:`DataFrame.to_csv` and :meth:`Series.to_csv` causes encoding error when compression and encoding are specified (:issue:`21241`, :issue:`21118`) +- Bug in :meth:`read_stata` and :class:`StataReader` which did not correctly decode utf-8 strings on Python 3 from Stata 14 files (dta version 118) (:issue:`21244`) - Plotting diff --git a/pandas/io/stata.py b/pandas/io/stata.py index 2797924985c70..8584e1f0e3f14 100644 --- a/pandas/io/stata.py +++ b/pandas/io/stata.py @@ -182,7 +182,7 @@ def read_stata(filepath_or_buffer, convert_dates=True, preserve_dtypes=preserve_dtypes, columns=columns, order_categoricals=order_categoricals, - chunksize=chunksize, encoding=encoding) + chunksize=chunksize) if iterator or chunksize: data = reader @@ -838,15 +838,8 @@ def get_base_missing_value(cls, dtype): class StataParser(object): - _default_encoding = 'latin-1' - def __init__(self, encoding): - if encoding is not None: - if encoding not in VALID_ENCODINGS: - raise ValueError('Unknown encoding. Only latin-1 and ascii ' - 'supported.') - - self._encoding = encoding + def __init__(self): # type code. # -------------------- @@ -964,8 +957,8 @@ def __init__(self, path_or_buf, convert_dates=True, convert_categoricals=True, index_col=None, convert_missing=False, preserve_dtypes=True, columns=None, order_categoricals=True, - encoding='latin-1', chunksize=None): - super(StataReader, self).__init__(encoding) + encoding=None, chunksize=None): + super(StataReader, self).__init__() self.col_sizes = () # Arguments to the reader (can be temporarily overridden in @@ -977,10 +970,6 @@ def __init__(self, path_or_buf, convert_dates=True, self._preserve_dtypes = preserve_dtypes self._columns = columns self._order_categoricals = order_categoricals - if encoding is not None: - if encoding not in VALID_ENCODINGS: - raise ValueError('Unknown encoding. Only latin-1 and ascii ' - 'supported.') self._encoding = encoding self._chunksize = chunksize @@ -998,18 +987,13 @@ def __init__(self, path_or_buf, convert_dates=True, path_or_buf = _stringify_path(path_or_buf) if isinstance(path_or_buf, str): path_or_buf, encoding, _, should_close = get_filepath_or_buffer( - path_or_buf, encoding=self._default_encoding - ) + path_or_buf) if isinstance(path_or_buf, (str, text_type, bytes)): self.path_or_buf = open(path_or_buf, 'rb') else: # Copy to BytesIO, and ensure no encoding contents = path_or_buf.read() - try: - contents = contents.encode(self._default_encoding) - except: - pass self.path_or_buf = BytesIO(contents) self._read_header() @@ -1030,6 +1014,15 @@ def close(self): except IOError: pass + def _set_encoding(self): + """ + Set string encoding which depends on file version + """ + if self.format_version < 118: + self._encoding = 'latin-1' + else: + self._encoding = 'utf-8' + def _read_header(self): first_char = self.path_or_buf.read(1) if struct.unpack('c', first_char)[0] == b'<': @@ -1049,6 +1042,7 @@ def _read_new_header(self, first_char): self.format_version = int(self.path_or_buf.read(3)) if self.format_version not in [117, 118]: raise ValueError(_version_error) + self._set_encoding() self.path_or_buf.read(21) # </release><byteorder> self.byteorder = self.path_or_buf.read(3) == b'MSF' and '>' or '<' self.path_or_buf.read(15) # </byteorder><K> @@ -1235,6 +1229,7 @@ def _read_old_header(self, first_char): self.format_version = struct.unpack('b', first_char)[0] if self.format_version not in [104, 105, 108, 111, 113, 114, 115]: raise ValueError(_version_error) + self._set_encoding() self.byteorder = struct.unpack('b', self.path_or_buf.read(1))[ 0] == 0x1 and '>' or '<' self.filetype = struct.unpack('b', self.path_or_buf.read(1))[0] @@ -1338,16 +1333,9 @@ def _decode(self, s): return s.decode('utf-8') def _null_terminate(self, s): - if compat.PY3 or self._encoding is not None: - # have bytes not strings, so must decode - s = s.partition(b"\0")[0] - return s.decode(self._encoding or self._default_encoding) - else: - null_byte = "\0" - try: - return s.lstrip(null_byte)[:s.index(null_byte)] - except: - return s + # have bytes not strings, so must decode + s = s.partition(b"\0")[0] + return s.decode(self._encoding) def _read_value_labels(self): if self._value_labels_read: @@ -1433,10 +1421,7 @@ def _read_strls(self): self.path_or_buf.read(4))[0] va = self.path_or_buf.read(length) if typ == 130: - encoding = 'utf-8' - if self.format_version == 117: - encoding = self._encoding or self._default_encoding - va = va[0:-1].decode(encoding) + va = va[0:-1].decode(self._encoding) # Wrap v_o in a string to allow uint64 values as keys on 32bit OS self.GSO[str(v_o)] = va @@ -1980,9 +1965,14 @@ class StataWriter(StataParser): def __init__(self, fname, data, convert_dates=None, write_index=True, encoding="latin-1", byteorder=None, time_stamp=None, data_label=None, variable_labels=None): - super(StataWriter, self).__init__(encoding) + super(StataWriter, self).__init__() self._convert_dates = {} if convert_dates is None else convert_dates self._write_index = write_index + if encoding is not None: + if encoding not in VALID_ENCODINGS: + raise ValueError('Unknown encoding. Only latin-1 and ascii ' + 'supported.') + self._encoding = encoding self._time_stamp = time_stamp self._data_label = data_label self._variable_labels = variable_labels diff --git a/pandas/tests/io/data/stata16_118.dta b/pandas/tests/io/data/stata16_118.dta new file mode 100644 index 0000000000000..49cfa49d1b302 Binary files /dev/null and b/pandas/tests/io/data/stata16_118.dta differ diff --git a/pandas/tests/io/test_stata.py b/pandas/tests/io/test_stata.py index f3a465da4e87f..e5585902a9dd6 100644 --- a/pandas/tests/io/test_stata.py +++ b/pandas/tests/io/test_stata.py @@ -96,6 +96,7 @@ def setup_method(self, method): self.dta23 = os.path.join(self.dirpath, 'stata15.dta') self.dta24_111 = os.path.join(self.dirpath, 'stata7_111.dta') + self.dta25_118 = os.path.join(self.dirpath, 'stata16_118.dta') self.stata_dates = os.path.join(self.dirpath, 'stata13_dates.dta') @@ -363,19 +364,14 @@ def test_encoding(self, version): encoded = read_stata(self.dta_encoding, encoding="latin-1") result = encoded.kreis1849[0] - if compat.PY3: - expected = raw.kreis1849[0] - assert result == expected - assert isinstance(result, compat.string_types) - else: - expected = raw.kreis1849.str.decode("latin-1")[0] - assert result == expected - assert isinstance(result, unicode) # noqa + expected = raw.kreis1849[0] + assert result == expected + assert isinstance(result, compat.string_types) with tm.ensure_clean() as path: encoded.to_stata(path, encoding='latin-1', write_index=False, version=version) - reread_encoded = read_stata(path, encoding='latin-1') + reread_encoded = read_stata(path) tm.assert_frame_equal(encoded, reread_encoded) def test_read_write_dta11(self): @@ -1500,3 +1496,18 @@ def test_gzip_writing(self): with gzip.GzipFile(path, 'rb') as gz: reread = pd.read_stata(gz, index_col='index') tm.assert_frame_equal(df, reread) + + def test_unicode_dta_118(self): + unicode_df = self.read_dta(self.dta25_118) + + columns = ['utf8', 'latin1', 'ascii', 'utf8_strl', 'ascii_strl'] + values = [[u'ραηδας', u'PÄNDÄS', 'p', u'ραηδας', 'p'], + [u'ƤĀńĐąŜ', u'Ö', 'a', u'ƤĀńĐąŜ', 'a'], + [u'ᴘᴀᴎᴅᴀS', u'Ü', 'n', u'ᴘᴀᴎᴅᴀS', 'n'], + [' ', ' ', 'd', ' ', 'd'], + [' ', '', 'a', ' ', 'a'], + ['', '', 's', '', 's'], + ['', '', ' ', '', ' ']] + expected = pd.DataFrame(values, columns=columns) + + tm.assert_frame_equal(unicode_df, expected)
Ensure that Stata 118 files always use utf-8 encoding - [x] closes #21244 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21279
2018-05-31T23:35:47Z
2018-06-06T13:15:24Z
2018-06-06T13:15:24Z
2019-03-21T13:27:46Z
Add missing period to get_dummies docs
diff --git a/pandas/core/reshape/reshape.py b/pandas/core/reshape/reshape.py index 0829aa8f5a509..2757e0797a410 100644 --- a/pandas/core/reshape/reshape.py +++ b/pandas/core/reshape/reshape.py @@ -725,7 +725,7 @@ def get_dummies(data, prefix=None, prefix_sep='_', dummy_na=False, ---------- data : array-like, Series, or DataFrame prefix : string, list of strings, or dict of strings, default None - String to append DataFrame column names + String to append DataFrame column names. Pass a list with length equal to the number of columns when calling get_dummies on a DataFrame. Alternatively, `prefix` can be a dictionary mapping column names to prefixes.
Newline characters are stripped from the docstring when formatting parameter documentation. Because of this, the docs for the `prefix` parameter of [`pandas.get_dummies`](https://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html) look like a single run-on sentence. Added a period to the end of the first sentence to fix this.
https://api.github.com/repos/pandas-dev/pandas/pulls/21277
2018-05-31T19:28:46Z
2018-06-01T00:14:34Z
2018-06-01T00:14:34Z
2018-06-09T09:18:47Z
PERF: improve performance of NDFrame.describe
diff --git a/asv_bench/benchmarks/frame_methods.py b/asv_bench/benchmarks/frame_methods.py index 4ff71c706cd34..12e4824b2dd2a 100644 --- a/asv_bench/benchmarks/frame_methods.py +++ b/asv_bench/benchmarks/frame_methods.py @@ -512,3 +512,21 @@ def time_nlargest(self, keep): def time_nsmallest(self, keep): self.df.nsmallest(100, 'A', keep=keep) + + +class Describe(object): + + goal_time = 0.2 + + def setup(self): + self.df = DataFrame({ + 'a': np.random.randint(0, 100, int(1e6)), + 'b': np.random.randint(0, 100, int(1e6)), + 'c': np.random.randint(0, 100, int(1e6)) + }) + + def time_series_describe(self): + self.df['a'].describe() + + def time_dataframe_describe(self): + self.df.describe() diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 6cbc19cca99e1..c69de149a0f35 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -63,8 +63,7 @@ Removal of prior version deprecations/changes Performance Improvements ~~~~~~~~~~~~~~~~~~~~~~~~ -- -- +- Improved performance of :func:`Series.describe` in case of numeric dtpyes (:issue:`21274`) - .. _whatsnew_0240.docs: diff --git a/pandas/core/generic.py b/pandas/core/generic.py index 9e4eda1bc4dc7..2adc15651ffca 100644 --- a/pandas/core/generic.py +++ b/pandas/core/generic.py @@ -8519,7 +8519,7 @@ def describe_numeric_1d(series): stat_index = (['count', 'mean', 'std', 'min'] + formatted_percentiles + ['max']) d = ([series.count(), series.mean(), series.std(), series.min()] + - [series.quantile(x) for x in percentiles] + [series.max()]) + series.quantile(percentiles).tolist() + [series.max()]) return pd.Series(d, index=stat_index, name=series.name) def describe_categorical_1d(data):
A one-line change that enables to calculate the percentiles in `describe` more efficiently. The point is that calculating percentiles in one pass is faster than separately. `describe` (with default `percentiles` argument) becomes 25-30% faster than before for numerical Series and DataFrames. ### Setup ``` import timeit setup = ''' import numpy as np import pandas as pd np.random.seed(123) s = pd.Series(np.random.randint(0, 100, 1000000)) ''' ``` ### Benchmark ``` min(timeit.Timer('s.describe()', setup=setup).repeat(100, 1)) ``` ### Results On master: ``` 0.06349272100487724 ``` With this change: ``` 0.04745814300258644 ``` Results are similar for DataFrames. - [ ] closes #xxxx - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [ ] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21274
2018-05-31T12:11:36Z
2018-06-05T17:01:14Z
2018-06-05T17:01:14Z
2018-06-08T08:12:31Z
CI: bump numpy on appveyor ci
diff --git a/ci/appveyor-27.yaml b/ci/appveyor-27.yaml index 84107c605b14f..cfc6a796bd77e 100644 --- a/ci/appveyor-27.yaml +++ b/ci/appveyor-27.yaml @@ -11,9 +11,9 @@ dependencies: - lxml - matplotlib - numexpr - - numpy=1.10* + - numpy=1.12* - openpyxl - - pytables==3.2.2 + - pytables - python=2.7.* - pytz - s3fs diff --git a/ci/appveyor-36.yaml b/ci/appveyor-36.yaml index 5e370de39958a..868724419c464 100644 --- a/ci/appveyor-36.yaml +++ b/ci/appveyor-36.yaml @@ -9,7 +9,7 @@ dependencies: - feather-format - matplotlib - numexpr - - numpy=1.13* + - numpy=1.14* - openpyxl - pyarrow - pytables
https://api.github.com/repos/pandas-dev/pandas/pulls/21271
2018-05-31T10:25:50Z
2018-05-31T15:59:16Z
2018-05-31T15:59:16Z
2018-05-31T15:59:37Z
DOC: fill in class names for rename methods
diff --git a/pandas/core/frame.py b/pandas/core/frame.py index 0899e9cd87aba..1c7339a91c2fd 100644 --- a/pandas/core/frame.py +++ b/pandas/core/frame.py @@ -3720,7 +3720,7 @@ def rename(self, *args, **kwargs): copy : boolean, default True Also copy underlying data inplace : boolean, default False - Whether to return a new %(klass)s. If True then value of copy is + Whether to return a new DataFrame. If True then value of copy is ignored. level : int or level name, default None In case of a MultiIndex, only rename labels in the specified diff --git a/pandas/core/series.py b/pandas/core/series.py index f25f73513df30..d59401414181f 100644 --- a/pandas/core/series.py +++ b/pandas/core/series.py @@ -3269,7 +3269,7 @@ def rename(self, index=None, **kwargs): copy : boolean, default True Also copy underlying data inplace : boolean, default False - Whether to return a new %(klass)s. If True then value of copy is + Whether to return a new Series. If True then value of copy is ignored. level : int or level name, default None In case of a MultiIndex, only rename labels in the specified
The documentation for the `inplace` parameter has the `%(klass)` placeholder from the original NDFrame. This fills in the appropriate values in the following places: * http://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.DataFrame.rename.html * http://pandas.pydata.org/pandas-docs/version/0.23/generated/pandas.Series.rename.html
https://api.github.com/repos/pandas-dev/pandas/pulls/21268
2018-05-31T04:53:13Z
2018-05-31T10:19:19Z
2018-05-31T10:19:19Z
2018-06-08T17:20:02Z
DOC: Fix renaming categories section
diff --git a/doc/source/categorical.rst b/doc/source/categorical.rst index e4ce7ebd01dac..c6827f67a390b 100644 --- a/doc/source/categorical.rst +++ b/doc/source/categorical.rst @@ -358,10 +358,10 @@ Renaming categories is done by assigning new values to the s s.cat.categories = ["Group %s" % g for g in s.cat.categories] s - s.cat.rename_categories([1,2,3]) + s = s.cat.rename_categories([1,2,3]) s # You can also pass a dict-like object to map the renaming - s.cat.rename_categories({1: 'x', 2: 'y', 3: 'z'}) + s = s.cat.rename_categories({1: 'x', 2: 'y', 3: 'z'}) s .. note::
The categories were not correctly saved so that the renaming using the dict-like object had no effect.
https://api.github.com/repos/pandas-dev/pandas/pulls/21264
2018-05-30T22:29:56Z
2018-05-31T08:29:23Z
2018-05-31T08:29:23Z
2018-05-31T08:30:30Z
Color text based on background color when using `_background_gradient()`
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index e931450cb5c01..0c604f9aad993 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -181,7 +181,7 @@ Reshaping Other ^^^^^ -- +- :meth: `~pandas.io.formats.style.Styler.background_gradient` now takes a ``text_color_threshold`` parameter to automatically lighten the text color based on the luminance of the background color. This improves readability with dark background colors without the need to limit the background colormap range. (:issue:`21258`) - - diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index f876ceb8a26bf..668cafec4b522 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -863,7 +863,7 @@ def highlight_null(self, null_color='red'): return self def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0, - subset=None): + subset=None, text_color_threshold=0.408): """ Color the background in a gradient according to the data in each column (optionally row). @@ -879,6 +879,12 @@ def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0, 1 or 'columns' for columnwise, 0 or 'index' for rowwise subset: IndexSlice a valid slice for ``data`` to limit the style application to + text_color_threshold: float or int + luminance threshold for determining text color. Facilitates text + visibility across varying background colors. From 0 to 1. + 0 = all text is dark colored, 1 = all text is light colored. + + .. versionadded:: 0.24.0 Returns ------- @@ -886,19 +892,26 @@ def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0, Notes ----- - Tune ``low`` and ``high`` to keep the text legible by - not using the entire range of the color map. These extend - the range of the data by ``low * (x.max() - x.min())`` - and ``high * (x.max() - x.min())`` before normalizing. + Set ``text_color_threshold`` or tune ``low`` and ``high`` to keep the + text legible by not using the entire range of the color map. The range + of the data is extended by ``low * (x.max() - x.min())`` and ``high * + (x.max() - x.min())`` before normalizing. + + Raises + ------ + ValueError + If ``text_color_threshold`` is not a value from 0 to 1. """ subset = _maybe_numeric_slice(self.data, subset) subset = _non_reducing_slice(subset) self.apply(self._background_gradient, cmap=cmap, subset=subset, - axis=axis, low=low, high=high) + axis=axis, low=low, high=high, + text_color_threshold=text_color_threshold) return self @staticmethod - def _background_gradient(s, cmap='PuBu', low=0, high=0): + def _background_gradient(s, cmap='PuBu', low=0, high=0, + text_color_threshold=0.408): """Color background in a range according to the data.""" with _mpl(Styler.background_gradient) as (plt, colors): rng = s.max() - s.min() @@ -909,8 +922,39 @@ def _background_gradient(s, cmap='PuBu', low=0, high=0): # https://github.com/matplotlib/matplotlib/issues/5427 normed = norm(s.values) c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)] - return ['background-color: {color}'.format(color=color) - for color in c] + if (not isinstance(text_color_threshold, (float, int)) or + not 0 <= text_color_threshold <= 1): + msg = "`text_color_threshold` must be a value from 0 to 1." + raise ValueError(msg) + + def relative_luminance(color): + """ + Calculate relative luminance of a color. + + The calculation adheres to the W3C standards + (https://www.w3.org/WAI/GL/wiki/Relative_luminance) + + Parameters + ---------- + color : matplotlib color + Hex code, rgb-tuple, or HTML color name. + + Returns + ------- + float + The relative luminance as a value from 0 to 1 + """ + rgb = colors.colorConverter.to_rgba_array(color)[:, :3] + rgb = np.where(rgb <= .03928, rgb / 12.92, + ((rgb + .055) / 1.055) ** 2.4) + lum = rgb.dot([.2126, .7152, .0722]) + return lum.item() + + text_colors = ['#f1f1f1' if relative_luminance(x) < + text_color_threshold else '#000000' for x in c] + + return ['background-color: {color};color: {tc}'.format( + color=color, tc=tc) for color, tc in zip(c, text_colors)] def set_properties(self, subset=None, **kwargs): """ diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index c1ab9cd184340..b355cda8df1bd 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -1017,9 +1017,9 @@ def test_hide_columns_mult_levels(self): assert ctx['body'][1][2]['display_value'] == 3 +@td.skip_if_no_mpl class TestStylerMatplotlibDep(object): - @td.skip_if_no_mpl def test_background_gradient(self): df = pd.DataFrame([[1, 2], [2, 4]], columns=['A', 'B']) @@ -1031,7 +1031,30 @@ def test_background_gradient(self): result = df.style.background_gradient( subset=pd.IndexSlice[1, 'A'])._compute().ctx - assert result[(1, 0)] == ['background-color: #fff7fb'] + + assert result[(1, 0)] == ['background-color: #fff7fb', + 'color: #000000'] + + @pytest.mark.parametrize( + 'c_map,expected', [ + (None, { + (0, 0): ['background-color: #440154', 'color: #f1f1f1'], + (1, 0): ['background-color: #fde725', 'color: #000000']}), + ('YlOrRd', { + (0, 0): ['background-color: #ffffcc', 'color: #000000'], + (1, 0): ['background-color: #800026', 'color: #f1f1f1']})]) + def test_text_color_threshold(self, c_map, expected): + df = pd.DataFrame([1, 2], columns=['A']) + result = df.style.background_gradient(cmap=c_map)._compute().ctx + assert result == expected + + @pytest.mark.parametrize("text_color_threshold", [1.1, '1', -1, [2, 2]]) + def test_text_color_threshold_raises(self, text_color_threshold): + df = pd.DataFrame([[1, 2], [2, 4]], columns=['A', 'B']) + msg = "`text_color_threshold` must be a value from 0 to 1." + with tm.assert_raises_regex(ValueError, msg): + df.style.background_gradient( + text_color_threshold=text_color_threshold)._compute() def test_block_names():
The purpose of this PR is to automatically color text dark or light based on the background color of the HTML table: ================`old behavior` ===========================`new behavior`======== ![image](https://user-images.githubusercontent.com/4560057/40745876-b43b17ca-6426-11e8-892c-7f27598789de.png) ![image](https://user-images.githubusercontent.com/4560057/40744927-0e2796a8-6424-11e8-9837-53566d53bef6.png) As described in #21258, I use the luminance-based approach from `seaborn`'s annotated heatmaps. Tagging @WillAyd who commented on that issue. A few comments on this PR 1. Initially, I was not sure if defining the `relative_luminance()` method within `_background_gradient()` was the right way to go, but I opted for this since I saw the same approach elsewhere in the file. Let me know if you prefer a different approach. 2. I am not sure how intuitive it is that a parameter named `text_color` takes a numeric argument and not a color, but I think it is a good name for discoverability. Naming it `luminance_threshold` or similar might be confusing for users looking for a way to change the text color. 3. I opted to make the light text not completely white. The focus should be the background color so the text should not pop out too much. Thoughts? ================`#ffffff` ============================`#f1f1f1` (current choice)=== ![image](https://user-images.githubusercontent.com/4560057/40744958-25ba1ac0-6424-11e8-9b51-afaf0a1d05c8.png) ![image](https://user-images.githubusercontent.com/4560057/40744927-0e2796a8-6424-11e8-9837-53566d53bef6.png) ![image](https://user-images.githubusercontent.com/4560057/40745533-b2b81c46-6425-11e8-8bdd-e743441a5b18.png) ![image](https://user-images.githubusercontent.com/4560057/40745507-a54dd0e6-6425-11e8-8e92-50afbd986c57.png) 4. I think 0.2 is a good default threshold value for `text_color` based on my own qualitative assessment, feel free to disagree. The seaborn default of 0.4 makes too much text white in my opinion. Since colors and contrast can be quite subjective, I thought I would include some comparisons. ============`text_color=0.4` ======================`text_color=0.2` (current choice)=== ![image](https://user-images.githubusercontent.com/4560057/40745779-6620b1ee-6426-11e8-830a-6517239c8305.png) ![image](https://user-images.githubusercontent.com/4560057/40745632-f692805a-6425-11e8-8f1f-9ff00b81965f.png) ![image](https://user-images.githubusercontent.com/4560057/40745801-7332014e-6426-11e8-88b5-75b34ecfd6ca.png) ![image](https://user-images.githubusercontent.com/4560057/40745647-0653f08c-6426-11e8-995f-b69e6dd1c85c.png) ![image](https://user-images.githubusercontent.com/4560057/40745756-4fd3ef5a-6426-11e8-9335-855a09c2ec56.png) ![image](https://user-images.githubusercontent.com/4560057/40745721-3d98f48e-6426-11e8-9511-a3a9d4b52225.png) This is my first PR, apologies if I have misunderstood something. - [x] closes #21258 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21263
2018-05-30T20:41:26Z
2018-06-07T12:52:21Z
2018-06-07T12:52:20Z
2018-06-07T19:26:03Z
ENH: Support ExtensionArray operators via a mixin
diff --git a/doc/source/extending.rst b/doc/source/extending.rst index 8018d35770924..38b3b19031a0e 100644 --- a/doc/source/extending.rst +++ b/doc/source/extending.rst @@ -61,7 +61,7 @@ Extension Types .. warning:: - The :class:`pandas.api.extension.ExtensionDtype` and :class:`pandas.api.extension.ExtensionArray` APIs are new and + The :class:`pandas.api.extensions.ExtensionDtype` and :class:`pandas.api.extensions.ExtensionArray` APIs are new and experimental. They may change between versions without warning. Pandas defines an interface for implementing data types and arrays that *extend* @@ -79,10 +79,10 @@ on :ref:`ecosystem.extensions`. The interface consists of two classes. -:class:`~pandas.api.extension.ExtensionDtype` +:class:`~pandas.api.extensions.ExtensionDtype` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -A :class:`pandas.api.extension.ExtensionDtype` is similar to a ``numpy.dtype`` object. It describes the +A :class:`pandas.api.extensions.ExtensionDtype` is similar to a ``numpy.dtype`` object. It describes the data type. Implementors are responsible for a few unique items like the name. One particularly important item is the ``type`` property. This should be the @@ -91,7 +91,7 @@ extension array for IP Address data, this might be ``ipaddress.IPv4Address``. See the `extension dtype source`_ for interface definition. -:class:`~pandas.api.extension.ExtensionArray` +:class:`~pandas.api.extensions.ExtensionArray` ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ This class provides all the array-like functionality. ExtensionArrays are @@ -113,6 +113,54 @@ by some other storage type, like Python lists. See the `extension array source`_ for the interface definition. The docstrings and comments contain guidance for properly implementing the interface. +.. _extending.extension.operator: + +:class:`~pandas.api.extensions.ExtensionArray` Operator Support +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. versionadded:: 0.24.0 + +By default, there are no operators defined for the class :class:`~pandas.api.extensions.ExtensionArray`. +There are two approaches for providing operator support for your ExtensionArray: + +1. Define each of the operators on your ``ExtensionArray`` subclass. +2. Use an operator implementation from pandas that depends on operators that are already defined + on the underlying elements (scalars) of the ExtensionArray. + +For the first approach, you define selected operators, e.g., ``__add__``, ``__le__``, etc. that +you want your ``ExtensionArray`` subclass to support. + +The second approach assumes that the underlying elements (i.e., scalar type) of the ``ExtensionArray`` +have the individual operators already defined. In other words, if your ``ExtensionArray`` +named ``MyExtensionArray`` is implemented so that each element is an instance +of the class ``MyExtensionElement``, then if the operators are defined +for ``MyExtensionElement``, the second approach will automatically +define the operators for ``MyExtensionArray``. + +A mixin class, :class:`~pandas.api.extensions.ExtensionScalarOpsMixin` supports this second +approach. If developing an ``ExtensionArray`` subclass, for example ``MyExtensionArray``, +can simply include ``ExtensionScalarOpsMixin`` as a parent class of ``MyExtensionArray``, +and then call the methods :meth:`~MyExtensionArray._add_arithmetic_ops` and/or +:meth:`~MyExtensionArray._add_comparison_ops` to hook the operators into +your ``MyExtensionArray`` class, as follows: + +.. code-block:: python + + class MyExtensionArray(ExtensionArray, ExtensionScalarOpsMixin): + pass + + MyExtensionArray._add_arithmetic_ops() + MyExtensionArray._add_comparison_ops() + +Note that since ``pandas`` automatically calls the underlying operator on each +element one-by-one, this might not be as performant as implementing your own +version of the associated operators directly on the ``ExtensionArray``. + +.. _extending.extension.testing: + +Testing Extension Arrays +^^^^^^^^^^^^^^^^^^^^^^^^ + We provide a test suite for ensuring that your extension arrays satisfy the expected behavior. To use the test suite, you must provide several pytest fixtures and inherit from the base test class. The required fixtures are found in @@ -174,11 +222,11 @@ There are 3 constructor properties to be defined: Following table shows how ``pandas`` data structures define constructor properties by default. =========================== ======================= ============= -Property Attributes ``Series`` ``DataFrame`` +Property Attributes ``Series`` ``DataFrame`` =========================== ======================= ============= -``_constructor`` ``Series`` ``DataFrame`` -``_constructor_sliced`` ``NotImplementedError`` ``Series`` -``_constructor_expanddim`` ``DataFrame`` ``Panel`` +``_constructor`` ``Series`` ``DataFrame`` +``_constructor_sliced`` ``NotImplementedError`` ``Series`` +``_constructor_expanddim`` ``DataFrame`` ``Panel`` =========================== ======================= ============= Below example shows how to define ``SubclassedSeries`` and ``SubclassedDataFrame`` overriding constructor properties. diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 1ab67bd80a5e8..2b38e7b1d5cc3 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -10,6 +10,22 @@ New features - ``ExcelWriter`` now accepts ``mode`` as a keyword argument, enabling append to existing workbooks when using the ``openpyxl`` engine (:issue:`3441`) +.. _whatsnew_0240.enhancements.extension_array_operators + +``ExtensionArray`` operator support +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +A ``Series`` based on an ``ExtensionArray`` now supports arithmetic and comparison +operators. (:issue:`19577`). There are two approaches for providing operator support for an ``ExtensionArray``: + +1. Define each of the operators on your ``ExtensionArray`` subclass. +2. Use an operator implementation from pandas that depends on operators that are already defined + on the underlying elements (scalars) of the ``ExtensionArray``. + +See the :ref:`ExtensionArray Operator Support +<extending.extension.operator>` documentation section for details on both +ways of adding operator support. + .. _whatsnew_0240.enhancements.other: Other Enhancements diff --git a/pandas/api/extensions/__init__.py b/pandas/api/extensions/__init__.py index 3e6e192a3502c..851a63725952a 100644 --- a/pandas/api/extensions/__init__.py +++ b/pandas/api/extensions/__init__.py @@ -3,5 +3,6 @@ register_index_accessor, register_series_accessor) from pandas.core.algorithms import take # noqa -from pandas.core.arrays.base import ExtensionArray # noqa +from pandas.core.arrays.base import (ExtensionArray, # noqa + ExtensionScalarOpsMixin) from pandas.core.dtypes.dtypes import ExtensionDtype # noqa diff --git a/pandas/conftest.py b/pandas/conftest.py index ae08e0817de29..8ca90722d17f7 100644 --- a/pandas/conftest.py +++ b/pandas/conftest.py @@ -89,7 +89,8 @@ def observed(request): '__mul__', '__rmul__', '__floordiv__', '__rfloordiv__', '__truediv__', '__rtruediv__', - '__pow__', '__rpow__'] + '__pow__', '__rpow__', + '__mod__', '__rmod__'] if not PY3: _all_arithmetic_operators.extend(['__div__', '__rdiv__']) @@ -102,6 +103,22 @@ def all_arithmetic_operators(request): return request.param +@pytest.fixture(params=['__eq__', '__ne__', '__le__', + '__lt__', '__ge__', '__gt__']) +def all_compare_operators(request): + """ + Fixture for dunder names for common compare operations + + * >= + * > + * == + * != + * < + * <= + """ + return request.param + + @pytest.fixture(params=[None, 'gzip', 'bz2', 'zip', pytest.param('xz', marks=td.skip_if_no_lzma)]) def compression(request): @@ -320,20 +337,3 @@ def mock(): return importlib.import_module("unittest.mock") else: return pytest.importorskip("mock") - - -@pytest.fixture(params=['__eq__', '__ne__', '__le__', - '__lt__', '__ge__', '__gt__']) -def all_compare_operators(request): - """ - Fixture for dunder names for common compare operations - - * >= - * > - * == - * != - * < - * <= - """ - - return request.param diff --git a/pandas/core/arrays/__init__.py b/pandas/core/arrays/__init__.py index f8adcf520c15b..f57348116c195 100644 --- a/pandas/core/arrays/__init__.py +++ b/pandas/core/arrays/__init__.py @@ -1,2 +1,3 @@ -from .base import ExtensionArray # noqa +from .base import (ExtensionArray, # noqa + ExtensionScalarOpsMixin) from .categorical import Categorical # noqa diff --git a/pandas/core/arrays/base.py b/pandas/core/arrays/base.py index 30949ca6d1d6b..a572fff1c44d7 100644 --- a/pandas/core/arrays/base.py +++ b/pandas/core/arrays/base.py @@ -7,8 +7,13 @@ """ import numpy as np +import operator + from pandas.errors import AbstractMethodError from pandas.compat.numpy import function as nv +from pandas.compat import set_function_name, PY3 +from pandas.core.dtypes.common import is_list_like +from pandas.core import ops _not_implemented_message = "{} does not implement {}." @@ -610,3 +615,125 @@ def _ndarray_values(self): used for interacting with our indexers. """ return np.array(self) + + +class ExtensionOpsMixin(object): + """ + A base class for linking the operators to their dunder names + """ + @classmethod + def _add_arithmetic_ops(cls): + cls.__add__ = cls._create_arithmetic_method(operator.add) + cls.__radd__ = cls._create_arithmetic_method(ops.radd) + cls.__sub__ = cls._create_arithmetic_method(operator.sub) + cls.__rsub__ = cls._create_arithmetic_method(ops.rsub) + cls.__mul__ = cls._create_arithmetic_method(operator.mul) + cls.__rmul__ = cls._create_arithmetic_method(ops.rmul) + cls.__pow__ = cls._create_arithmetic_method(operator.pow) + cls.__rpow__ = cls._create_arithmetic_method(ops.rpow) + cls.__mod__ = cls._create_arithmetic_method(operator.mod) + cls.__rmod__ = cls._create_arithmetic_method(ops.rmod) + cls.__floordiv__ = cls._create_arithmetic_method(operator.floordiv) + cls.__rfloordiv__ = cls._create_arithmetic_method(ops.rfloordiv) + cls.__truediv__ = cls._create_arithmetic_method(operator.truediv) + cls.__rtruediv__ = cls._create_arithmetic_method(ops.rtruediv) + if not PY3: + cls.__div__ = cls._create_arithmetic_method(operator.div) + cls.__rdiv__ = cls._create_arithmetic_method(ops.rdiv) + + cls.__divmod__ = cls._create_arithmetic_method(divmod) + cls.__rdivmod__ = cls._create_arithmetic_method(ops.rdivmod) + + @classmethod + def _add_comparison_ops(cls): + cls.__eq__ = cls._create_comparison_method(operator.eq) + cls.__ne__ = cls._create_comparison_method(operator.ne) + cls.__lt__ = cls._create_comparison_method(operator.lt) + cls.__gt__ = cls._create_comparison_method(operator.gt) + cls.__le__ = cls._create_comparison_method(operator.le) + cls.__ge__ = cls._create_comparison_method(operator.ge) + + +class ExtensionScalarOpsMixin(ExtensionOpsMixin): + """A mixin for defining the arithmetic and logical operations on + an ExtensionArray class, where it is assumed that the underlying objects + have the operators already defined. + + Usage + ------ + If you have defined a subclass MyExtensionArray(ExtensionArray), then + use MyExtensionArray(ExtensionArray, ExtensionScalarOpsMixin) to + get the arithmetic operators. After the definition of MyExtensionArray, + insert the lines + + MyExtensionArray._add_arithmetic_ops() + MyExtensionArray._add_comparison_ops() + + to link the operators to your class. + """ + + @classmethod + def _create_method(cls, op, coerce_to_dtype=True): + """ + A class method that returns a method that will correspond to an + operator for an ExtensionArray subclass, by dispatching to the + relevant operator defined on the individual elements of the + ExtensionArray. + + Parameters + ---------- + op : function + An operator that takes arguments op(a, b) + coerce_to_dtype : bool + boolean indicating whether to attempt to convert + the result to the underlying ExtensionArray dtype + (default True) + + Returns + ------- + A method that can be bound to a method of a class + + Example + ------- + Given an ExtensionArray subclass called MyExtensionArray, use + + >>> __add__ = cls._create_method(operator.add) + + in the class definition of MyExtensionArray to create the operator + for addition, that will be based on the operator implementation + of the underlying elements of the ExtensionArray + + """ + + def _binop(self, other): + def convert_values(param): + if isinstance(param, ExtensionArray) or is_list_like(param): + ovalues = param + else: # Assume its an object + ovalues = [param] * len(self) + return ovalues + lvalues = self + rvalues = convert_values(other) + + # If the operator is not defined for the underlying objects, + # a TypeError should be raised + res = [op(a, b) for (a, b) in zip(lvalues, rvalues)] + + if coerce_to_dtype: + try: + res = self._from_sequence(res) + except TypeError: + pass + + return res + + op_name = ops._get_op_name(op, True) + return set_function_name(_binop, op_name, cls) + + @classmethod + def _create_arithmetic_method(cls, op): + return cls._create_method(op) + + @classmethod + def _create_comparison_method(cls, op): + return cls._create_method(op, coerce_to_dtype=False) diff --git a/pandas/core/ops.py b/pandas/core/ops.py index 540ebeee438f6..fa6d88648cc63 100644 --- a/pandas/core/ops.py +++ b/pandas/core/ops.py @@ -33,6 +33,7 @@ is_bool_dtype, is_list_like, is_scalar, + is_extension_array_dtype, _ensure_object) from pandas.core.dtypes.cast import ( maybe_upcast_putmask, find_common_type, @@ -993,6 +994,26 @@ def _construct_divmod_result(left, result, index, name, dtype): ) +def dispatch_to_extension_op(op, left, right): + """ + Assume that left or right is a Series backed by an ExtensionArray, + apply the operator defined by op. + """ + + # The op calls will raise TypeError if the op is not defined + # on the ExtensionArray + if is_extension_array_dtype(left): + res_values = op(left.values, right) + else: + # We know that left is not ExtensionArray and is Series and right is + # ExtensionArray. Want to force ExtensionArray op to get called + res_values = op(list(left.values), right.values) + + res_name = get_op_result_name(left, right) + return left._constructor(res_values, index=left.index, + name=res_name) + + def _arith_method_SERIES(cls, op, special): """ Wrapper function for Series arithmetic operations, to avoid @@ -1061,6 +1082,11 @@ def wrapper(left, right): raise TypeError("{typ} cannot perform the operation " "{op}".format(typ=type(left).__name__, op=str_rep)) + elif (is_extension_array_dtype(left) or + (is_extension_array_dtype(right) and + not is_categorical_dtype(right))): + return dispatch_to_extension_op(op, left, right) + lvalues = left.values rvalues = right if isinstance(rvalues, ABCSeries): @@ -1238,6 +1264,11 @@ def wrapper(self, other, axis=None): return self._constructor(res_values, index=self.index, name=res_name) + elif (is_extension_array_dtype(self) or + (is_extension_array_dtype(other) and + not is_categorical_dtype(other))): + return dispatch_to_extension_op(op, self, other) + elif isinstance(other, ABCSeries): # By this point we have checked that self._indexed_same(other) res_values = na_op(self.values, other.values) diff --git a/pandas/tests/extension/base/__init__.py b/pandas/tests/extension/base/__init__.py index 9da985625c4ee..640b894e2245f 100644 --- a/pandas/tests/extension/base/__init__.py +++ b/pandas/tests/extension/base/__init__.py @@ -47,6 +47,7 @@ class TestMyDtype(BaseDtypeTests): from .groupby import BaseGroupbyTests # noqa from .interface import BaseInterfaceTests # noqa from .methods import BaseMethodsTests # noqa +from .ops import BaseArithmeticOpsTests, BaseComparisonOpsTests # noqa from .missing import BaseMissingTests # noqa from .reshaping import BaseReshapingTests # noqa from .setitem import BaseSetitemTests # noqa diff --git a/pandas/tests/extension/base/ops.py b/pandas/tests/extension/base/ops.py new file mode 100644 index 0000000000000..659b9757ac1e3 --- /dev/null +++ b/pandas/tests/extension/base/ops.py @@ -0,0 +1,94 @@ +import pytest + +import operator + +import pandas as pd +from .base import BaseExtensionTests + + +class BaseOpsUtil(BaseExtensionTests): + def get_op_from_name(self, op_name): + short_opname = op_name.strip('_') + try: + op = getattr(operator, short_opname) + except AttributeError: + # Assume it is the reverse operator + rop = getattr(operator, short_opname[1:]) + op = lambda x, y: rop(y, x) + + return op + + def check_opname(self, s, op_name, other, exc=NotImplementedError): + op = self.get_op_from_name(op_name) + + self._check_op(s, op, other, exc) + + def _check_op(self, s, op, other, exc=NotImplementedError): + if exc is None: + result = op(s, other) + expected = s.combine(other, op) + self.assert_series_equal(result, expected) + else: + with pytest.raises(exc): + op(s, other) + + +class BaseArithmeticOpsTests(BaseOpsUtil): + """Various Series and DataFrame arithmetic ops methods.""" + + def test_arith_scalar(self, data, all_arithmetic_operators): + # scalar + op_name = all_arithmetic_operators + s = pd.Series(data) + self.check_opname(s, op_name, s.iloc[0], exc=TypeError) + + def test_arith_array(self, data, all_arithmetic_operators): + # ndarray & other series + op_name = all_arithmetic_operators + s = pd.Series(data) + self.check_opname(s, op_name, [s.iloc[0]] * len(s), exc=TypeError) + + def test_divmod(self, data): + s = pd.Series(data) + self._check_op(s, divmod, 1, exc=TypeError) + self._check_op(1, divmod, s, exc=TypeError) + + def test_error(self, data, all_arithmetic_operators): + # invalid ops + op_name = all_arithmetic_operators + with pytest.raises(AttributeError): + getattr(data, op_name) + + +class BaseComparisonOpsTests(BaseOpsUtil): + """Various Series and DataFrame comparison ops methods.""" + + def _compare_other(self, s, data, op_name, other): + op = self.get_op_from_name(op_name) + if op_name == '__eq__': + assert getattr(data, op_name)(other) is NotImplemented + assert not op(s, other).all() + elif op_name == '__ne__': + assert getattr(data, op_name)(other) is NotImplemented + assert op(s, other).all() + + else: + + # array + assert getattr(data, op_name)(other) is NotImplemented + + # series + s = pd.Series(data) + with pytest.raises(TypeError): + op(s, other) + + def test_compare_scalar(self, data, all_compare_operators): + op_name = all_compare_operators + s = pd.Series(data) + self._compare_other(s, data, op_name, 0) + + def test_compare_array(self, data, all_compare_operators): + op_name = all_compare_operators + s = pd.Series(data) + other = [0] * len(data) + self._compare_other(s, data, op_name, other) diff --git a/pandas/tests/extension/category/test_categorical.py b/pandas/tests/extension/category/test_categorical.py index 61fdb8454b542..ae0d72c204d13 100644 --- a/pandas/tests/extension/category/test_categorical.py +++ b/pandas/tests/extension/category/test_categorical.py @@ -183,3 +183,29 @@ def test_combine_add(self, data_repeated): class TestCasting(base.BaseCastingTests): pass + + +class TestArithmeticOps(base.BaseArithmeticOpsTests): + + def test_arith_scalar(self, data, all_arithmetic_operators): + + op_name = all_arithmetic_operators + if op_name != '__rmod__': + super(TestArithmeticOps, self).test_arith_scalar(data, op_name) + else: + pytest.skip('rmod never called when string is first argument') + + +class TestComparisonOps(base.BaseComparisonOpsTests): + + def _compare_other(self, s, data, op_name, other): + op = self.get_op_from_name(op_name) + if op_name == '__eq__': + assert not op(data, other).all() + + elif op_name == '__ne__': + assert op(data, other).all() + + else: + with pytest.raises(TypeError): + op(data, other) diff --git a/pandas/tests/extension/decimal/array.py b/pandas/tests/extension/decimal/array.py index cc6fadc483d5e..3f2f24cd26af0 100644 --- a/pandas/tests/extension/decimal/array.py +++ b/pandas/tests/extension/decimal/array.py @@ -6,7 +6,8 @@ import numpy as np import pandas as pd -from pandas.core.arrays import ExtensionArray +from pandas.core.arrays import (ExtensionArray, + ExtensionScalarOpsMixin) from pandas.core.dtypes.base import ExtensionDtype @@ -24,13 +25,14 @@ def construct_from_string(cls, string): "'{}'".format(cls, string)) -class DecimalArray(ExtensionArray): +class DecimalArray(ExtensionArray, ExtensionScalarOpsMixin): dtype = DecimalDtype() def __init__(self, values): for val in values: if not isinstance(val, self.dtype.type): - raise TypeError + raise TypeError("All values must be of type " + + str(self.dtype.type)) values = np.asarray(values, dtype=object) self._data = values @@ -103,5 +105,9 @@ def _concat_same_type(cls, to_concat): return cls(np.concatenate([x._data for x in to_concat])) +DecimalArray._add_arithmetic_ops() +DecimalArray._add_comparison_ops() + + def make_data(): return [decimal.Decimal(random.random()) for _ in range(100)] diff --git a/pandas/tests/extension/decimal/test_decimal.py b/pandas/tests/extension/decimal/test_decimal.py index f74b4d7e94f11..45ee7f227c4f0 100644 --- a/pandas/tests/extension/decimal/test_decimal.py +++ b/pandas/tests/extension/decimal/test_decimal.py @@ -191,3 +191,64 @@ def test_dataframe_constructor_with_different_dtype_raises(): xpr = "Cannot coerce extension array to dtype 'int64'. " with tm.assert_raises_regex(ValueError, xpr): pd.DataFrame({"A": arr}, dtype='int64') + + +class TestArithmeticOps(BaseDecimal, base.BaseArithmeticOpsTests): + + def check_opname(self, s, op_name, other, exc=None): + super(TestArithmeticOps, self).check_opname(s, op_name, + other, exc=None) + + def test_arith_array(self, data, all_arithmetic_operators): + op_name = all_arithmetic_operators + s = pd.Series(data) + + context = decimal.getcontext() + divbyzerotrap = context.traps[decimal.DivisionByZero] + invalidoptrap = context.traps[decimal.InvalidOperation] + context.traps[decimal.DivisionByZero] = 0 + context.traps[decimal.InvalidOperation] = 0 + + # Decimal supports ops with int, but not float + other = pd.Series([int(d * 100) for d in data]) + self.check_opname(s, op_name, other) + + if "mod" not in op_name: + self.check_opname(s, op_name, s * 2) + + self.check_opname(s, op_name, 0) + self.check_opname(s, op_name, 5) + context.traps[decimal.DivisionByZero] = divbyzerotrap + context.traps[decimal.InvalidOperation] = invalidoptrap + + @pytest.mark.skip(reason="divmod not appropriate for decimal") + def test_divmod(self, data): + pass + + def test_error(self): + pass + + +class TestComparisonOps(BaseDecimal, base.BaseComparisonOpsTests): + + def check_opname(self, s, op_name, other, exc=None): + super(TestComparisonOps, self).check_opname(s, op_name, + other, exc=None) + + def _compare_other(self, s, data, op_name, other): + self.check_opname(s, op_name, other) + + def test_compare_scalar(self, data, all_compare_operators): + op_name = all_compare_operators + s = pd.Series(data) + self._compare_other(s, data, op_name, 0.5) + + def test_compare_array(self, data, all_compare_operators): + op_name = all_compare_operators + s = pd.Series(data) + + alter = np.random.choice([-1, 0, 1], len(data)) + # Randomly double, halve or keep same value + other = pd.Series(data) * [decimal.Decimal(pow(2.0, i)) + for i in alter] + self._compare_other(s, data, op_name, other) diff --git a/pandas/tests/extension/json/array.py b/pandas/tests/extension/json/array.py index 10be7836cb8d7..d3043bf0852d2 100644 --- a/pandas/tests/extension/json/array.py +++ b/pandas/tests/extension/json/array.py @@ -47,7 +47,8 @@ class JSONArray(ExtensionArray): def __init__(self, values): for val in values: if not isinstance(val, self.dtype.type): - raise TypeError + raise TypeError("All values must be of type " + + str(self.dtype.type)) self.data = values # Some aliases for common attribute names to ensure pandas supports diff --git a/pandas/tests/extension/json/test_json.py b/pandas/tests/extension/json/test_json.py index 85a282ae4007f..268134dc8c333 100644 --- a/pandas/tests/extension/json/test_json.py +++ b/pandas/tests/extension/json/test_json.py @@ -238,3 +238,12 @@ def test_groupby_extension_agg(self, as_index, data_for_grouping): super(TestGroupby, self).test_groupby_extension_agg( as_index, data_for_grouping ) + + +class TestArithmeticOps(BaseJSON, base.BaseArithmeticOpsTests): + def test_error(self, data, all_arithmetic_operators): + pass + + +class TestComparisonOps(BaseJSON, base.BaseComparisonOpsTests): + pass diff --git a/pandas/util/testing.py b/pandas/util/testing.py index a5afcb6915034..11e9942079aad 100644 --- a/pandas/util/testing.py +++ b/pandas/util/testing.py @@ -29,7 +29,8 @@ is_categorical_dtype, is_interval_dtype, is_sequence, - is_list_like) + is_list_like, + is_extension_array_dtype) from pandas.io.formats.printing import pprint_thing from pandas.core.algorithms import take_1d import pandas.core.common as com @@ -1243,6 +1244,10 @@ def assert_series_equal(left, right, check_dtype=True, right = pd.IntervalIndex(right) assert_index_equal(left, right, obj='{obj}.index'.format(obj=obj)) + elif (is_extension_array_dtype(left) and not is_categorical_dtype(left) and + is_extension_array_dtype(right) and not is_categorical_dtype(right)): + return assert_extension_array_equal(left.values, right.values) + else: _testing.assert_almost_equal(left.get_values(), right.get_values(), check_less_precise=check_less_precise,
- [x] closes #19577 - [x] tests added / passed - tests/extension/decimal/test_decimal.py:TestOperator - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry - in v0.24.0 Based on a discussion in #20889, this provides a mixin (via a mixin factory) that provides a default implementation of operators for `ExtensionArray` using the operators defined on the underlying `ExtensionDtype` . Tested using the `DecimalArray` implementation. NOTE: This requires #21183 ~~and #21260~~ to be accepted into master, and so the changes from those pull requests are included here. Comments from @jorisvandenbossche @TomAugspurger @jreback @jbrockmendel are welcome.
https://api.github.com/repos/pandas-dev/pandas/pulls/21261
2018-05-30T18:32:47Z
2018-06-29T02:01:01Z
2018-06-29T02:01:01Z
2018-07-02T14:39:19Z
BUG: Series.get() with ExtensionArray and integer index
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 1ab67bd80a5e8..76d08e84a6efd 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -270,6 +270,7 @@ Reshaping ExtensionArray ^^^^^^^^^^^^^^ +- Bug in :meth:`Series.get` for ``Series`` using ``ExtensionArray`` and integer index (:issue:`21257`) - :meth:`Series.combine()` works correctly with :class:`~pandas.api.extensions.ExtensionArray` inside of :class:`Series` (:issue:`20825`) - :meth:`Series.combine()` with scalar argument now works for any function type (:issue:`21248`) - diff --git a/pandas/core/indexes/base.py b/pandas/core/indexes/base.py index 122f8662abb61..ba60d10099948 100644 --- a/pandas/core/indexes/base.py +++ b/pandas/core/indexes/base.py @@ -2988,16 +2988,20 @@ def get_value(self, series, key): # use this, e.g. DatetimeIndex s = getattr(series, '_values', None) if isinstance(s, (ExtensionArray, Index)) and is_scalar(key): - # GH 20825 + # GH 20882, 21257 # Unify Index and ExtensionArray treatment # First try to convert the key to a location - # If that fails, see if key is an integer, and + # If that fails, raise a KeyError if an integer + # index, otherwise, see if key is an integer, and # try that try: iloc = self.get_loc(key) return s[iloc] except KeyError: - if is_integer(key): + if (len(self) > 0 and + self.inferred_type in ['integer', 'boolean']): + raise + elif is_integer(key): return s[key] s = com._values_from_object(series) diff --git a/pandas/tests/extension/base/getitem.py b/pandas/tests/extension/base/getitem.py index 883b3f5588aef..e9df49780f119 100644 --- a/pandas/tests/extension/base/getitem.py +++ b/pandas/tests/extension/base/getitem.py @@ -130,7 +130,7 @@ def test_get(self, data): expected = s.iloc[[0, 1]] self.assert_series_equal(result, expected) - assert s.get(-1) == s.iloc[-1] + assert s.get(-1) is None assert s.get(s.index.max() + 1) is None s = pd.Series(data[:6], index=list('abcdef')) @@ -147,6 +147,11 @@ def test_get(self, data): assert s.get(-1) == s.iloc[-1] assert s.get(len(s)) is None + # GH 21257 + s = pd.Series(data) + s2 = s[::2] + assert s2.get(1) is None + def test_take_sequence(self, data): result = pd.Series(data)[[0, 1, 3]] assert result.iloc[0] == data[0] diff --git a/pandas/tests/series/indexing/test_indexing.py b/pandas/tests/series/indexing/test_indexing.py index 8571fbc10e9bb..25bc394e312a0 100644 --- a/pandas/tests/series/indexing/test_indexing.py +++ b/pandas/tests/series/indexing/test_indexing.py @@ -187,6 +187,49 @@ def test_getitem_box_float64(test_data): assert isinstance(value, np.float64) +@pytest.mark.parametrize( + 'arr', + [ + np.random.randn(10), + tm.makeDateIndex(10, name='a').tz_localize( + tz='US/Eastern'), + ]) +def test_get(arr): + # GH 21260 + s = Series(arr, index=[2 * i for i in range(len(arr))]) + assert s.get(4) == s.iloc[2] + + result = s.get([4, 6]) + expected = s.iloc[[2, 3]] + tm.assert_series_equal(result, expected) + + result = s.get(slice(2)) + expected = s.iloc[[0, 1]] + tm.assert_series_equal(result, expected) + + assert s.get(-1) is None + assert s.get(s.index.max() + 1) is None + + s = Series(arr[:6], index=list('abcdef')) + assert s.get('c') == s.iloc[2] + + result = s.get(slice('b', 'd')) + expected = s.iloc[[1, 2, 3]] + tm.assert_series_equal(result, expected) + + result = s.get('Z') + assert result is None + + assert s.get(4) == s.iloc[4] + assert s.get(-1) == s.iloc[-1] + assert s.get(len(s)) is None + + # GH 21257 + s = pd.Series(arr) + s2 = s[::2] + assert s2.get(1) is None + + def test_series_box_timestamp(): rng = pd.date_range('20090415', '20090519', freq='B') ser = Series(rng)
- [x] closes #21257 - [x] tests added / passed - added example in tests/extension/base/getitem.py:test_get() - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry - Put this in 0.23.1 for now
https://api.github.com/repos/pandas-dev/pandas/pulls/21260
2018-05-30T17:35:51Z
2018-06-29T00:47:09Z
2018-06-29T00:47:09Z
2018-06-29T13:44:00Z
ENH: Add support for tablewise application of style.background_gradient with axis=None
diff --git a/doc/source/whatsnew/v0.24.0.txt b/doc/source/whatsnew/v0.24.0.txt index 034a56b2ac0cb..c042275f00a17 100644 --- a/doc/source/whatsnew/v0.24.0.txt +++ b/doc/source/whatsnew/v0.24.0.txt @@ -425,6 +425,7 @@ Other - :meth: `~pandas.io.formats.style.Styler.background_gradient` now takes a ``text_color_threshold`` parameter to automatically lighten the text color based on the luminance of the background color. This improves readability with dark background colors without the need to limit the background colormap range. (:issue:`21258`) - Require at least 0.28.2 version of ``cython`` to support read-only memoryviews (:issue:`21688`) +- :meth: `~pandas.io.formats.style.Styler.background_gradient` now also supports tablewise application (in addition to rowwise and columnwise) with ``axis=None`` (:issue:`15204`) - - - diff --git a/pandas/io/formats/style.py b/pandas/io/formats/style.py index 62c2ea8ab9273..808b6979b235e 100644 --- a/pandas/io/formats/style.py +++ b/pandas/io/formats/style.py @@ -913,21 +913,22 @@ def background_gradient(self, cmap='PuBu', low=0, high=0, axis=0, def _background_gradient(s, cmap='PuBu', low=0, high=0, text_color_threshold=0.408): """Color background in a range according to the data.""" + if (not isinstance(text_color_threshold, (float, int)) or + not 0 <= text_color_threshold <= 1): + msg = "`text_color_threshold` must be a value from 0 to 1." + raise ValueError(msg) + with _mpl(Styler.background_gradient) as (plt, colors): - rng = s.max() - s.min() + smin = s.values.min() + smax = s.values.max() + rng = smax - smin # extend lower / upper bounds, compresses color range - norm = colors.Normalize(s.min() - (rng * low), - s.max() + (rng * high)) - # matplotlib modifies inplace? + norm = colors.Normalize(smin - (rng * low), smax + (rng * high)) + # matplotlib colors.Normalize modifies inplace? # https://github.com/matplotlib/matplotlib/issues/5427 - normed = norm(s.values) - c = [colors.rgb2hex(x) for x in plt.cm.get_cmap(cmap)(normed)] - if (not isinstance(text_color_threshold, (float, int)) or - not 0 <= text_color_threshold <= 1): - msg = "`text_color_threshold` must be a value from 0 to 1." - raise ValueError(msg) + rgbas = plt.cm.get_cmap(cmap)(norm(s.values)) - def relative_luminance(color): + def relative_luminance(rgba): """ Calculate relative luminance of a color. @@ -936,25 +937,33 @@ def relative_luminance(color): Parameters ---------- - color : matplotlib color - Hex code, rgb-tuple, or HTML color name. + color : rgb or rgba tuple Returns ------- float The relative luminance as a value from 0 to 1 """ - rgb = colors.colorConverter.to_rgba_array(color)[:, :3] - rgb = np.where(rgb <= .03928, rgb / 12.92, - ((rgb + .055) / 1.055) ** 2.4) - lum = rgb.dot([.2126, .7152, .0722]) - return lum.item() - - text_colors = ['#f1f1f1' if relative_luminance(x) < - text_color_threshold else '#000000' for x in c] - - return ['background-color: {color};color: {tc}'.format( - color=color, tc=tc) for color, tc in zip(c, text_colors)] + r, g, b = ( + x / 12.92 if x <= 0.03928 else ((x + 0.055) / 1.055 ** 2.4) + for x in rgba[:3] + ) + return 0.2126 * r + 0.7152 * g + 0.0722 * b + + def css(rgba): + dark = relative_luminance(rgba) < text_color_threshold + text_color = '#f1f1f1' if dark else '#000000' + return 'background-color: {b};color: {c};'.format( + b=colors.rgb2hex(rgba), c=text_color + ) + + if s.ndim == 1: + return [css(rgba) for rgba in rgbas] + else: + return pd.DataFrame( + [[css(rgba) for rgba in row] for row in rgbas], + index=s.index, columns=s.columns + ) def set_properties(self, subset=None, **kwargs): """ diff --git a/pandas/tests/io/formats/test_style.py b/pandas/tests/io/formats/test_style.py index b355cda8df1bd..293dadd19031d 100644 --- a/pandas/tests/io/formats/test_style.py +++ b/pandas/tests/io/formats/test_style.py @@ -1056,6 +1056,34 @@ def test_text_color_threshold_raises(self, text_color_threshold): df.style.background_gradient( text_color_threshold=text_color_threshold)._compute() + @td.skip_if_no_mpl + def test_background_gradient_axis(self): + df = pd.DataFrame([[1, 2], [2, 4]], columns=['A', 'B']) + + low = ['background-color: #f7fbff', 'color: #000000'] + high = ['background-color: #08306b', 'color: #f1f1f1'] + mid = ['background-color: #abd0e6', 'color: #000000'] + result = df.style.background_gradient(cmap='Blues', + axis=0)._compute().ctx + assert result[(0, 0)] == low + assert result[(0, 1)] == low + assert result[(1, 0)] == high + assert result[(1, 1)] == high + + result = df.style.background_gradient(cmap='Blues', + axis=1)._compute().ctx + assert result[(0, 0)] == low + assert result[(0, 1)] == high + assert result[(1, 0)] == low + assert result[(1, 1)] == high + + result = df.style.background_gradient(cmap='Blues', + axis=None)._compute().ctx + assert result[(0, 0)] == low + assert result[(0, 1)] == mid + assert result[(1, 0)] == mid + assert result[(1, 1)] == high + def test_block_names(): # catch accidental removal of a block
- [x] closes #15204 - [x] tests added / passed - [x] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [x] whatsnew entry
https://api.github.com/repos/pandas-dev/pandas/pulls/21259
2018-05-30T15:58:02Z
2018-07-12T12:38:38Z
2018-07-12T12:38:38Z
2018-07-12T12:38:40Z
BUG: Allow IntervalIndex to be constructed from categorical data with appropriate dtype
diff --git a/doc/source/whatsnew/v0.23.1.txt b/doc/source/whatsnew/v0.23.1.txt index 35484e34ee9eb..5dd2490dd5b39 100644 --- a/doc/source/whatsnew/v0.23.1.txt +++ b/doc/source/whatsnew/v0.23.1.txt @@ -81,6 +81,7 @@ Indexing - Bug in :meth:`Series.reset_index` where appropriate error was not raised with an invalid level name (:issue:`20925`) - Bug in :func:`interval_range` when ``start``/``periods`` or ``end``/``periods`` are specified with float ``start`` or ``end`` (:issue:`21161`) - Bug in :meth:`MultiIndex.set_names` where error raised for a ``MultiIndex`` with ``nlevels == 1`` (:issue:`21149`) +- Bug in :class:`IntervalIndex` constructors where creating an ``IntervalIndex`` from categorical data was not fully supported (:issue:`21243`, issue:`21253`) - I/O diff --git a/pandas/core/indexes/interval.py b/pandas/core/indexes/interval.py index 8f8d8760583ce..eb9d7efc06c27 100644 --- a/pandas/core/indexes/interval.py +++ b/pandas/core/indexes/interval.py @@ -112,6 +112,10 @@ def maybe_convert_platform_interval(values): ------- array """ + if is_categorical_dtype(values): + # GH 21243/21253 + values = np.array(values) + if isinstance(values, (list, tuple)) and len(values) == 0: # GH 19016 # empty lists/tuples get object dtype by default, but this is not diff --git a/pandas/tests/indexes/interval/test_construction.py b/pandas/tests/indexes/interval/test_construction.py index 5fdf92dcb2044..b1711c3444586 100644 --- a/pandas/tests/indexes/interval/test_construction.py +++ b/pandas/tests/indexes/interval/test_construction.py @@ -6,8 +6,9 @@ from pandas import ( Interval, IntervalIndex, Index, Int64Index, Float64Index, Categorical, - date_range, timedelta_range, period_range, notna) + CategoricalIndex, date_range, timedelta_range, period_range, notna) from pandas.compat import lzip +from pandas.core.dtypes.common import is_categorical_dtype from pandas.core.dtypes.dtypes import IntervalDtype import pandas.core.common as com import pandas.util.testing as tm @@ -111,6 +112,22 @@ def test_constructor_string(self, constructor, breaks): with tm.assert_raises_regex(TypeError, msg): constructor(**self.get_kwargs_from_breaks(breaks)) + @pytest.mark.parametrize('cat_constructor', [ + Categorical, CategoricalIndex]) + def test_constructor_categorical_valid(self, constructor, cat_constructor): + # GH 21243/21253 + if isinstance(constructor, partial) and constructor.func is Index: + # Index is defined to create CategoricalIndex from categorical data + pytest.skip() + + breaks = np.arange(10, dtype='int64') + expected = IntervalIndex.from_breaks(breaks) + + cat_breaks = cat_constructor(breaks) + result_kwargs = self.get_kwargs_from_breaks(cat_breaks) + result = constructor(**result_kwargs) + tm.assert_index_equal(result, expected) + def test_generic_errors(self, constructor): # filler input data to be used when supplying invalid kwargs filler = self.get_kwargs_from_breaks(range(10)) @@ -238,6 +255,8 @@ def get_kwargs_from_breaks(self, breaks, closed='right'): tuples = lzip(breaks[:-1], breaks[1:]) if isinstance(breaks, (list, tuple)): return {'data': tuples} + elif is_categorical_dtype(breaks): + return {'data': breaks._constructor(tuples)} return {'data': com._asarray_tuplesafe(tuples)} def test_constructor_errors(self): @@ -286,6 +305,8 @@ def get_kwargs_from_breaks(self, breaks, closed='right'): if isinstance(breaks, list): return {'data': ivs} + elif is_categorical_dtype(breaks): + return {'data': breaks._constructor(ivs)} return {'data': np.array(ivs, dtype=object)} def test_generic_errors(self, constructor):
- [X] closes #21243 - [X] closes #21253 - [X] tests added / passed - [X] passes `git diff upstream/master -u -- "*.py" | flake8 --diff` - [X] whatsnew entry Added this to 0.23.1 since it's a regression and the fix is a minor change outside the `IntervalIndex` class. Not opposed to pushing to 0.24.0 if backporting this could be problematic.
https://api.github.com/repos/pandas-dev/pandas/pulls/21254
2018-05-30T06:49:31Z
2018-06-04T21:28:52Z
2018-06-04T21:28:51Z
2018-06-22T17:14:31Z